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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
029fd7c4aabe1ebcfd683db2b9668d059f5f4785 | [
"B = []\nlength = len(A)\nfor i in range(length):\n B.append(int(str(A[i])[-k]))\nreturn B",
"C = []\nB = _deepcopy(A)\nk = 27\nfor i in range(k):\n C.append(0)\nlength = len(A)\nfor j in range(length):\n C[A[j]] = C[A[j]] + 1\nfor i in range(1, k):\n C[i] = C[i] + C[i - 1]\nfor i in range(length):\n ... | <|body_start_0|>
B = []
length = len(A)
for i in range(length):
B.append(int(str(A[i])[-k]))
return B
<|end_body_0|>
<|body_start_1|>
C = []
B = _deepcopy(A)
k = 27
for i in range(k):
C.append(0)
length = len(A)
for... | chpater8.3 note and function | Chapter8_3 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter8_3:
"""chpater8.3 note and function"""
def getarraystr_subarray(self, A, k):
"""取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarraystr_subarray(['ABC', 'DEF', 'OPQ'], 1) ['C', 'F', 'Q'] `... | stack_v2_sparse_classes_75kplus_train_070900 | 18,569 | permissive | [
{
"docstring": "取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarraystr_subarray(['ABC', 'DEF', 'OPQ'], 1) ['C', 'F', 'Q'] ```",
"name": "getarraystr_subarray",
"signature": "def getarraystr_subarray(self, A, k)"
}... | 4 | stack_v2_sparse_classes_30k_train_051003 | Implement the Python class `Chapter8_3` described below.
Class description:
chpater8.3 note and function
Method signatures and docstrings:
- def getarraystr_subarray(self, A, k): 取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarra... | Implement the Python class `Chapter8_3` described below.
Class description:
chpater8.3 note and function
Method signatures and docstrings:
- def getarraystr_subarray(self, A, k): 取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarra... | 33662f46dc346203b220d7481d1a4439feda05d2 | <|skeleton|>
class Chapter8_3:
"""chpater8.3 note and function"""
def getarraystr_subarray(self, A, k):
"""取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarraystr_subarray(['ABC', 'DEF', 'OPQ'], 1) ['C', 'F', 'Q'] `... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chapter8_3:
"""chpater8.3 note and function"""
def getarraystr_subarray(self, A, k):
"""取一个数组中每个元素第k位构成的子数组 Args === `A` : 待取子数组的数组 `k` : 第1位是最低位,第d位是最高位 Return === `subarray` : 取好的子数组 Example === ```python Chapter8_3().getarraystr_subarray(['ABC', 'DEF', 'OPQ'], 1) ['C', 'F', 'Q'] ```"""
... | the_stack_v2_python_sparse | src/chapter8/chapter8note.py | HideLakitu/IntroductionToAlgorithm.Python | train | 1 |
81621b2599250408ebc71601e8ea7be65f960e39 | [
"self.assertEqual(list(ds.keys()), [])\nself.assertEqual(pipes.cdp_name(), None)\nself.assert_(not hasattr(ds, 'y'))\nself.state.load_state(state='basic_single_pipe', dir=status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'saved_states')\ndp = pipes.get_pipe('orig')\nself.assertEqual(list(ds.key... | <|body_start_0|>
self.assertEqual(list(ds.keys()), [])
self.assertEqual(pipes.cdp_name(), None)
self.assert_(not hasattr(ds, 'y'))
self.state.load_state(state='basic_single_pipe', dir=status.install_path + sep + 'test_suite' + sep + 'shared_data' + sep + 'saved_states')
dp = pipe... | Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests. | State_base_class | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State_base_class:
"""Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests."""
def test_load(self):
"""The unpickling and restoration of the relax data storage singleton. This tests the normal operation o... | stack_v2_sparse_classes_75kplus_train_070901 | 5,594 | no_license | [
{
"docstring": "The unpickling and restoration of the relax data storage singleton. This tests the normal operation of the pipe_control.state.load() function.",
"name": "test_load",
"signature": "def test_load(self)"
},
{
"docstring": "The modification of an unpickled and restored relax data sto... | 4 | null | Implement the Python class `State_base_class` described below.
Class description:
Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests.
Method signatures and docstrings:
- def test_load(self): The unpickling and restoration of the relax ... | Implement the Python class `State_base_class` described below.
Class description:
Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests.
Method signatures and docstrings:
- def test_load(self): The unpickling and restoration of the relax ... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class State_base_class:
"""Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests."""
def test_load(self):
"""The unpickling and restoration of the relax data storage singleton. This tests the normal operation o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class State_base_class:
"""Base class for the tests of both the 'prompt.state' and 'pipe_control.state' modules. This base class also contains shared unit tests."""
def test_load(self):
"""The unpickling and restoration of the relax data storage singleton. This tests the normal operation of the pipe_co... | the_stack_v2_python_sparse | test_suite/unit_tests/state_testing_base.py | jlec/relax | train | 4 |
b7aa8e73f6ca0ebd66b658cc77d890a7948c9b56 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ToneInfo()",
"from .tone import Tone\nfrom .tone import Tone\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', n.get_str_value()), 'sequenceId': lambda n: setattr(self, 'sequence_id', n.g... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ToneInfo()
<|end_body_0|>
<|body_start_1|>
from .tone import Tone
from .tone import Tone
fields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata... | ToneInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ToneInfo... | stack_v2_sparse_classes_75kplus_train_070902 | 2,754 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ToneInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | stack_v2_sparse_classes_30k_train_027321 | Implement the Python class `ToneInfo` described below.
Class description:
Implement the ToneInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | Implement the Python class `ToneInfo` described below.
Class description:
Implement the ToneInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ToneInfo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ToneInfo"""
if... | the_stack_v2_python_sparse | msgraph/generated/models/tone_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d0285c9c4dbfe41b8d024e515e82e296ffbd0687 | [
"self.user = user\nself.block_producer = block_producer\nself.block_producer_like = block_producer_like",
"if not self.user.does_exist_by_email(email=user_email):\n raise UserWithSpecifiedEmailAddressDoesNotExistError\nif not self.block_producer.does_exist(identifier=block_producer_id):\n raise BlockProduce... | <|body_start_0|>
self.user = user
self.block_producer = block_producer
self.block_producer_like = block_producer_like
<|end_body_0|>
<|body_start_1|>
if not self.user.does_exist_by_email(email=user_email):
raise UserWithSpecifiedEmailAddressDoesNotExistError
if not s... | Liking block producer implementation. | LikeBlockProducer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikeBlockProducer:
"""Liking block producer implementation."""
def __init__(self, user, block_producer, block_producer_like):
"""Constructor."""
<|body_0|>
def do(self, user_email, block_producer_id):
"""To like a block producer."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_070903 | 8,206 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, user, block_producer, block_producer_like)"
},
{
"docstring": "To like a block producer.",
"name": "do",
"signature": "def do(self, user_email, block_producer_id)"
}
] | 2 | null | Implement the Python class `LikeBlockProducer` described below.
Class description:
Liking block producer implementation.
Method signatures and docstrings:
- def __init__(self, user, block_producer, block_producer_like): Constructor.
- def do(self, user_email, block_producer_id): To like a block producer. | Implement the Python class `LikeBlockProducer` described below.
Class description:
Liking block producer implementation.
Method signatures and docstrings:
- def __init__(self, user, block_producer, block_producer_like): Constructor.
- def do(self, user_email, block_producer_id): To like a block producer.
<|skeleton|... | 81034cc8f92989dbf2e0df79befdd8d83442dd3a | <|skeleton|>
class LikeBlockProducer:
"""Liking block producer implementation."""
def __init__(self, user, block_producer, block_producer_like):
"""Constructor."""
<|body_0|>
def do(self, user_email, block_producer_id):
"""To like a block producer."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LikeBlockProducer:
"""Liking block producer implementation."""
def __init__(self, user, block_producer, block_producer_like):
"""Constructor."""
self.user = user
self.block_producer = block_producer
self.block_producer_like = block_producer_like
def do(self, user_emai... | the_stack_v2_python_sparse | directory/block_producer/domain/objects.py | Remmeauth/block-producers-directory-back | train | 0 |
bde595c7e9a4ee5dc25e735b39f55e4f4d7f7ffa | [
"super(ModelBrowser, self).__init__(parent=parent)\nself.path_ = path\nself.width_ = width\nself.height_ = height\nself.inc = 0\nself.roty = 0\nself.cam = Camera('PERSPECTIVE')\npass",
"self.model = Model()\nself.model.load_model(self.path_)\nself.cam.setEye(0, 0, -60)\nself.cam.on()\npass",
"glPushMatrix()\ngl... | <|body_start_0|>
super(ModelBrowser, self).__init__(parent=parent)
self.path_ = path
self.width_ = width
self.height_ = height
self.inc = 0
self.roty = 0
self.cam = Camera('PERSPECTIVE')
pass
<|end_body_0|>
<|body_start_1|>
self.model = Model()
... | ModelBrowser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
<|body_0|>
def initGL(self):
"""Overloaded function from GLWidget"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070904 | 1,827 | no_license | [
{
"docstring": "@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen",
"name": "__init__",
"signature": "def __init__(self, path, width, height, parent=None)"
},
{
"docstring": "Overloaded function from GLWidget",
"name": "initGL",
"signat... | 4 | stack_v2_sparse_classes_30k_train_012315 | Implement the Python class `ModelBrowser` described below.
Class description:
Implement the ModelBrowser class.
Method signatures and docstrings:
- def __init__(self, path, width, height, parent=None): @param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen
- def initGL(s... | Implement the Python class `ModelBrowser` described below.
Class description:
Implement the ModelBrowser class.
Method signatures and docstrings:
- def __init__(self, path, width, height, parent=None): @param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen
- def initGL(s... | ef3737087d25248e3f924e7d66bb4ef459745956 | <|skeleton|>
class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
<|body_0|>
def initGL(self):
"""Overloaded function from GLWidget"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelBrowser:
def __init__(self, path, width, height, parent=None):
"""@param path : Path to a model @param width : Width of the Screen @param height : Height of the Screen"""
super(ModelBrowser, self).__init__(parent=parent)
self.path_ = path
self.width_ = width
self.h... | the_stack_v2_python_sparse | tutorials/model_browser.py | pchalas1/libWall | train | 0 | |
188b0cb5ef96b2095058eb78345236afc3b1d73b | [
"self.R_mean = R_mean\nself.G_mean = G_mean\nself.B_mean = B_mean",
"B, G, R = cv2.split(image.astype('float32'))\nR -= self.R_mean\nG -= self.G_mean\nB -= self.B_mean\nreturn cv2.merge([B, G, R])"
] | <|body_start_0|>
self.R_mean = R_mean
self.G_mean = G_mean
self.B_mean = B_mean
<|end_body_0|>
<|body_start_1|>
B, G, R = cv2.split(image.astype('float32'))
R -= self.R_mean
G -= self.G_mean
B -= self.B_mean
return cv2.merge([B, G, R])
<|end_body_1|>
| SubtractMeansPreprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubtractMeansPreprocessor:
def __init__(self, R_mean, G_mean, B_mean):
"""Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Green value across the entire data set :param B_mean: mean Blue valie across the entire data set"""
<|body_0... | stack_v2_sparse_classes_75kplus_train_070905 | 846 | no_license | [
{
"docstring": "Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Green value across the entire data set :param B_mean: mean Blue valie across the entire data set",
"name": "__init__",
"signature": "def __init__(self, R_mean, G_mean, B_mean)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_002596 | Implement the Python class `SubtractMeansPreprocessor` described below.
Class description:
Implement the SubtractMeansPreprocessor class.
Method signatures and docstrings:
- def __init__(self, R_mean, G_mean, B_mean): Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Gr... | Implement the Python class `SubtractMeansPreprocessor` described below.
Class description:
Implement the SubtractMeansPreprocessor class.
Method signatures and docstrings:
- def __init__(self, R_mean, G_mean, B_mean): Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Gr... | e9f2010715fa06f50095d05684617c86e18ca661 | <|skeleton|>
class SubtractMeansPreprocessor:
def __init__(self, R_mean, G_mean, B_mean):
"""Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Green value across the entire data set :param B_mean: mean Blue valie across the entire data set"""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubtractMeansPreprocessor:
def __init__(self, R_mean, G_mean, B_mean):
"""Initialise the class :param R_mean: mean Red value across the entire data set :param G_mean: mean Green value across the entire data set :param B_mean: mean Blue valie across the entire data set"""
self.R_mean = R_mean
... | the_stack_v2_python_sparse | dltoolkit/preprocess/subtractmeans.py | GeoffBreemer/DLToolkit | train | 2 | |
c5e0b917a467e89cf8010986f5686304605e5bf3 | [
"df['gainAhead'] = self.gainAhead(df.Close)\ndf['beLong'] = np.where(df.gainAhead > beLongThreshold, 1, -1)\nreturn df",
"nrows = p.shape[0]\ng = np.zeros(nrows)\nfor i in range(0, nrows - 1):\n g[i] = (p[i + 1] - p[i]) / p[i]\n if abs(g[i]) < 0.0001:\n g[i] = 0.0001\nreturn g",
"nrows = p.shape[0]... | <|body_start_0|>
df['gainAhead'] = self.gainAhead(df.Close)
df['beLong'] = np.where(df.gainAhead > beLongThreshold, 1, -1)
return df
<|end_body_0|>
<|body_start_1|>
nrows = p.shape[0]
g = np.zeros(nrows)
for i in range(0, nrows - 1):
g[i] = (p[i + 1] - p[i]) ... | ComputeTarget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeTarget:
def setTarget(self, df, direction, beLongThreshold):
"""Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or short (currently unused, assume long) beLongThreshold: gain must be above this threshold to set directio... | stack_v2_sparse_classes_75kplus_train_070906 | 12,297 | no_license | [
{
"docstring": "Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or short (currently unused, assume long) beLongThreshold: gain must be above this threshold to set direction Return: df: Dataframe with gainAhead and beLong columns added To update: Adde... | 3 | stack_v2_sparse_classes_30k_train_026106 | Implement the Python class `ComputeTarget` described below.
Class description:
Implement the ComputeTarget class.
Method signatures and docstrings:
- def setTarget(self, df, direction, beLongThreshold): Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or sh... | Implement the Python class `ComputeTarget` described below.
Class description:
Implement the ComputeTarget class.
Method signatures and docstrings:
- def setTarget(self, df, direction, beLongThreshold): Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or sh... | 35c8485c379508c763f3d16087030832792171f6 | <|skeleton|>
class ComputeTarget:
def setTarget(self, df, direction, beLongThreshold):
"""Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or short (currently unused, assume long) beLongThreshold: gain must be above this threshold to set directio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComputeTarget:
def setTarget(self, df, direction, beLongThreshold):
"""Set value of target to 1 if gainAhead>0, otherwise set to 0 Args: df: dataframe of issue data direction: long or short (currently unused, assume long) beLongThreshold: gain must be above this threshold to set direction Return: df: ... | the_stack_v2_python_sparse | Code/lib/retrieve_data.py | ineedaspo1/QuantTradingSys | train | 0 | |
00f121880a7a9d7cb86d44e8cbf79c34afeacd4c | [
"for key, value in named.items():\n setattr(self, key, value)\nsuper(_MouseChangeEvent, self).__init__()",
"base = event.__dict__.copy()\ntry:\n del base['visitedNodes']\nexcept KeyError:\n pass\nreturn cls(lastPath=lastPath, newPath=newPath, **base)"
] | <|body_start_0|>
for key, value in named.items():
setattr(self, key, value)
super(_MouseChangeEvent, self).__init__()
<|end_body_0|>
<|body_start_1|>
base = event.__dict__.copy()
try:
del base['visitedNodes']
except KeyError:
pass
retu... | Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath -- previous value for target path, in essence... | _MouseChangeEvent | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath ... | stack_v2_sparse_classes_75kplus_train_070907 | 16,446 | permissive | [
{
"docstring": "Initialise the event with named attributes",
"name": "__init__",
"signature": "def __init__(self, **named)"
},
{
"docstring": "Construct synthetic mouse event from a move event",
"name": "fromMoveEvent",
"signature": "def fromMoveEvent(cls, event, lastPath, newPath)"
}
... | 2 | stack_v2_sparse_classes_30k_train_004392 | Implement the Python class `_MouseChangeEvent` described below.
Class description:
Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements suc... | Implement the Python class `_MouseChangeEvent` described below.
Class description:
Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements suc... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _MouseChangeEvent:
"""Base class for mouse in/out events The mouse in/out event types are "synthetic", that is, they are generated by other events when certain conditions are true. The change events allow for easily constructing common interface elements such as mouse-overs. Attributes: lastPath -- previous v... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/events/mouseevents.py | alexus37/AugmentedRealityChess | train | 1 |
efd7e6b6b9bf86249d8d7809e0af91eba4f16130 | [
"logger.info('Overriding class: Decoder -> BiGRUDecoder.')\nsuper(BiGRUDecoder, self).__init__()\nself.n_output = n_output\nself.n_hidden = n_hidden_dec\nself.n_embedding = n_embedding\nself.embedding = nn.Embedding(n_output, n_embedding)\nself.a = Attention(n_hidden_enc, n_hidden_dec)\nself.rnn = nn.GRU(n_hidden_e... | <|body_start_0|>
logger.info('Overriding class: Decoder -> BiGRUDecoder.')
super(BiGRUDecoder, self).__init__()
self.n_output = n_output
self.n_hidden = n_hidden_dec
self.n_embedding = n_embedding
self.embedding = nn.Embedding(n_output, n_embedding)
self.a = Atten... | A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture. | BiGRUDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiGRUDecoder:
"""A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture."""
def __init__(self, n_output=128, n_hidden_enc=128, n_hidden_dec=128, n_embedding=128, dropout=0.5):
"""Initialization method. Args: n_output (int): Number of outp... | stack_v2_sparse_classes_75kplus_train_070908 | 3,086 | permissive | [
{
"docstring": "Initialization method. Args: n_output (int): Number of output units. n_hidden_enc (int): Number of hidden units in the Encoder. n_hidden_dec (int): Number of hidden units in the Decoder. n_embedding (int): Number of embedding units. dropout (float): Amount of dropout to be applied.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_032396 | Implement the Python class `BiGRUDecoder` described below.
Class description:
A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture.
Method signatures and docstrings:
- def __init__(self, n_output=128, n_hidden_enc=128, n_hidden_dec=128, n_embedding=128, dropout=0.5): In... | Implement the Python class `BiGRUDecoder` described below.
Class description:
A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture.
Method signatures and docstrings:
- def __init__(self, n_output=128, n_hidden_enc=128, n_hidden_dec=128, n_embedding=128, dropout=0.5): In... | cccc670d48995fa0bfbdf9fc8013d13a90ea5e84 | <|skeleton|>
class BiGRUDecoder:
"""A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture."""
def __init__(self, n_output=128, n_hidden_enc=128, n_hidden_dec=128, n_embedding=128, dropout=0.5):
"""Initialization method. Args: n_output (int): Number of outp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiGRUDecoder:
"""A BiGRUDecoder class is used to supply the decoding part of the Attention-based Seq2Seq architecture."""
def __init__(self, n_output=128, n_hidden_enc=128, n_hidden_dec=128, n_embedding=128, dropout=0.5):
"""Initialization method. Args: n_output (int): Number of output units. n_h... | the_stack_v2_python_sparse | textformer/models/decoders/bi_gru.py | gugarosa/textformer | train | 3 |
b43904996bf497d2d6b1728a9f411135ed9c2e61 | [
"super().__init__(unique_id, model)\nself.pos = np.array(pos)\nself.speed = speed\nself.velocity = velocity\nself.vision = vision\nself.separation = separation\nself.cohere_factor = cohere\nself.separate_factor = separate\nself.match_factor = match\nself.tag = tag",
"cohere = np.zeros(2)\nother_fish = [n for n in... | <|body_start_0|>
super().__init__(unique_id, model)
self.pos = np.array(pos)
self.speed = speed
self.velocity = velocity
self.vision = vision
self.separation = separation
self.cohere_factor = cohere
self.separate_factor = separate
self.match_factor... | A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid. | Fish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr... | stack_v2_sparse_classes_75kplus_train_070909 | 12,295 | no_license | [
{
"docstring": "Create a new Boid (bird, fish) agent. Args: unique_id: Unique agent identifier. pos: Starting position speed: Distance to move per step. velocity: numpy vector for the Boid's direction of movement. vision: Radius to look around for nearby Boids. separation: Minimum distance to maintain from othe... | 6 | stack_v2_sparse_classes_30k_test_000253 | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati... | Implement the Python class `Fish` described below.
Class description:
A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati... | 18166af285d2a40f903bc178f5c37b7d758fb0bd | <|skeleton|>
class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fish:
"""A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other ... | the_stack_v2_python_sparse | shoal_model.py | sowasser/fish-shoaling-model | train | 1 |
85357f6ac5dfad07a24bda83506395d993f6e9ff | [
"prev = None\nwhile head:\n cur = head\n head = head.next\n cur.next = prev\n prev = cur\nreturn prev",
"prev = None\ncur = head\nwhile cur:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\nreturn prev",
"if not head or not head.next:\n return head\nret = self.reverseList(... | <|body_start_0|>
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
<|end_body_0|>
<|body_start_1|>
prev = None
cur = head
while cur:
nxt = cur.next
cur.next =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList0(self, head: ListNode) -> ListNode:
"""有点类似于反转字符串"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""不移动头节点的方法: prev:记录下一次要指向的节点 cur:当前节点 nxt:当前节点的下一个节点,因为当前节点需要指向prev,会丢失下一个节点,所以需要记录"""
<|body_1|>
def reverseL... | stack_v2_sparse_classes_75kplus_train_070910 | 1,405 | no_license | [
{
"docstring": "有点类似于反转字符串",
"name": "reverseList0",
"signature": "def reverseList0(self, head: ListNode) -> ListNode"
},
{
"docstring": "不移动头节点的方法: prev:记录下一次要指向的节点 cur:当前节点 nxt:当前节点的下一个节点,因为当前节点需要指向prev,会丢失下一个节点,所以需要记录",
"name": "reverseList1",
"signature": "def reverseList1(self, head... | 3 | stack_v2_sparse_classes_30k_train_050436 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList0(self, head: ListNode) -> ListNode: 有点类似于反转字符串
- def reverseList1(self, head: ListNode) -> ListNode: 不移动头节点的方法: prev:记录下一次要指向的节点 cur:当前节点 nxt:当前节点的下一个节点,因为当前节点需要指... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList0(self, head: ListNode) -> ListNode: 有点类似于反转字符串
- def reverseList1(self, head: ListNode) -> ListNode: 不移动头节点的方法: prev:记录下一次要指向的节点 cur:当前节点 nxt:当前节点的下一个节点,因为当前节点需要指... | b9a2bd8385e44cc79454f9c7f2146370896559ec | <|skeleton|>
class Solution:
def reverseList0(self, head: ListNode) -> ListNode:
"""有点类似于反转字符串"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""不移动头节点的方法: prev:记录下一次要指向的节点 cur:当前节点 nxt:当前节点的下一个节点,因为当前节点需要指向prev,会丢失下一个节点,所以需要记录"""
<|body_1|>
def reverseL... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList0(self, head: ListNode) -> ListNode:
"""有点类似于反转字符串"""
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
def reverseList1(self, head: ListNode) -> ListNode:
... | the_stack_v2_python_sparse | 206.ReverseLinkedList.py | haveGrasses/Algorithm | train | 0 | |
8f8a9a7472430a1edbb7b5b3bf4effe794a2eeb2 | [
"datas = []\nfin = open(w_file, 'r')\nfor line in fin.readlines():\n f = float(line.split('\\n')[0])\n datas.append(f)\nfin.close()\nreturn datas",
"datas = self.data_collect(w_file)\ntot = 0\nfor data in datas:\n tot = tot + data\naverage = tot / len(datas)\ntot = 0\nfor data in datas:\n tot = tot + ... | <|body_start_0|>
datas = []
fin = open(w_file, 'r')
for line in fin.readlines():
f = float(line.split('\n')[0])
datas.append(f)
fin.close()
return datas
<|end_body_0|>
<|body_start_1|>
datas = self.data_collect(w_file)
tot = 0
for ... | ParaMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
<|body_0|>
def get_para(self, w_file):
"""get parameter :param w_file: filename :return: average u and sigma's square"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_070911 | 975 | no_license | [
{
"docstring": "open fine and handle data form :param w_file: filename :return: data (list)",
"name": "data_collect",
"signature": "def data_collect(self, w_file)"
},
{
"docstring": "get parameter :param w_file: filename :return: average u and sigma's square",
"name": "get_para",
"signat... | 2 | stack_v2_sparse_classes_30k_train_032631 | Implement the Python class `ParaMaker` described below.
Class description:
Implement the ParaMaker class.
Method signatures and docstrings:
- def data_collect(self, w_file): open fine and handle data form :param w_file: filename :return: data (list)
- def get_para(self, w_file): get parameter :param w_file: filename ... | Implement the Python class `ParaMaker` described below.
Class description:
Implement the ParaMaker class.
Method signatures and docstrings:
- def data_collect(self, w_file): open fine and handle data form :param w_file: filename :return: data (list)
- def get_para(self, w_file): get parameter :param w_file: filename ... | b0820b8d8924a9b22c820e3dce4778f4f9a0a96f | <|skeleton|>
class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
<|body_0|>
def get_para(self, w_file):
"""get parameter :param w_file: filename :return: average u and sigma's square"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
datas = []
fin = open(w_file, 'r')
for line in fin.readlines():
f = float(line.split('\n')[0])
datas.append(f)
fin.close(... | the_stack_v2_python_sparse | NaiveBayesian/para_make.py | P-a-z/learn-python-slowly | train | 0 | |
47920f83698f8f269a45844e31540e852c4ddde0 | [
"if not intervals:\n return 0\nintervals.sort(key=lambda d: d.start)\nendheap = [intervals[0].end]\nn = len(intervals)\nrooms = 1\nfor i in range(1, n):\n if endheap:\n if intervals[i].start < endheap[0]:\n rooms += 1\n else:\n heapq.heappop(endheap)\n heapq.heappush(end... | <|body_start_0|>
if not intervals:
return 0
intervals.sort(key=lambda d: d.start)
endheap = [intervals[0].end]
n = len(intervals)
rooms = 1
for i in range(1, n):
if endheap:
if intervals[i].start < endheap[0]:
ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def minMeetingRooms3(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
def minMeetingRooms2(self, intervals):
... | stack_v2_sparse_classes_75kplus_train_070912 | 2,515 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: int",
"name": "minMeetingRooms3",
"signature": "def minMeetingRooms3(self, intervals)"
... | 4 | stack_v2_sparse_classes_30k_train_015985 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMeetingRooms3(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMeetingRooms3(self, intervals): :type intervals: List[Interval] :rtype: int
- def minMe... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_0|>
def minMeetingRooms3(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
<|body_1|>
def minMeetingRooms2(self, intervals):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minMeetingRooms(self, intervals):
""":type intervals: List[Interval] :rtype: int"""
if not intervals:
return 0
intervals.sort(key=lambda d: d.start)
endheap = [intervals[0].end]
n = len(intervals)
rooms = 1
for i in range(1, n):... | the_stack_v2_python_sparse | 253-meeting_rooms_II.py | WweiL/LeetCode | train | 0 | |
a86a4d2b01abaf1474f254d6d1691e724705ae0c | [
"self.fd = fd\nself.started = False\nself.piper = None\nself.pipew = None",
"if not self.started:\n self.oldhandle = os.dup(self.fd)\n self.piper, self.pipew = os.pipe()\n os.dup2(self.pipew, self.fd)\n os.close(self.pipew)\n if self.fd == STDOUT:\n sys.stdout = io.TextIOWrapper(os.fdopen(se... | <|body_start_0|>
self.fd = fd
self.started = False
self.piper = None
self.pipew = None
<|end_body_0|>
<|body_start_1|>
if not self.started:
self.oldhandle = os.dup(self.fd)
self.piper, self.pipew = os.pipe()
os.dup2(self.pipew, self.fd)
... | Class to redirect output (stdout or stderr) at the OS level using file descriptors. | FDRedirector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FDRedirector:
"""Class to redirect output (stdout or stderr) at the OS level using file descriptors."""
def __init__(self, fd=STDOUT):
"""fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR."""
<|body_0|>
def start(self):
"""Se... | stack_v2_sparse_classes_75kplus_train_070913 | 4,943 | permissive | [
{
"docstring": "fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR.",
"name": "__init__",
"signature": "def __init__(self, fd=STDOUT)"
},
{
"docstring": "Setup the redirection.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_001653 | Implement the Python class `FDRedirector` described below.
Class description:
Class to redirect output (stdout or stderr) at the OS level using file descriptors.
Method signatures and docstrings:
- def __init__(self, fd=STDOUT): fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR.
... | Implement the Python class `FDRedirector` described below.
Class description:
Class to redirect output (stdout or stderr) at the OS level using file descriptors.
Method signatures and docstrings:
- def __init__(self, fd=STDOUT): fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR.
... | 6b8a24a632354d70c8ba44df717291573a5e0bd2 | <|skeleton|>
class FDRedirector:
"""Class to redirect output (stdout or stderr) at the OS level using file descriptors."""
def __init__(self, fd=STDOUT):
"""fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR."""
<|body_0|>
def start(self):
"""Se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FDRedirector:
"""Class to redirect output (stdout or stderr) at the OS level using file descriptors."""
def __init__(self, fd=STDOUT):
"""fd is the file descriptor of the outpout you want to capture. It can be STDOUT or STERR."""
self.fd = fd
self.started = False
self.pipe... | the_stack_v2_python_sparse | MC simulation/mcdose/mcdose/deprecated/fd_redirector.py | qihuilyu/P2T | train | 1 |
c33fc840a21a2dce3cdc03ae94629e68d93a120f | [
"super().__init__()\nif queue:\n self.queue = queue\nelse:\n raise Exception('ERROR: No queue object supplied!')",
"self.acquire()\ntry:\n while not self.queue.empty():\n self.queue.get()\nfinally:\n self.release()",
"try:\n msg = self.format(record)\n self.queue.put(msg)\nexcept Except... | <|body_start_0|>
super().__init__()
if queue:
self.queue = queue
else:
raise Exception('ERROR: No queue object supplied!')
<|end_body_0|>
<|body_start_1|>
self.acquire()
try:
while not self.queue.empty():
self.queue.get()
... | Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required. | VlogHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VlogHandler:
"""Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required."""
def __init__(self, queue=None):
"""Initialize the handler. Args: queue (multiprocessing.Queue): A queue object shared with the video recording process... | stack_v2_sparse_classes_75kplus_train_070914 | 5,343 | permissive | [
{
"docstring": "Initialize the handler. Args: queue (multiprocessing.Queue): A queue object shared with the video recording process.",
"name": "__init__",
"signature": "def __init__(self, queue=None)"
},
{
"docstring": "Empties the queue by popping all items until it's empty.",
"name": "flus... | 3 | null | Implement the Python class `VlogHandler` described below.
Class description:
Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required.
Method signatures and docstrings:
- def __init__(self, queue=None): Initialize the handler. Args: queue (multiprocessing.Queue... | Implement the Python class `VlogHandler` described below.
Class description:
Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required.
Method signatures and docstrings:
- def __init__(self, queue=None): Initialize the handler. Args: queue (multiprocessing.Queue... | 0f249ce8f7c30e99bdf54f67cbd012d48e91dd3b | <|skeleton|>
class VlogHandler:
"""Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required."""
def __init__(self, queue=None):
"""Initialize the handler. Args: queue (multiprocessing.Queue): A queue object shared with the video recording process... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VlogHandler:
"""Logging module handler class. Inherits directly from the logging.Handler prototype, as no fancy stuff is required."""
def __init__(self, queue=None):
"""Initialize the handler. Args: queue (multiprocessing.Queue): A queue object shared with the video recording process."""
... | the_stack_v2_python_sparse | platform_server/tools/vlogging.py | croningp/ChemputerSoftware | train | 85 |
d1210513ae82ff7de006c7e70aba3632ee09b9fb | [
"delta_lon_lat = np.array(meters, dtype=np.float64)\nif len(delta_lon_lat.shape) == 1:\n if delta_lon_lat.shape[0] == 2:\n delta_lon_lat = delta_lon_lat.reshape(1, 2)\n else:\n delta_lon_lat = delta_lon_lat.reshape(1, 3)\nref_positions = np.asarray(ref_positions, dtype=np.float64)\nif len(ref_po... | <|body_start_0|>
delta_lon_lat = np.array(meters, dtype=np.float64)
if len(delta_lon_lat.shape) == 1:
if delta_lon_lat.shape[0] == 2:
delta_lon_lat = delta_lon_lat.reshape(1, 2)
else:
delta_lon_lat = delta_lon_lat.reshape(1, 3)
ref_position... | class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks OK. | FlatEarthProjection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlatEarthProjection:
"""class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks OK."""
def meters_to_lonlat(meter... | stack_v2_sparse_classes_75kplus_train_070915 | 25,780 | no_license | [
{
"docstring": "Converts from delta meters to delta latitude-longitude, using the Flat-Earth projection. dlat = dy * 8.9992801e-06 dlon = dy * 8.9992801e-06 * cos(ref_lat) (based on previous GNOME value: and/or average radius of the earth of 6366706.989 m) :param meters: Distances in meters :type meters: NX3 nu... | 4 | stack_v2_sparse_classes_30k_train_032778 | Implement the Python class `FlatEarthProjection` described below.
Class description:
class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks... | Implement the Python class `FlatEarthProjection` described below.
Class description:
class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks... | 2e24d53b8b1099022a08ad73377ed6d1c7838f0f | <|skeleton|>
class FlatEarthProjection:
"""class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks OK."""
def meters_to_lonlat(meter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlatEarthProjection:
"""class to define a "flat earth" projection: longitude is scaled to the cosine of the mid-latitude -- but that's it. not conforming to equal area, distance, bearing, or any other nifty map properties -- but easy to compute, and it looks OK."""
def meters_to_lonlat(meters, ref_positi... | the_stack_v2_python_sparse | py_gnome/gnome/utilities/projections.py | bhattvihang/PyGnome | train | 1 |
2d71d5032e29b772e4a23624cd052d97ef8f7248 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.inst_lbl = Label(self, text='Input password to longevity secret.')\nself.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W)\nself.pw_lbl = Label(self, text='Password: ')\nself.pw_lbl.grid(row=1, column=0, sticky=W)\nself.pw... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.inst_lbl = Label(self, text='Input password to longevity secret.')
self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W)
self.pw_lbl = ... | Application with GUI, which can revealed secret of longevity. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application with GUI, which can revealed secret of longevity."""
def __init__(self, master):
"""Initialize frame."""
<|body_0|>
def create_widgets(self):
"""Create widgets Button, Text and Entry."""
<|body_1|>
def reveal(self):
... | stack_v2_sparse_classes_75kplus_train_070916 | 2,625 | no_license | [
{
"docstring": "Initialize frame.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create widgets Button, Text and Entry.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "Print message depends of password val... | 3 | stack_v2_sparse_classes_30k_train_025191 | Implement the Python class `Application` described below.
Class description:
Application with GUI, which can revealed secret of longevity.
Method signatures and docstrings:
- def __init__(self, master): Initialize frame.
- def create_widgets(self): Create widgets Button, Text and Entry.
- def reveal(self): Print mess... | Implement the Python class `Application` described below.
Class description:
Application with GUI, which can revealed secret of longevity.
Method signatures and docstrings:
- def __init__(self, master): Initialize frame.
- def create_widgets(self): Create widgets Button, Text and Entry.
- def reveal(self): Print mess... | 120e2d62468a085424ec71a22effe27d6b38b548 | <|skeleton|>
class Application:
"""Application with GUI, which can revealed secret of longevity."""
def __init__(self, master):
"""Initialize frame."""
<|body_0|>
def create_widgets(self):
"""Create widgets Button, Text and Entry."""
<|body_1|>
def reveal(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Application with GUI, which can revealed secret of longevity."""
def __init__(self, master):
"""Initialize frame."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create widgets Button,... | the_stack_v2_python_sparse | Chapter 10/longevity.py | MartaSzuran/Python-for-the-Absolute-Beginner-M.Dawson | train | 1 |
1f9db630d99dc883d96748263909c293af90eb94 | [
"self.num_feat_per_dim = num_feat_per_dim\nself.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))\nself.freq = to.randn(num_feat_per_dim, inp_dim)\nif not isinstance(bandwidth, to.Tensor):\n bandwidth = to.from_numpy(np.asanyarray(bandwidth))\nself.freq *= to.sqrt(to.tensor(2.0) / to.atleast_2d(bandwidth))\nsel... | <|body_start_0|>
self.num_feat_per_dim = num_feat_per_dim
self.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))
self.freq = to.randn(num_feat_per_dim, inp_dim)
if not isinstance(bandwidth, to.Tensor):
bandwidth = to.from_numpy(np.asanyarray(bandwidth))
self.freq *= ... | Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007 | RFFeat | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian ... | stack_v2_sparse_classes_75kplus_train_070917 | 19,215 | permissive | [
{
"docstring": "Gaussian kernel: $k(x,y) = \\\\exp(-\\\\sigma**2 / (2*d) * ||x-y||^2)$ Sample from $\\\\mathcal{N}(0,1)$ and scale the result by $\\\\sigma / \\\\sqrt{2*d}$ :param inp_dim: flat dimension of the inputs i.e. the observations, called $d$ in [1] :param num_feat_per_dim: number of random Fourier fea... | 2 | stack_v2_sparse_classes_30k_train_023803 | Implement the Python class `RFFeat` described below.
Class description:
Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float,... | Implement the Python class `RFFeat` described below.
Class description:
Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float,... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian kernel: $k(x,... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/features.py | 1abner1/SimuRLacra | train | 0 |
a3e5e003d657cb4420c8ad0070f5eaa69f976583 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TemporaryAccessPassAuthenticationMethodConfiguration()",
"from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .authentication_method_target import AuthenticationMethodTarget\nfrom .authentication_me... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TemporaryAccessPassAuthenticationMethodConfiguration()
<|end_body_0|>
<|body_start_1|>
from .authentication_method_configuration import AuthenticationMethodConfiguration
from .authentica... | TemporaryAccessPassAuthenticationMethodConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporaryAccessPassAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_75kplus_train_070918 | 4,745 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TemporaryAccessPassAuthenticationMethodConfiguration",
"name": "create_from_discriminator_value",
"signature... | 3 | null | Implement the Python class `TemporaryAccessPassAuthenticationMethodConfiguration` described below.
Class description:
Implement the TemporaryAccessPassAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAcce... | Implement the Python class `TemporaryAccessPassAuthenticationMethodConfiguration` described below.
Class description:
Implement the TemporaryAccessPassAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAcce... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TemporaryAccessPassAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporaryAccessPassAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to u... | the_stack_v2_python_sparse | msgraph/generated/models/temporary_access_pass_authentication_method_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
541c0a5611ef6eb98332bbfb3522e20a26af38e8 | [
"super(SigmoidBenchmark, self).__init__(config_path, config)\nif not self.config:\n self.config = objdict(SIGMOID_DEFAULTS.copy())\nfor key in SIGMOID_DEFAULTS:\n if key not in self.config:\n self.config[key] = SIGMOID_DEFAULTS[key]",
"if 'instance_set' not in self.config.keys():\n self.read_insta... | <|body_start_0|>
super(SigmoidBenchmark, self).__init__(config_path, config)
if not self.config:
self.config = objdict(SIGMOID_DEFAULTS.copy())
for key in SIGMOID_DEFAULTS:
if key not in self.config:
self.config[key] = SIGMOID_DEFAULTS[key]
<|end_body_0|>
... | Benchmark with default configuration & relevant functions for Sigmoid | SigmoidBenchmark | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SigmoidBenchmark:
"""Benchmark with default configuration & relevant functions for Sigmoid"""
def __init__(self, config_path=None, config=None):
"""Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to config file (optional)"""
<|body_0|>
def get_envi... | stack_v2_sparse_classes_75kplus_train_070919 | 8,827 | permissive | [
{
"docstring": "Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to config file (optional)",
"name": "__init__",
"signature": "def __init__(self, config_path=None, config=None)"
},
{
"docstring": "Return Sigmoid env with current configuration Returns ------- SigmoidEnv Sigm... | 5 | stack_v2_sparse_classes_30k_train_009356 | Implement the Python class `SigmoidBenchmark` described below.
Class description:
Benchmark with default configuration & relevant functions for Sigmoid
Method signatures and docstrings:
- def __init__(self, config_path=None, config=None): Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to confi... | Implement the Python class `SigmoidBenchmark` described below.
Class description:
Benchmark with default configuration & relevant functions for Sigmoid
Method signatures and docstrings:
- def __init__(self, config_path=None, config=None): Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to confi... | d99b21ec844a46d6e18e729ab299f8e9051a68e8 | <|skeleton|>
class SigmoidBenchmark:
"""Benchmark with default configuration & relevant functions for Sigmoid"""
def __init__(self, config_path=None, config=None):
"""Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to config file (optional)"""
<|body_0|>
def get_envi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SigmoidBenchmark:
"""Benchmark with default configuration & relevant functions for Sigmoid"""
def __init__(self, config_path=None, config=None):
"""Initialize Sigmoid Benchmark Parameters ------- config_path : str Path to config file (optional)"""
super(SigmoidBenchmark, self).__init__(co... | the_stack_v2_python_sparse | dacbench/benchmarks/sigmoid_benchmark.py | automl/DACBench | train | 19 |
c83b142fa14bc2e818f5cc60ac21c8638bf5cd67 | [
"super().__init__(coreDetection, image)\nif coreDetection.landmarks17_opt.isValid():\n self.landmarks17: Optional[Landmarks17] = Landmarks17(coreDetection.landmarks17_opt.value())\nelse:\n self.landmarks17 = None",
"res = super().asDict()\nif self.landmarks17 is not None:\n res['landmarks17'] = self.land... | <|body_start_0|>
super().__init__(coreDetection, image)
if coreDetection.landmarks17_opt.isValid():
self.landmarks17: Optional[Landmarks17] = Landmarks17(coreDetection.landmarks17_opt.value())
else:
self.landmarks17 = None
<|end_body_0|>
<|body_start_1|>
res = su... | Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17 | BodyDetection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BodyDetection:
"""Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17"""
def __init__(self, coreDetection: Human, image: VLImage):
"""Init. Args: coreDetection: core detection"""
<|body_0|>
def asDict(self) -> Dict[str, Any]:
"""Convert human de... | stack_v2_sparse_classes_75kplus_train_070920 | 15,818 | permissive | [
{
"docstring": "Init. Args: coreDetection: core detection",
"name": "__init__",
"signature": "def __init__(self, coreDetection: Human, image: VLImage)"
},
{
"docstring": "Convert human detection to dict (json). Returns: dict. required keys: 'rect', 'score'. optional keys: 'landmarks5', 'landmark... | 2 | stack_v2_sparse_classes_30k_train_051435 | Implement the Python class `BodyDetection` described below.
Class description:
Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17
Method signatures and docstrings:
- def __init__(self, coreDetection: Human, image: VLImage): Init. Args: coreDetection: core detection
- def asDict(self) -> Dict[str, A... | Implement the Python class `BodyDetection` described below.
Class description:
Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17
Method signatures and docstrings:
- def __init__(self, coreDetection: Human, image: VLImage): Init. Args: coreDetection: core detection
- def asDict(self) -> Dict[str, A... | 7a4bebc92ae7a96d8d9c18a024208308942f90cd | <|skeleton|>
class BodyDetection:
"""Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17"""
def __init__(self, coreDetection: Human, image: VLImage):
"""Init. Args: coreDetection: core detection"""
<|body_0|>
def asDict(self) -> Dict[str, Any]:
"""Convert human de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BodyDetection:
"""Attributes: landmarks17 (Optional[Landmarks17]): optional landmarks17"""
def __init__(self, coreDetection: Human, image: VLImage):
"""Init. Args: coreDetection: core detection"""
super().__init__(coreDetection, image)
if coreDetection.landmarks17_opt.isValid():
... | the_stack_v2_python_sparse | lunavl/sdk/detectors/bodydetector.py | matemax/lunasdk | train | 16 |
5a2cf3dc6d7b81410e56a0d1ab944519aabc82f0 | [
"self.logger = logging.getLogger('BeamShutter')\nself.port_opened = False\ntry:\n self.beam_shutter_serial_port = serial.Serial(port, baudrate=115200, timeout=0.1, write_timeout=1)\n self.port_opened = True\nexcept serial.SerialException:\n self.logger.error('Cannot open Beam Shutter Controller port!')\n ... | <|body_start_0|>
self.logger = logging.getLogger('BeamShutter')
self.port_opened = False
try:
self.beam_shutter_serial_port = serial.Serial(port, baudrate=115200, timeout=0.1, write_timeout=1)
self.port_opened = True
except serial.SerialException:
self... | Beam Shutter class | BeamShutter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BeamShutter:
"""Beam Shutter class"""
def __init__(self, port):
"""Init function"""
<|body_0|>
def beam_off(self):
"""Close the beam shutter"""
<|body_1|>
def beam_on(self):
"""Open the beam shutter"""
<|body_2|>
def beam_shutter... | stack_v2_sparse_classes_75kplus_train_070921 | 3,253 | no_license | [
{
"docstring": "Init function",
"name": "__init__",
"signature": "def __init__(self, port)"
},
{
"docstring": "Close the beam shutter",
"name": "beam_off",
"signature": "def beam_off(self)"
},
{
"docstring": "Open the beam shutter",
"name": "beam_on",
"signature": "def be... | 5 | stack_v2_sparse_classes_30k_train_034931 | Implement the Python class `BeamShutter` described below.
Class description:
Beam Shutter class
Method signatures and docstrings:
- def __init__(self, port): Init function
- def beam_off(self): Close the beam shutter
- def beam_on(self): Open the beam shutter
- def beam_shutter_2_off(self): Open the beam shutter
- de... | Implement the Python class `BeamShutter` described below.
Class description:
Beam Shutter class
Method signatures and docstrings:
- def __init__(self, port): Init function
- def beam_off(self): Close the beam shutter
- def beam_on(self): Open the beam shutter
- def beam_shutter_2_off(self): Open the beam shutter
- de... | a50506f31b667107b8b08dfdf47d4798556a8e8c | <|skeleton|>
class BeamShutter:
"""Beam Shutter class"""
def __init__(self, port):
"""Init function"""
<|body_0|>
def beam_off(self):
"""Close the beam shutter"""
<|body_1|>
def beam_on(self):
"""Open the beam shutter"""
<|body_2|>
def beam_shutter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BeamShutter:
"""Beam Shutter class"""
def __init__(self, port):
"""Init function"""
self.logger = logging.getLogger('BeamShutter')
self.port_opened = False
try:
self.beam_shutter_serial_port = serial.Serial(port, baudrate=115200, timeout=0.1, write_timeout=1)
... | the_stack_v2_python_sparse | RU_GUI_release/py_gui/beam_shutter.py | ycorrales/LANL_P25_RU_Felix_GUI | train | 0 |
7a88f24954bb02389d332885ac483236a1f6a796 | [
"if user not in self._user_enrollments:\n self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)\nreturn self._user_enrollments[user]",
"field_dictionary = super().field_dictionary(**kwargs)\nif not kwargs.get('user'):\n field_dictionary['course'] = []\nelif not kwargs.get('course_id'):\... | <|body_start_0|>
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
return self._user_enrollments[user]
<|end_body_0|>
<|body_start_1|>
field_dictionary = super().field_dictionary(**kwargs)
if not kwargs.get('use... | SearchFilterGenerator for LMS Search | LmsSearchFilterGenerator | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_75kplus_train_070922 | 2,467 | permissive | [
{
"docstring": "Return the specified user's course enrollments",
"name": "_enrollments_for_user",
"signature": "def _enrollments_for_user(self, user)"
},
{
"docstring": "add course if provided otherwise add courses in which the user is enrolled in",
"name": "field_dictionary",
"signature... | 3 | stack_v2_sparse_classes_30k_train_007345 | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | Implement the Python class `LmsSearchFilterGenerator` described below.
Class description:
SearchFilterGenerator for LMS Search
Method signatures and docstrings:
- def _enrollments_for_user(self, user): Return the specified user's course enrollments
- def field_dictionary(self, **kwargs): add course if provided otherw... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
<|body_0|>
def field_dictionary(self, **kwargs):
"""add course if provided otherwise add courses in wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LmsSearchFilterGenerator:
"""SearchFilterGenerator for LMS Search"""
def _enrollments_for_user(self, user):
"""Return the specified user's course enrollments"""
if user not in self._user_enrollments:
self._user_enrollments[user] = CourseEnrollment.enrollments_for_user(user)
... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/lib/courseware_search/lms_filter_generator.py | luque/better-ways-of-thinking-about-software | train | 3 |
9fb86ebe3ca0bc2e40dc831f0a0507f6da6702e6 | [
"B, c, m = features.size()\nn = idx.size(1)\nctx.three_interpolate_for_backward = (idx, weight, m)\nreturn _ext.three_interpolate(features, idx, weight)",
"idx, weight, m = ctx.three_interpolate_for_backward\ngrad_features = _ext.three_interpolate_grad(grad_out.contiguous(), idx, weight, m)\nreturn (grad_features... | <|body_start_0|>
B, c, m = features.size()
n = idx.size(1)
ctx.three_interpolate_for_backward = (idx, weight, m)
return _ext.three_interpolate(features, idx, weight)
<|end_body_0|>
<|body_start_1|>
idx, weight, m = ctx.three_interpolate_for_backward
grad_features = _ext.... | ThreeInterpolate | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeInterpolate:
def forward(ctx, features, idx, weight):
"""Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target feature... | stack_v2_sparse_classes_75kplus_train_070923 | 15,763 | permissive | [
{
"docstring": "Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target features in features weight : torch.Tensor (B, n, 3) weights Returns ------- ... | 2 | stack_v2_sparse_classes_30k_train_019148 | Implement the Python class `ThreeInterpolate` described below.
Class description:
Implement the ThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features, idx, weight): Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descr... | Implement the Python class `ThreeInterpolate` described below.
Class description:
Implement the ThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features, idx, weight): Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descr... | c0eecf2223c3c28d048d816fd239c118b8568dcf | <|skeleton|>
class ThreeInterpolate:
def forward(ctx, features, idx, weight):
"""Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target feature... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreeInterpolate:
def forward(ctx, features, idx, weight):
"""Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target features in features ... | the_stack_v2_python_sparse | pointcloud/pointnet2/utils/pointnet2_utils.py | WangLi2019Gt/qpu_code | train | 0 | |
e3e7c112713f28effafb05b8edd56c2dff67d33b | [
"assert niveau.upper() in ['D', 'E', 'I'], 'Le niveau doit être parmis D, E et I'\nmessage = (niveau + ':').encode('utf-8') + pickle.dumps(message)\nif isinstance(conn, mp.connection.Connection):\n conn.send_bytes(message)\nelse:\n conn.send(message)",
"if isinstance(conn, mp.connection.Connection):\n if... | <|body_start_0|>
assert niveau.upper() in ['D', 'E', 'I'], 'Le niveau doit être parmis D, E et I'
message = (niveau + ':').encode('utf-8') + pickle.dumps(message)
if isinstance(conn, mp.connection.Connection):
conn.send_bytes(message)
else:
conn.send(message)
<|en... | Base des serveurs | BaseServeur | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseServeur:
"""Base des serveurs"""
def envoi(self, conn, message, niveau='I'):
"""Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info"""
<|body_0|>
def recevoir(self, conn, timeout=0.0... | stack_v2_sparse_classes_75kplus_train_070924 | 1,958 | no_license | [
{
"docstring": "Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info",
"name": "envoi",
"signature": "def envoi(self, conn, message, niveau='I')"
},
{
"docstring": "Reçoit et analyse le message.",
"name": "re... | 2 | stack_v2_sparse_classes_30k_train_010515 | Implement the Python class `BaseServeur` described below.
Class description:
Base des serveurs
Method signatures and docstrings:
- def envoi(self, conn, message, niveau='I'): Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info
- def ... | Implement the Python class `BaseServeur` described below.
Class description:
Base des serveurs
Method signatures and docstrings:
- def envoi(self, conn, message, niveau='I'): Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info
- def ... | 3348716489815a6e145d1699a1deb9143800afe2 | <|skeleton|>
class BaseServeur:
"""Base des serveurs"""
def envoi(self, conn, message, niveau='I'):
"""Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info"""
<|body_0|>
def recevoir(self, conn, timeout=0.0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseServeur:
"""Base des serveurs"""
def envoi(self, conn, message, niveau='I'):
"""Envoie un message dans la connection conn. Le message doit être picklable. Définition des niveaux: - D : données - E : erreur - I : info"""
assert niveau.upper() in ['D', 'E', 'I'], 'Le niveau doit être pa... | the_stack_v2_python_sparse | base/serveurs/base.py | Jujulego/pyupnp | train | 0 |
7ebbd01376f070d2331fc01031eb60317930bf24 | [
"super().__init__()\nif not isinstance(size, int):\n raise _BeartypeUtilCacheLruException(f'LRU cache capacity {repr(size)} not integer.')\nelif size < 1:\n raise _BeartypeUtilCacheLruException(f'LRU cache capacity {size} not positive.')\nself._size = size\nself._lock = Lock()",
"with self._lock:\n if __... | <|body_start_0|>
super().__init__()
if not isinstance(size, int):
raise _BeartypeUtilCacheLruException(f'LRU cache capacity {repr(size)} not integer.')
elif size < 1:
raise _BeartypeUtilCacheLruException(f'LRU cache capacity {size} not positive.')
self._size = siz... | **Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak references for s... | CacheLruStrong | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementati... | stack_v2_sparse_classes_75kplus_train_070925 | 8,726 | permissive | [
{
"docstring": "Initialize this cache to an empty cache with a capacity of this size. Parameters ---------- size : int **Cache capacity** (i.e., maximum number of key-value pairs held in this cache). Raises ------ _BeartypeUtilCacheLruException: If the capacity is *not* an integer or its a **non-positive intege... | 4 | stack_v2_sparse_classes_30k_train_043286 | Implement the Python class `CacheLruStrong` described below.
Class description:
**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-sa... | Implement the Python class `CacheLruStrong` described below.
Class description:
**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-sa... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically... | the_stack_v2_python_sparse | beartype/_util/cache/map/utilmaplru.py | beartype/beartype | train | 1,992 |
cb85eaa78b75832a3b2d18c632fa2f8e8a719a72 | [
"tk.Frame.__init__(self, parent)\nself._parent = parent\nself._controller = controller\nself._page = tk.IntVar()\nself._create_widgets()",
"tk.Label(self, text='Sensor Type:').grid(row=0, column=0)\ntk.Radiobutton(self, text='Temperature', variable=self._page, value=1, command=self._page_switch).grid(row=0, colum... | <|body_start_0|>
tk.Frame.__init__(self, parent)
self._parent = parent
self._controller = controller
self._page = tk.IntVar()
self._create_widgets()
<|end_body_0|>
<|body_start_1|>
tk.Label(self, text='Sensor Type:').grid(row=0, column=0)
tk.Radiobutton(self, tex... | Navigation Bar | TopNavbarView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopNavbarView:
"""Navigation Bar"""
def __init__(self, parent, controller):
"""Initialize the nav bar"""
<|body_0|>
def _create_widgets(self):
"""Creates the widgets for the nav bar"""
<|body_1|>
def _page_switch(self):
"""Handle Switching Be... | stack_v2_sparse_classes_75kplus_train_070926 | 1,461 | no_license | [
{
"docstring": "Initialize the nav bar",
"name": "__init__",
"signature": "def __init__(self, parent, controller)"
},
{
"docstring": "Creates the widgets for the nav bar",
"name": "_create_widgets",
"signature": "def _create_widgets(self)"
},
{
"docstring": "Handle Switching Betw... | 3 | null | Implement the Python class `TopNavbarView` described below.
Class description:
Navigation Bar
Method signatures and docstrings:
- def __init__(self, parent, controller): Initialize the nav bar
- def _create_widgets(self): Creates the widgets for the nav bar
- def _page_switch(self): Handle Switching Between Pages | Implement the Python class `TopNavbarView` described below.
Class description:
Navigation Bar
Method signatures and docstrings:
- def __init__(self, parent, controller): Initialize the nav bar
- def _create_widgets(self): Creates the widgets for the nav bar
- def _page_switch(self): Handle Switching Between Pages
<|... | e46520c7d44f384fc104a07d48015bc301951966 | <|skeleton|>
class TopNavbarView:
"""Navigation Bar"""
def __init__(self, parent, controller):
"""Initialize the nav bar"""
<|body_0|>
def _create_widgets(self):
"""Creates the widgets for the nav bar"""
<|body_1|>
def _page_switch(self):
"""Handle Switching Be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopNavbarView:
"""Navigation Bar"""
def __init__(self, parent, controller):
"""Initialize the nav bar"""
tk.Frame.__init__(self, parent)
self._parent = parent
self._controller = controller
self._page = tk.IntVar()
self._create_widgets()
def _create_wid... | the_stack_v2_python_sparse | client/top_navbar_view.py | kanoni4567/sensor_api | train | 0 |
0739f4322856affff3ddd86bebaec1f11caa1bc7 | [
"extent_raw_geom = obj['extent']\nif extent_raw_geom is not None:\n extent_geometry = GEOSGeometry(extent_raw_geom)\n return extent_geometry.extent\nreturn None",
"ret = super().to_representation(instance)\nret['id'] = instance['aquifer_id']\nret['name'] = instance['aquifer_name']\nif instance['area']:\n ... | <|body_start_0|>
extent_raw_geom = obj['extent']
if extent_raw_geom is not None:
extent_geometry = GEOSGeometry(extent_raw_geom)
return extent_geometry.extent
return None
<|end_body_0|>
<|body_start_1|>
ret = super().to_representation(instance)
ret['id'] ... | Serialize an aquifer list | AquiferSerializerV2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
<|body_0|>
def to_representation(self, instance):
"""Rather the declare serializer fields, we must reference them here because they are queried as a `dict`... | stack_v2_sparse_classes_75kplus_train_070927 | 12,484 | permissive | [
{
"docstring": "Gets a GeoJSON extent",
"name": "get_extent",
"signature": "def get_extent(self, obj)"
},
{
"docstring": "Rather the declare serializer fields, we must reference them here because they are queried as a `dict`, which dramatically improves performance due to the high number of join... | 2 | stack_v2_sparse_classes_30k_test_002970 | Implement the Python class `AquiferSerializerV2` described below.
Class description:
Serialize an aquifer list
Method signatures and docstrings:
- def get_extent(self, obj): Gets a GeoJSON extent
- def to_representation(self, instance): Rather the declare serializer fields, we must reference them here because they ar... | Implement the Python class `AquiferSerializerV2` described below.
Class description:
Serialize an aquifer list
Method signatures and docstrings:
- def get_extent(self, obj): Gets a GeoJSON extent
- def to_representation(self, instance): Rather the declare serializer fields, we must reference them here because they ar... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
<|body_0|>
def to_representation(self, instance):
"""Rather the declare serializer fields, we must reference them here because they are queried as a `dict`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
extent_raw_geom = obj['extent']
if extent_raw_geom is not None:
extent_geometry = GEOSGeometry(extent_raw_geom)
return extent_geometry.extent
... | the_stack_v2_python_sparse | app/backend/aquifers/serializers_v2.py | bcgov/gwells | train | 39 |
cc0a5b92374d04634f30dcc14fd6475bc0f11881 | [
"path = os.path.join(self.directory, self.filepath)\nlog_report('INFO', 'path: ' + str(path), self)\nself.image_dp = self.get_default_image_path(path, self.image_dp)\nlog_report('INFO', 'image_dp: ' + str(self.image_dp), self)\ncameras, points = OpenSfMJSONFileHandler.parse_opensfm_file(path, self.image_dp, self.im... | <|body_start_0|>
path = os.path.join(self.directory, self.filepath)
log_report('INFO', 'path: ' + str(path), self)
self.image_dp = self.get_default_image_path(path, self.image_dp)
log_report('INFO', 'image_dp: ' + str(self.image_dp), self)
cameras, points = OpenSfMJSONFileHandler... | Import an :code:`OpenSfM` JSON file | ImportOpenSfMOperator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportOpenSfMOperator:
"""Import an :code:`OpenSfM` JSON file"""
def execute(self, context):
"""Import an :code:`OpenSfM` :code:`JSON` file."""
<|body_0|>
def invoke(self, context, event):
"""Set the default import options before running the operator."""
... | stack_v2_sparse_classes_75kplus_train_070928 | 3,101 | permissive | [
{
"docstring": "Import an :code:`OpenSfM` :code:`JSON` file.",
"name": "execute",
"signature": "def execute(self, context)"
},
{
"docstring": "Set the default import options before running the operator.",
"name": "invoke",
"signature": "def invoke(self, context, event)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_048679 | Implement the Python class `ImportOpenSfMOperator` described below.
Class description:
Import an :code:`OpenSfM` JSON file
Method signatures and docstrings:
- def execute(self, context): Import an :code:`OpenSfM` :code:`JSON` file.
- def invoke(self, context, event): Set the default import options before running the ... | Implement the Python class `ImportOpenSfMOperator` described below.
Class description:
Import an :code:`OpenSfM` JSON file
Method signatures and docstrings:
- def execute(self, context): Import an :code:`OpenSfM` :code:`JSON` file.
- def invoke(self, context, event): Set the default import options before running the ... | da404ebf8d4412196c2740f0b569cbf9e542952d | <|skeleton|>
class ImportOpenSfMOperator:
"""Import an :code:`OpenSfM` JSON file"""
def execute(self, context):
"""Import an :code:`OpenSfM` :code:`JSON` file."""
<|body_0|>
def invoke(self, context, event):
"""Set the default import options before running the operator."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportOpenSfMOperator:
"""Import an :code:`OpenSfM` JSON file"""
def execute(self, context):
"""Import an :code:`OpenSfM` :code:`JSON` file."""
path = os.path.join(self.directory, self.filepath)
log_report('INFO', 'path: ' + str(path), self)
self.image_dp = self.get_defaul... | the_stack_v2_python_sparse | photogrammetry_importer/operators/opensfm_import_op.py | SBCV/Blender-Addon-Photogrammetry-Importer | train | 718 |
2f7613d71ae3454302a5287de71367ba32b2f34f | [
"if not self.inputCallbacks:\n self.inputCallbacks = {}\nself.inputCallbacks[name] = deactivate_control\nprev_enum = self.parameters['controlled_by'].datatype.export_datatype()['members']\nself.parameters['controlled_by'].datatype = EnumType(Enum(prev_enum, **{name: None}))",
"if self.controlled_by:\n self.... | <|body_start_0|>
if not self.inputCallbacks:
self.inputCallbacks = {}
self.inputCallbacks[name] = deactivate_control
prev_enum = self.parameters['controlled_by'].datatype.export_datatype()['members']
self.parameters['controlled_by'].datatype = EnumType(Enum(prev_enum, **{name... | mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called | HasControlledBy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HasControlledBy:
"""mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called"""
def register_input(self, name, deactivate_control):
"""register input :param nam... | stack_v2_sparse_classes_75kplus_train_070929 | 3,945 | no_license | [
{
"docstring": "register input :param name: the name of the module (for controlled_by enum) :param deactivate_control: a method on the input module to switch off control",
"name": "register_input",
"signature": "def register_input(self, name, deactivate_control)"
},
{
"docstring": "method to cha... | 2 | null | Implement the Python class `HasControlledBy` described below.
Class description:
mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called
Method signatures and docstrings:
- def register_input(s... | Implement the Python class `HasControlledBy` described below.
Class description:
mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called
Method signatures and docstrings:
- def register_input(s... | 2e741728693b0fab40204d429000a5a4f827d841 | <|skeleton|>
class HasControlledBy:
"""mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called"""
def register_input(self, name, deactivate_control):
"""register input :param nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HasControlledBy:
"""mixin for modules with controlled_by in the :meth:`write_target` the hardware action to switch to own control should be done and in addition self.self_controlled() should be called"""
def register_input(self, name, deactivate_control):
"""register input :param name: the name o... | the_stack_v2_python_sparse | frappy/mixins.py | SampleEnvironment/frappy | train | 3 |
7451956c499f0afeddc2372dce2f5297cf91b5be | [
"super(AUGRU_Cell, self).__init__()\nself.Wu = init.xavier_uniform_(Parameter(torch.empty(in_dim, hidden_dim)))\nself.Uu = init.xavier_uniform_(Parameter(torch.empty(in_dim, hidden_dim)))\nself.bu = init.xavier_uniform_(Parameter(torch.empty(1, hidden_dim)))\nself.Wr = init.xavier_uniform_(Parameter(torch.empty(in_... | <|body_start_0|>
super(AUGRU_Cell, self).__init__()
self.Wu = init.xavier_uniform_(Parameter(torch.empty(in_dim, hidden_dim)))
self.Uu = init.xavier_uniform_(Parameter(torch.empty(in_dim, hidden_dim)))
self.bu = init.xavier_uniform_(Parameter(torch.empty(1, hidden_dim)))
self.Wr ... | AUGRU_Cell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AUGRU_Cell:
def __init__(self, in_dim, hidden_dim):
""":param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度"""
<|body_0|>
def attention(self, x, item):
""":param x: 输入的序列中第t个向量 [ batch_size, dim ] :param item: 目标物品的向量 [ batch_size, dim ] :return: 注意力权重 [ batch_size, 1 ... | stack_v2_sparse_classes_75kplus_train_070930 | 10,235 | no_license | [
{
"docstring": ":param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度",
"name": "__init__",
"signature": "def __init__(self, in_dim, hidden_dim)"
},
{
"docstring": ":param x: 输入的序列中第t个向量 [ batch_size, dim ] :param item: 目标物品的向量 [ batch_size, dim ] :return: 注意力权重 [ batch_size, 1 ]",
"name": "att... | 3 | stack_v2_sparse_classes_30k_train_040838 | Implement the Python class `AUGRU_Cell` described below.
Class description:
Implement the AUGRU_Cell class.
Method signatures and docstrings:
- def __init__(self, in_dim, hidden_dim): :param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度
- def attention(self, x, item): :param x: 输入的序列中第t个向量 [ batch_size, dim ] :param it... | Implement the Python class `AUGRU_Cell` described below.
Class description:
Implement the AUGRU_Cell class.
Method signatures and docstrings:
- def __init__(self, in_dim, hidden_dim): :param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度
- def attention(self, x, item): :param x: 输入的序列中第t个向量 [ batch_size, dim ] :param it... | c7bef7c5ca6e755d0714a688e0c36f35146c8a10 | <|skeleton|>
class AUGRU_Cell:
def __init__(self, in_dim, hidden_dim):
""":param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度"""
<|body_0|>
def attention(self, x, item):
""":param x: 输入的序列中第t个向量 [ batch_size, dim ] :param item: 目标物品的向量 [ batch_size, dim ] :return: 注意力权重 [ batch_size, 1 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AUGRU_Cell:
def __init__(self, in_dim, hidden_dim):
""":param in_dim: 输入向量的维度 :param hidden_dim: 输出的隐藏层维度"""
super(AUGRU_Cell, self).__init__()
self.Wu = init.xavier_uniform_(Parameter(torch.empty(in_dim, hidden_dim)))
self.Uu = init.xavier_uniform_(Parameter(torch.empty(in_dim... | the_stack_v2_python_sparse | chapter3/s34_DIEN.py | chenrj23/recbyhand | train | 0 | |
0ca2159a3671d4848bc7f187c0427c43e5ef534a | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n direction = choice(list(range(361)))\n distance = choice([1, 2])\n x_step = math.cos(direction) * distance\n y_step = math.sin(direction) * distance\n next_x = self.x_values[-1] ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
direction = choice(list(range(361)))
distance = choice([1, 2])
x_step = math.cos(directio... | 一个生成随机漫步数据的类 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=500):
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_points = num_points
self.x_values = [0]
... | stack_v2_sparse_classes_75kplus_train_070931 | 1,537 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, num_points=500)"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000318 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=500): 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=500): 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=500):
"""初始化... | 4f1d59879d94c82fab9142e2ef4fa98486004246 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=500):
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=500):
"""初始化随机漫步的属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while len(self.x_values) < self.num_points:
dir... | the_stack_v2_python_sparse | 醉汉随机漫步.py | ATM0909/Experiment | train | 1 |
b9d3d2b462df2a8140f493f5bcba2bedeef8a8c1 | [
"url = 'http://test.lemonban.com/futureloan/mvc/api/member/register'\nphone = ob.getstr('register', 'phone')\npwd = ob.getstr('register', 'pwd')\ndata = {'mobilephone': phone, 'pwd': pwd, 'regname': 'zhaojian'}\nHttpSession(url=url, data=data).httprequest(method='post')\nsetattr(ConText, 'phone', phone)\nsetattr(Co... | <|body_start_0|>
url = 'http://test.lemonban.com/futureloan/mvc/api/member/register'
phone = ob.getstr('register', 'phone')
pwd = ob.getstr('register', 'pwd')
data = {'mobilephone': phone, 'pwd': pwd, 'regname': 'zhaojian'}
HttpSession(url=url, data=data).httprequest(method='post... | 前置条件类 | PreClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreClass:
"""前置条件类"""
def register(self):
"""注册"""
<|body_0|>
def login(self):
"""登录"""
<|body_1|>
def recharge(self, amount=20000):
"""充值 :param amount: 充值金额 :return:"""
<|body_2|>
def withdraw(self, r_amount=10000, w_amount=500... | stack_v2_sparse_classes_75kplus_train_070932 | 3,994 | no_license | [
{
"docstring": "注册",
"name": "register",
"signature": "def register(self)"
},
{
"docstring": "登录",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "充值 :param amount: 充值金额 :return:",
"name": "recharge",
"signature": "def recharge(self, amount=20000)"
},... | 5 | stack_v2_sparse_classes_30k_train_044815 | Implement the Python class `PreClass` described below.
Class description:
前置条件类
Method signatures and docstrings:
- def register(self): 注册
- def login(self): 登录
- def recharge(self, amount=20000): 充值 :param amount: 充值金额 :return:
- def withdraw(self, r_amount=10000, w_amount=5000): 取现 :param r_amount: 充值金额 :param w_am... | Implement the Python class `PreClass` described below.
Class description:
前置条件类
Method signatures and docstrings:
- def register(self): 注册
- def login(self): 登录
- def recharge(self, amount=20000): 充值 :param amount: 充值金额 :return:
- def withdraw(self, r_amount=10000, w_amount=5000): 取现 :param r_amount: 充值金额 :param w_am... | 685b537408886e3ca1de95d9352fefb76bacc284 | <|skeleton|>
class PreClass:
"""前置条件类"""
def register(self):
"""注册"""
<|body_0|>
def login(self):
"""登录"""
<|body_1|>
def recharge(self, amount=20000):
"""充值 :param amount: 充值金额 :return:"""
<|body_2|>
def withdraw(self, r_amount=10000, w_amount=500... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreClass:
"""前置条件类"""
def register(self):
"""注册"""
url = 'http://test.lemonban.com/futureloan/mvc/api/member/register'
phone = ob.getstr('register', 'phone')
pwd = ob.getstr('register', 'pwd')
data = {'mobilephone': phone, 'pwd': pwd, 'regname': 'zhaojian'}
... | the_stack_v2_python_sparse | common/precondition_context.py | zhaojian0419/zj_api_test | train | 0 |
6ca819871743ece09c4af82fb9aa8090f31d5bd5 | [
"if not super().is_valid():\n return False\nare_types_valid = all([type(self.description) is str, type(self.created_in) is str])\nif not are_types_valid:\n return False\nare_values_valid = all([0 < len(self.description) <= MAX_VALUE_LIMIT, 0 < len(self.created_in) <= MAX_VALUE_LIMIT])\nreturn are_values_valid... | <|body_start_0|>
if not super().is_valid():
return False
are_types_valid = all([type(self.description) is str, type(self.created_in) is str])
if not are_types_valid:
return False
are_values_valid = all([0 < len(self.description) <= MAX_VALUE_LIMIT, 0 < len(self.cr... | Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops | Unit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unit:
"""Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops"""
def is_valid(self) -> bool:
"""Check if the Unit object is valid :return: Boolean, True if valid, False otherwise"""
<|body_0|>
def from_str(da... | stack_v2_sparse_classes_75kplus_train_070933 | 1,642 | no_license | [
{
"docstring": "Check if the Unit object is valid :return: Boolean, True if valid, False otherwise",
"name": "is_valid",
"signature": "def is_valid(self) -> bool"
},
{
"docstring": "Parse a string to object a Structure",
"name": "from_str",
"signature": "def from_str(data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028467 | Implement the Python class `Unit` described below.
Class description:
Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops
Method signatures and docstrings:
- def is_valid(self) -> bool: Check if the Unit object is valid :return: Boolean, True if valid, F... | Implement the Python class `Unit` described below.
Class description:
Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops
Method signatures and docstrings:
- def is_valid(self) -> bool: Check if the Unit object is valid :return: Boolean, True if valid, F... | 31df8c3c17b28ed02920f92bfddca25d1d169762 | <|skeleton|>
class Unit:
"""Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops"""
def is_valid(self) -> bool:
"""Check if the Unit object is valid :return: Boolean, True if valid, False otherwise"""
<|body_0|>
def from_str(da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Unit:
"""Units are train-ables that can be created from specific buildings Ex, military buildings can create military troops"""
def is_valid(self) -> bool:
"""Check if the Unit object is valid :return: Boolean, True if valid, False otherwise"""
if not super().is_valid():
retur... | the_stack_v2_python_sparse | aoe2_api/models/unit.py | agiletelescope/aoe2-api | train | 1 |
7580962eb7f43cd91f7e0d88b757e7d7b8c8190b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service API definition. | MyServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyServiceServicer:
"""Service API definition."""
def LikeAFunction(self, request, context):
"""Similar to a normal function call."""
<|body_0|>
def GetResponseStream(self, request, context):
"""A response-streaming RPC where the client sends a request to the serv... | stack_v2_sparse_classes_75kplus_train_070934 | 11,324 | no_license | [
{
"docstring": "Similar to a normal function call.",
"name": "LikeAFunction",
"signature": "def LikeAFunction(self, request, context)"
},
{
"docstring": "A response-streaming RPC where the client sends a request to the server and gets a stream to read a sequence of messages back. The client read... | 6 | null | Implement the Python class `MyServiceServicer` described below.
Class description:
Service API definition.
Method signatures and docstrings:
- def LikeAFunction(self, request, context): Similar to a normal function call.
- def GetResponseStream(self, request, context): A response-streaming RPC where the client sends ... | Implement the Python class `MyServiceServicer` described below.
Class description:
Service API definition.
Method signatures and docstrings:
- def LikeAFunction(self, request, context): Similar to a normal function call.
- def GetResponseStream(self, request, context): A response-streaming RPC where the client sends ... | 9598af1b8be7ebe8462a0bbfc87a6edfa5063741 | <|skeleton|>
class MyServiceServicer:
"""Service API definition."""
def LikeAFunction(self, request, context):
"""Similar to a normal function call."""
<|body_0|>
def GetResponseStream(self, request, context):
"""A response-streaming RPC where the client sends a request to the serv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyServiceServicer:
"""Service API definition."""
def LikeAFunction(self, request, context):
"""Similar to a normal function call."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not impleme... | the_stack_v2_python_sparse | Python/grpc-hello/basics/generated/my_service_pb2_grpc.py | langenhagen/experiments-and-tutorials | train | 4 |
70edcb73239287b25b55f3bf69d90b40addb98ae | [
"self.doi_prefix = prefix\nif self.doi_prefix[-1] == '/':\n self.doi_prefix = self.doi_prefix[:-1]\nif not message_testing:\n self.message_testing = 'The prefix 10.5072 is invalid. The prefixis only used for testing purposes, and no DOIs with this prefix are attached to any meaningful content.'\nif not messag... | <|body_start_0|>
self.doi_prefix = prefix
if self.doi_prefix[-1] == '/':
self.doi_prefix = self.doi_prefix[:-1]
if not message_testing:
self.message_testing = 'The prefix 10.5072 is invalid. The prefixis only used for testing purposes, and no DOIs with this prefix are att... | Validate if DOI. | InvalidDOIPrefix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
<|body_0|>
def __call__(self, form, field):
"""Validate."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_070935 | 11,750 | no_license | [
{
"docstring": "Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072",
"name": "__init__",
"signature": "def __init__(self, prefix='10.5072', message=None, message_testing=None)"
},
{
"docstring": "Validate.",
"name": "__call__",
"signature": "def __call__(self, form, field)... | 2 | stack_v2_sparse_classes_30k_train_001930 | Implement the Python class `InvalidDOIPrefix` described below.
Class description:
Validate if DOI.
Method signatures and docstrings:
- def __init__(self, prefix='10.5072', message=None, message_testing=None): Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072
- def __call__(self, form, field): Validate... | Implement the Python class `InvalidDOIPrefix` described below.
Class description:
Validate if DOI.
Method signatures and docstrings:
- def __init__(self, prefix='10.5072', message=None, message_testing=None): Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072
- def __call__(self, form, field): Validate... | 4de8910fff569fc9028300c70b63200da521ddb9 | <|skeleton|>
class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
<|body_0|>
def __call__(self, form, field):
"""Validate."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvalidDOIPrefix:
"""Validate if DOI."""
def __init__(self, prefix='10.5072', message=None, message_testing=None):
"""Initialize validator. :param doi_prefix: DOI prefix, e.g. 10.5072"""
self.doi_prefix = prefix
if self.doi_prefix[-1] == '/':
self.doi_prefix = self.doi... | the_stack_v2_python_sparse | inspirehep/modules/forms/validation_utils.py | nikpap/inspire-next | train | 1 |
071b784b2ca0c02070f6c432fcc5bfb44804b9a3 | [
"super(M2VAE, self).__init__(name=name)\nself._classifier = classifier\nself._encoder = encoder\nself._decoder = decoder\nself._latent_prior = latent_prior\nself._latent_posterior = latent_posterior\nself._class_prior = class_prior\nself._class_posterior = class_posterior\nself._output_dist = output_dist\nself._num... | <|body_start_0|>
super(M2VAE, self).__init__(name=name)
self._classifier = classifier
self._encoder = encoder
self._decoder = decoder
self._latent_prior = latent_prior
self._latent_posterior = latent_posterior
self._class_prior = class_prior
self._class_po... | M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models' | M2VAE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class M2VAE:
"""M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models'"""
def __init__(self, classifier, encoder, decoder, latent_prior, latent_posterior, class_prior, class_posterior, output_dist, num_classes, name='m2_vae'):
"""Args: classifier (Tensor... | stack_v2_sparse_classes_75kplus_train_070936 | 5,349 | no_license | [
{
"docstring": "Args: classifier (Tensor -> Tensor): Called $q_\\\\phi(y|x)$, takes data and gives class logits. encoder (Tensor -> Tensor -> (Tensor, Tensor)): Called $q_\\\\phi(z|x,y)$, takes data and class label and outputs loc and scale values. decoder (Tensor -> Tensor): Called $p_ heta(x|y,z)$, takes clas... | 6 | stack_v2_sparse_classes_30k_train_019750 | Implement the Python class `M2VAE` described below.
Class description:
M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models'
Method signatures and docstrings:
- def __init__(self, classifier, encoder, decoder, latent_prior, latent_posterior, class_prior, class_posterior, output_di... | Implement the Python class `M2VAE` described below.
Class description:
M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models'
Method signatures and docstrings:
- def __init__(self, classifier, encoder, decoder, latent_prior, latent_posterior, class_prior, class_posterior, output_di... | 11b322af306daf60c6d3b1784c3cf348f0eed778 | <|skeleton|>
class M2VAE:
"""M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models'"""
def __init__(self, classifier, encoder, decoder, latent_prior, latent_posterior, class_prior, class_posterior, output_dist, num_classes, name='m2_vae'):
"""Args: classifier (Tensor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class M2VAE:
"""M2 VAE model from Kinga et al. 2014 'Semi-supervised Learning with Deep Generative Models'"""
def __init__(self, classifier, encoder, decoder, latent_prior, latent_posterior, class_prior, class_posterior, output_dist, num_classes, name='m2_vae'):
"""Args: classifier (Tensor -> Tensor): ... | the_stack_v2_python_sparse | pyroclast/svae/m2vae.py | DrKwint/pyroclast | train | 9 |
bd31ed958f380889786cee1bbab0a61a7f6de2e1 | [
"result = 0\nprev_length = 0\ncur_length = 1\nfor i in range(1, len(s)):\n if s[i] == s[i - 1]:\n cur_length += 1\n else:\n prev_length = cur_length\n cur_length = 1\n if prev_length >= cur_length:\n result += 1\nreturn result",
"result, prev, curr = (0, 0, 1)\nfor i in xrange... | <|body_start_0|>
result = 0
prev_length = 0
cur_length = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
cur_length += 1
else:
prev_length = cur_length
cur_length = 1
if prev_length >= cur_length:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBinarySubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countBinarySubstrings2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 0
prev_length = 0
cur_l... | stack_v2_sparse_classes_75kplus_train_070937 | 960 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "countBinarySubstrings",
"signature": "def countBinarySubstrings(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countBinarySubstrings2",
"signature": "def countBinarySubstrings2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011822 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBinarySubstrings(self, s): :type s: str :rtype: int
- def countBinarySubstrings2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBinarySubstrings(self, s): :type s: str :rtype: int
- def countBinarySubstrings2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def countBinarySub... | b149d1e8a83b0dfc724bd9dc129a1cad407dd91f | <|skeleton|>
class Solution:
def countBinarySubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countBinarySubstrings2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countBinarySubstrings(self, s):
""":type s: str :rtype: int"""
result = 0
prev_length = 0
cur_length = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
cur_length += 1
else:
prev_length = cur_length
... | the_stack_v2_python_sparse | string/0696_count_binary_substrings/0696_count_binary_substrings.py | zdyxry/LeetCode | train | 6 | |
61a5dff3746d83b2e879a0da368addc3f813edad | [
"dic = {root: None}\n\ndef dfs(node):\n if node:\n if node.left:\n dic[node.left] = node\n if node.right:\n dic[node.right] = node\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nl1, l2 = (p, q)\nwhile l1 != l2:\n l1 = dic.get(l1, q)\n l2 = dic.get(l2, p)\nr... | <|body_start_0|>
dic = {root: None}
def dfs(node):
if node:
if node.left:
dic[node.left] = node
if node.right:
dic[node.right] = node
dfs(node.left)
dfs(node.right)
dfs(root)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:递归"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_070938 | 5,443 | no_license | [
{
"docstring": "思路:存储父节点",
"name": "lowestCommonAncestor1",
"signature": "def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "思路:递归",
"name": "lowestCommonAncestor2",
"signature": "def lowestCommonAncestor2(self, root: 'TreeNo... | 2 | stack_v2_sparse_classes_30k_train_030514 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 思路:存储父节点
- def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'Tre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 思路:存储父节点
- def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'Tre... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:递归"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
dic = {root: None}
def dfs(node):
if node:
if node.left:
dic[node.left] = node
if node.right:
... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/236. Lowest Common Ancestor of a Binary Tree.py | yiming1012/MyLeetCode | train | 2 | |
4e62ed0bb7122f7534f549049242d1dd37a53777 | [
"key = 'job_id, group_name, start_time, repeat_count, cron, path, method, params'\nvalue_tuple = (params['job_id'], params.get('group_name', 'default'), params['start_time'], params.get('repeat_count', 0), params.get('cron', ''), params['path'], params['method'], self.json.dumps(params['params'], cls=self.date_enco... | <|body_start_0|>
key = 'job_id, group_name, start_time, repeat_count, cron, path, method, params'
value_tuple = (params['job_id'], params.get('group_name', 'default'), params['start_time'], params.get('repeat_count', 0), params.get('cron', ''), params['path'], params['method'], self.json.dumps(params['p... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def save_job(self, params):
"""保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'] service路径 param['method'] 方法 param['params'] 参数 :return:"""
<|body_0|>
def upda... | stack_v2_sparse_classes_75kplus_train_070939 | 4,715 | no_license | [
{
"docstring": "保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'] service路径 param['method'] 方法 param['params'] 参数 :return:",
"name": "save_job",
"signature": "def save_job(self, params)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_001075 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def save_job(self, params): 保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def save_job(self, params): 保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'... | 7f327efd6f082ee2d4516454a8b02f5134834b0d | <|skeleton|>
class Model:
def save_job(self, params):
"""保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'] service路径 param['method'] 方法 param['params'] 参数 :return:"""
<|body_0|>
def upda... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
def save_job(self, params):
"""保存定时任务 :param params: param['job_id'] 任务id param['group_name'] 任务组名 param['start_time'] 任务开始时间 param['repeat_count'] 重复次数 param['cron'] cron表达式 param['path'] service路径 param['method'] 方法 param['params'] 参数 :return:"""
key = 'job_id, group_name, start_time,... | the_stack_v2_python_sparse | src/task/schedule/model.py | yuiitsu/Torplugins | train | 0 | |
d46dbdc7817e80d9a01d72ded7b4fe60ec4d5ed9 | [
"global _REGISTRY\nregistry_entry = veredi.get().get(_REGISTRY, Null())\nsub_entry = registry_entry.get(key, Null())\nreturn sub_entry",
"context = klass._get(_REGISTRARS)\n_set(context, register, data, ownership)\nregistrees = klass._get(_REGISTREES)\nregistrees[register] = {}",
"all_registries = klass._get(_R... | <|body_start_0|>
global _REGISTRY
registry_entry = veredi.get().get(_REGISTRY, Null())
sub_entry = registry_entry.get(key, Null())
return sub_entry
<|end_body_0|>
<|body_start_1|>
context = klass._get(_REGISTRARS)
_set(context, register, data, ownership)
registre... | registry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
<|body_0|>
def registrar(klass: Type['registry'], register: label.DotStr, data: ContextMap, ownership: Ownership) -> None:
... | stack_v2_sparse_classes_75kplus_train_070940 | 45,187 | no_license | [
{
"docstring": "Get registry's full sub-context from background context.",
"name": "_get",
"signature": "def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]"
},
{
"docstring": "Adds `register`'s dotted label and background data to the background's registrars.",
"name":... | 3 | stack_v2_sparse_classes_30k_val_002700 | Implement the Python class `registry` described below.
Class description:
Implement the registry class.
Method signatures and docstrings:
- def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]: Get registry's full sub-context from background context.
- def registrar(klass: Type['registry'], regi... | Implement the Python class `registry` described below.
Class description:
Implement the registry class.
Method signatures and docstrings:
- def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]: Get registry's full sub-context from background context.
- def registrar(klass: Type['registry'], regi... | 8c9fc1170ceac335985686571568eebf08b0db7a | <|skeleton|>
class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
<|body_0|>
def registrar(klass: Type['registry'], register: label.DotStr, data: ContextMap, ownership: Ownership) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class registry:
def _get(klass: Type['registry'], key: str) -> Nullable[ContextMutableMap]:
"""Get registry's full sub-context from background context."""
global _REGISTRY
registry_entry = veredi.get().get(_REGISTRY, Null())
sub_entry = registry_entry.get(key, Null())
return ... | the_stack_v2_python_sparse | data/background.py | cole-brown/veredi-code | train | 1 | |
b08a36702e12c0069eecad1ca9161dc0187486a3 | [
"self.a = a\nself.b = b\nself.mu = mu\nself.lamda = lamda\nself.max_iter = max_iter\nself.threshold = threshold",
"N = len(X)\nX_sum = X.sum()\nX2_sum = np.sum(X ** 2)\nE_tau = init_tau\nmu_N = (self.lamda * self.mu + X_sum) / (self.lamda + N)\nlam_N = (self.lamda + N) * E_tau\nfor _ in range(self.max_iter):\n ... | <|body_start_0|>
self.a = a
self.b = b
self.mu = mu
self.lamda = lamda
self.max_iter = max_iter
self.threshold = threshold
<|end_body_0|>
<|body_start_1|>
N = len(X)
X_sum = X.sum()
X2_sum = np.sum(X ** 2)
E_tau = init_tau
mu_N = (... | VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (float): threshold | VariationalGauss1D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariationalGauss1D:
"""VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (float): threshold"""
def __init__(se... | stack_v2_sparse_classes_75kplus_train_070941 | 16,219 | permissive | [
{
"docstring": "Args: a,b (float): hyper parameter for prior distibution mu,lamda (float): hyper parameter for prior distibution max_iter (int): max iteration threshold (float): threshold",
"name": "__init__",
"signature": "def __init__(self, a=0, b=0, mu=0, lamda=0, max_iter=1000, threshold=0.01)"
},... | 2 | null | Implement the Python class `VariationalGauss1D` described below.
Class description:
VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (fl... | Implement the Python class `VariationalGauss1D` described below.
Class description:
VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (fl... | 992f2c07e88b2bad331e08303bdba84684f04d40 | <|skeleton|>
class VariationalGauss1D:
"""VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (float): threshold"""
def __init__(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VariationalGauss1D:
"""VariationalGauss1D approximately predict posterior distribution for gaussian Attributes: a,b (float): parameter for posterior distibution mu,lamda (float): parameter for posterior distibution max_iter (int): max iteration threshold (float): threshold"""
def __init__(self, a=0, b=0,... | the_stack_v2_python_sparse | prml/approximate_inference.py | hedwig100/PRML | train | 1 |
6f041c97fa83aba073553b8c8e5e258a8e1841fa | [
"super().__init__(zone, dt, cavity_label, fault_label, cavity_conf, fault_conf, label_source, data_dir)\nself.e_type = ExampleType.WINDOWED_EXAMPLE\nself.start = start\nself.n_samples = n_samples\nself.end = None",
"super().load_data(verbose)\nif self.event_df.Time.min() > self.start:\n raise RuntimeError('Req... | <|body_start_0|>
super().__init__(zone, dt, cavity_label, fault_label, cavity_conf, fault_conf, label_source, data_dir)
self.e_type = ExampleType.WINDOWED_EXAMPLE
self.start = start
self.n_samples = n_samples
self.end = None
<|end_body_0|>
<|body_start_1|>
super().load_d... | An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is variable depending on control system settings. An Exception is raised at load tim... | WindowedExample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowedExample:
"""An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is variable depending on control system s... | stack_v2_sparse_classes_75kplus_train_070942 | 32,091 | no_license | [
{
"docstring": "Construct an instance th will only store the required window upon a load_data() call. Arguments: start: The start of the time window. n_samples: The number of samples to include after the start of the window.",
"name": "__init__",
"signature": "def __init__(self, zone: str, dt: datetime,... | 2 | stack_v2_sparse_classes_30k_train_035283 | Implement the Python class `WindowedExample` described below.
Class description:
An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is... | Implement the Python class `WindowedExample` described below.
Class description:
An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is... | 7003c8bd6f9907b3a2eef1d61fbdd6949b2df73c | <|skeleton|>
class WindowedExample:
"""An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is variable depending on control system s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WindowedExample:
"""An extension of Example class that allows the caller to specify only a time-window of event_df be returned. This window is based on the relative values in the Time column. The standard time range is approximately [-1500, 100], but this is variable depending on control system settings. An E... | the_stack_v2_python_sparse | rfwtools/example.py | slominskir/rfwtools | train | 0 |
78542a5ff70ac979ff04fbb01977fb9cc54c762f | [
"head = ListNode(0)\ntail = head\nqueue = PriorityQueue()\ncount = 0\nfor item in lists:\n if item:\n queue.put((item.val, count, item))\n count += 1\nwhile not queue.empty():\n val, count, node = queue.get()\n tail.next = node\n tail = tail.next\n node = node.next\n if node:\n ... | <|body_start_0|>
head = ListNode(0)
tail = head
queue = PriorityQueue()
count = 0
for item in lists:
if item:
queue.put((item.val, count, item))
count += 1
while not queue.empty():
val, count, node = queue.get()
... | 题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6"""
def mergeKLists(self, lists) -> ListNode:
"""优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增的count值进行区分), 然后依次从优先队列中取出一个元素 :param lists: :return:"""
... | stack_v2_sparse_classes_75kplus_train_070943 | 2,912 | no_license | [
{
"docstring": "优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增的count值进行区分), 然后依次从优先队列中取出一个元素 :param lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists) -> ListNode"
},
{
"docstring": "每次拿出一个链表和已有的链表进行合并 :param lists: :return:",
"name": "m... | 4 | stack_v2_sparse_classes_30k_train_036977 | Implement the Python class `Solution` described below.
Class description:
题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
Method signatures and docstrings:
- def mergeKLists(self, lists) -> ListNode: 优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增... | Implement the Python class `Solution` described below.
Class description:
题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
Method signatures and docstrings:
- def mergeKLists(self, lists) -> ListNode: 优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增... | dae77e21032ea5a59b9942f8a37e8c14566b5224 | <|skeleton|>
class Solution:
"""题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6"""
def mergeKLists(self, lists) -> ListNode:
"""优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增的count值进行区分), 然后依次从优先队列中取出一个元素 :param lists: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""题目: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6"""
def mergeKLists(self, lists) -> ListNode:
"""优先队列:先把lists里面的每个列表都放进优先队列中, 在优先队列中按照头节点的值排序(为了在有相同元素时也能够进行排序,加入一个递增的count值进行区分), 然后依次从优先队列中取出一个元素 :param lists: :return:"""
head ... | the_stack_v2_python_sparse | 合并K个排序链表.py | jony0113/leetcode | train | 0 |
6eddb41f6f0e081a43c3adb26d283008e5fd2610 | [
"with tables(db.engine, 'user_comments') as (con, comments):\n q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))\n return [dict(c) for c in q.execute().fetchall()]",
"with tables(db.engine, 'user_comments') as (con, comments):\n q = comments.insert().values(vcf_id=ru... | <|body_start_0|>
with tables(db.engine, 'user_comments') as (con, comments):
q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))
return [dict(c) for c in q.execute().fetchall()]
<|end_body_0|>
<|body_start_1|>
with tables(db.engine, 'user_comm... | CommentList | [
"Apache-2.0",
"CC-BY-3.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
<|body_0|>
def post(self, run_id):
"""Create a comment."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with tables(db.engine, 'user_comments') as (con, comments):
q =... | stack_v2_sparse_classes_75kplus_train_070944 | 8,737 | permissive | [
{
"docstring": "Get a list of all comments.",
"name": "get",
"signature": "def get(self, run_id)"
},
{
"docstring": "Create a comment.",
"name": "post",
"signature": "def post(self, run_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013405 | Implement the Python class `CommentList` described below.
Class description:
Implement the CommentList class.
Method signatures and docstrings:
- def get(self, run_id): Get a list of all comments.
- def post(self, run_id): Create a comment. | Implement the Python class `CommentList` described below.
Class description:
Implement the CommentList class.
Method signatures and docstrings:
- def get(self, run_id): Get a list of all comments.
- def post(self, run_id): Create a comment.
<|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a... | a436c4fc212e4429fb5196a9a4d36c37bd050c52 | <|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
<|body_0|>
def post(self, run_id):
"""Create a comment."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
with tables(db.engine, 'user_comments') as (con, comments):
q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))
return [dict(c) for c in q.execute().fetchall()]
... | the_stack_v2_python_sparse | cycledash/api/comments.py | haoziyeung/cycledash | train | 0 | |
4ba225b07a6d3d0528ffcecb49153fd9ba34d658 | [
"self.description = self.brief = self.author = self.license = self.license_url = self.url = self.status = self.version = self.notes = ''\nself.depends = []\nself.rosdeps = []\nself.exports = []\nself.platforms = []\nself.is_catkin = is_catkin\nself.type = type_\nself.filename = filename\nself.unknown_tags = []",
... | <|body_start_0|>
self.description = self.brief = self.author = self.license = self.license_url = self.url = self.status = self.version = self.notes = ''
self.depends = []
self.rosdeps = []
self.exports = []
self.platforms = []
self.is_catkin = is_catkin
self.type ... | Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``) | Manifest | [
"BSD-3-Clause",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${pref... | stack_v2_sparse_classes_75kplus_train_070945 | 17,667 | permissive | [
{
"docstring": ":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${prefix}`` in ``<export>`` values, ``str``.",
"name": "__init__",
"signature": "def __init__(self, type_='package', filename=None, is_catkin=False)"
},
{
"docstring": ":pa... | 2 | stack_v2_sparse_classes_30k_train_024371 | Implement the Python class `Manifest` described below.
Class description:
Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)
Method signatures and docstrings:
- def __init__(self, type_='package', filename=None, is_catkin=False): :param type: `'package'` or `'stack'` :param filename: lo... | Implement the Python class `Manifest` described below.
Class description:
Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)
Method signatures and docstrings:
- def __init__(self, type_='package', filename=None, is_catkin=False): :param type: `'package'` or `'stack'` :param filename: lo... | 1f3039edd24c059459563cb81d194326fe824905 | <|skeleton|>
class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${pref... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Manifest:
"""Object representation of a ROS manifest file (``manifest.xml`` and ``stack.xml``)"""
def __init__(self, type_='package', filename=None, is_catkin=False):
""":param type: `'package'` or `'stack'` :param filename: location of manifest file. Necessary if converting ``${prefix}`` in ``<e... | the_stack_v2_python_sparse | arm/usr/lib/python2.7/dist-packages/rospkg/manifest.py | Roboy/roboy_plexus | train | 2 |
347742d07c623bc4c91b6d8fa90d2bb14ae0ee3b | [
"super().__init__(config, global_config, parent)\nself._temp_dir = self.config.get('temp_dir')\nself.register([self.temp_dir_context])",
"if path is None and self._temp_dir is None:\n return TemporaryDirectory()\nreturn nullcontext(path or self._temp_dir)"
] | <|body_start_0|>
super().__init__(config, global_config, parent)
self._temp_dir = self.config.get('temp_dir')
self.register([self.temp_dir_context])
<|end_body_0|>
<|body_start_1|>
if path is None and self._temp_dir is None:
return TemporaryDirectory()
return nullcon... | A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service. | TempDirContextService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TempDirContextService:
"""A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service."""
def __init__(self, config: Option... | stack_v2_sparse_classes_75kplus_train_070946 | 2,199 | permissive | [
{
"docstring": "Create a new instance of a service that provides temporary directory context for local exec service. Parameters ---------- config : dict Free-format dictionary that contains parameters for the service. (E.g., root path for config files, etc.) global_config : dict Free-format dictionary of global... | 2 | stack_v2_sparse_classes_30k_train_002900 | Implement the Python class `TempDirContextService` described below.
Class description:
A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service.
M... | Implement the Python class `TempDirContextService` described below.
Class description:
A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service.
M... | 0db80043dad256d77dc4c2b4fc54aa0b0aa2597f | <|skeleton|>
class TempDirContextService:
"""A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service."""
def __init__(self, config: Option... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TempDirContextService:
"""A *base* service class that provides a method to create a temporary directory context for local scripts. It is inherited by LocalExecService and MockLocalExecService. This class is not supposed to be used as a standalone service."""
def __init__(self, config: Optional[Dict[str, ... | the_stack_v2_python_sparse | mlos_bench/mlos_bench/services/local/temp_dir_context.py | microsoft/MLOS | train | 109 |
c206f530b3c09740c0c07890e168a85bcf1751d8 | [
"self.collection = mongo.db.node\ntry:\n __data = list(self.collection.find({}, {'_id': 0}).sort([('_id', 1)]))\n code = 20000\n data = {'total': len(__data), 'items': __data}\nexcept Exception as e:\n code = 40000\n data = {'message': str(e)}\nreturn self.create_response(code, data)",
"collection ... | <|body_start_0|>
self.collection = mongo.db.node
try:
__data = list(self.collection.find({}, {'_id': 0}).sort([('_id', 1)]))
code = 20000
data = {'total': len(__data), 'items': __data}
except Exception as e:
code = 40000
data = {'messag... | Node | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def get(self):
""":return:"""
<|body_0|>
def post(self):
"""新建、更新 节点 :return:"""
<|body_1|>
def delete(self):
"""删除节点 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.collection = mongo.db.node
try:
... | stack_v2_sparse_classes_75kplus_train_070947 | 2,152 | permissive | [
{
"docstring": ":return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新建、更新 节点 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "删除节点 :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | null | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): 新建、更新 节点 :return:
- def delete(self): 删除节点 :return: | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): 新建、更新 节点 :return:
- def delete(self): 删除节点 :return:
<|skeleton|>
class Node:
def get(self):
""":return:"""
<|body_0|>
... | de6c7fa3ded6b936328e6fc678f2e6f7b098de39 | <|skeleton|>
class Node:
def get(self):
""":return:"""
<|body_0|>
def post(self):
"""新建、更新 节点 :return:"""
<|body_1|>
def delete(self):
"""删除节点 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def get(self):
""":return:"""
self.collection = mongo.db.node
try:
__data = list(self.collection.find({}, {'_id': 0}).sort([('_id', 1)]))
code = 20000
data = {'total': len(__data), 'items': __data}
except Exception as e:
cod... | the_stack_v2_python_sparse | server/pmon/resource/node.py | yolylight/PMon | train | 0 | |
628ba21db6aed06ad4782946de5e71945992f56a | [
"filepath = cls._convert_filepath(filepath)\nif filepath.suffix == '.mol2':\n return cls._from_mol2_file(filepath, compute2d)\nelif filepath.suffix == '.pdb':\n return cls._from_pdb_file(filepath, compute2d)\nelse:\n raise ValueError(f'The {filepath.suffix} format is not supported or invalid.')",
"if ext... | <|body_start_0|>
filepath = cls._convert_filepath(filepath)
if filepath.suffix == '.mol2':
return cls._from_mol2_file(filepath, compute2d)
elif filepath.suffix == '.pdb':
return cls._from_pdb_file(filepath, compute2d)
else:
raise ValueError(f'The {file... | Parse a structure as an RDKit molecule. | Rdkit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rdkit:
"""Parse a structure as an RDKit molecule."""
def from_file(cls, filepath, compute2d=True):
"""Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb and mol2 files only. compute2d : bool Compute 2D coordin... | stack_v2_sparse_classes_75kplus_train_070948 | 4,192 | permissive | [
{
"docstring": "Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb and mol2 files only. compute2d : bool Compute 2D coordinates for ligand (default). Returns ------- rdkit.Chem.rdchem.Mol Structure as RDKit molecule object.",
"name":... | 6 | null | Implement the Python class `Rdkit` described below.
Class description:
Parse a structure as an RDKit molecule.
Method signatures and docstrings:
- def from_file(cls, filepath, compute2d=True): Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb... | Implement the Python class `Rdkit` described below.
Class description:
Parse a structure as an RDKit molecule.
Method signatures and docstrings:
- def from_file(cls, filepath, compute2d=True): Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb... | c76e87c4fdcb822dfc025e6cb87c34c9e17505d2 | <|skeleton|>
class Rdkit:
"""Parse a structure as an RDKit molecule."""
def from_file(cls, filepath, compute2d=True):
"""Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb and mol2 files only. compute2d : bool Compute 2D coordin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rdkit:
"""Parse a structure as an RDKit molecule."""
def from_file(cls, filepath, compute2d=True):
"""Load structures as RDKit molecule from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb and mol2 files only. compute2d : bool Compute 2D coordinates for liga... | the_stack_v2_python_sparse | opencadd/io/rdkit.py | volkamerlab/opencadd | train | 62 |
e11ec8987841e7bea94259bfe18067ee3ac06ecf | [
"self.title = 'Convert Miles to Kilometres'\nself.root = Builder.load_file('convert_miles_km.kv')\nreturn self.root",
"value = self.get_valid_input()\nresult = value * MILES_TO_KM\nself.root.ids.output_label.text = str(result)",
"try:\n value = float(self.root.ids.input_number.text)\n return value\nexcept... | <|body_start_0|>
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
value = self.get_valid_input()
result = value * MILES_TO_KM
self.root.ids.output_label.text = str(result)
<|e... | MilesToKilometresApp is a Kivy app to convert miles to kilometres | MilesToKilometresApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MilesToKilometresApp:
"""MilesToKilometresApp is a Kivy app to convert miles to kilometres"""
def build(self):
"""Build kivy app from kv file"""
<|body_0|>
def handle_convert(self):
"""Handle conversion, output result to label widget"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus_train_070949 | 1,375 | no_license | [
{
"docstring": "Build kivy app from kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Handle conversion, output result to label widget",
"name": "handle_convert",
"signature": "def handle_convert(self)"
},
{
"docstring": "Handle invalid input. If valid,... | 4 | stack_v2_sparse_classes_30k_train_019942 | Implement the Python class `MilesToKilometresApp` described below.
Class description:
MilesToKilometresApp is a Kivy app to convert miles to kilometres
Method signatures and docstrings:
- def build(self): Build kivy app from kv file
- def handle_convert(self): Handle conversion, output result to label widget
- def ge... | Implement the Python class `MilesToKilometresApp` described below.
Class description:
MilesToKilometresApp is a Kivy app to convert miles to kilometres
Method signatures and docstrings:
- def build(self): Build kivy app from kv file
- def handle_convert(self): Handle conversion, output result to label widget
- def ge... | 77aa106b05c613300d5870ef673fcb77c7ef8d2a | <|skeleton|>
class MilesToKilometresApp:
"""MilesToKilometresApp is a Kivy app to convert miles to kilometres"""
def build(self):
"""Build kivy app from kv file"""
<|body_0|>
def handle_convert(self):
"""Handle conversion, output result to label widget"""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MilesToKilometresApp:
"""MilesToKilometresApp is a Kivy app to convert miles to kilometres"""
def build(self):
"""Build kivy app from kv file"""
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
def handle... | the_stack_v2_python_sparse | prac_07/KivyDemos-master/convert_miles_km.py | SharonReginaSutio99/Python-basic | train | 0 |
09a1b6c560f856e1d686ae30b19f01eb21edce10 | [
"painter = QPainter(self.outPixmap())\npainter.drawPixmap(QPoint(0, 0), self.startPixmap())\nreturn (-1.0, 1.0)",
"out = self.outPixmap()\npainter = QPainter(out)\npainter.eraseRect(0, 0, out.width(), out.height())\nif alpha < 0.0:\n alpha = -1.0 * alpha\n source = self.startPixmap()\nelse:\n source = se... | <|body_start_0|>
painter = QPainter(self.outPixmap())
painter.drawPixmap(QPoint(0, 0), self.startPixmap())
return (-1.0, 1.0)
<|end_body_0|>
<|body_start_1|>
out = self.outPixmap()
painter = QPainter(out)
painter.eraseRect(0, 0, out.width(), out.height())
if alph... | A QPixmapTransition which animates using a fade effect. | QFadeTransition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QFadeTransition:
"""A QPixmapTransition which animates using a fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the relevant pixmaps into the output usi... | stack_v2_sparse_classes_75kplus_train_070950 | 14,565 | permissive | [
{
"docstring": "Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the relevant pixmaps into the output using an appropriate alpha.",
"name": "preparePixmap",
"signature": "def preparePixmap(self)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_002542 | Implement the Python class `QFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition u... | Implement the Python class `QFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition u... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QFadeTransition:
"""A QPixmapTransition which animates using a fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the relevant pixmaps into the output usi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QFadeTransition:
"""A QPixmapTransition which animates using a fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the relevant pixmaps into the output using an appropr... | the_stack_v2_python_sparse | enaml/qt/q_pixmap_transition.py | MatthieuDartiailh/enaml | train | 26 |
8e581894042921bac01b3ca0de37f67d994e4a12 | [
"log.debug('Initiate SingleBiSBiS <Virtual View>')\nsuper(SingleBiSBiSVirtualizer, self).__init__(id=id, global_view=global_view, type=self.TYPE)\nself.sbb_id = sbb_id",
"dov = self.global_view.get_resource_info()\nif dov.is_empty():\n log.warning('Requested global resource view is empty! Return the default em... | <|body_start_0|>
log.debug('Initiate SingleBiSBiS <Virtual View>')
super(SingleBiSBiSVirtualizer, self).__init__(id=id, global_view=global_view, type=self.TYPE)
self.sbb_id = sbb_id
<|end_body_0|>
<|body_start_1|>
dov = self.global_view.get_resource_info()
if dov.is_empty():
... | Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view. | SingleBiSBiSVirtualizer | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type glob... | stack_v2_sparse_classes_75kplus_train_070951 | 29,468 | permissive | [
{
"docstring": "Init. :param global_view: virtualizer instance represents the global view :type global_view: :any:`DomainVirtualizer` :param id: id of the assigned entity :type: id: str :param kwargs: optional parameters for Virtualizer :type kwargs: dict :return: None",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_042027 | Implement the Python class `SingleBiSBiSVirtualizer` described below.
Class description:
Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view.
Method signatures and docstrings:
- def __init__(self, global_view, id, sbb_id=None, **kwargs): Init. :param global_view: v... | Implement the Python class `SingleBiSBiSVirtualizer` described below.
Class description:
Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view.
Method signatures and docstrings:
- def __init__(self, global_view, id, sbb_id=None, **kwargs): Init. :param global_view: v... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type glob... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleBiSBiSVirtualizer:
"""Actual Virtualizer class for ESCAPEv2. Default virtualizer class which offer the trivial one BisBis view."""
def __init__(self, global_view, id, sbb_id=None, **kwargs):
"""Init. :param global_view: virtualizer instance represents the global view :type global_view: :any... | the_stack_v2_python_sparse | escape/escape/adapt/virtualization.py | JerryLX/escape | train | 0 |
361fa07c13e65b449cd400f40a5ce6665624e1f6 | [
"self._config = config\nself._project_name = project_name\nself._repo_name = repo_name\nself._config['database'] = db_name\nself._logging_util = LoggingUtil()\nlog_path = log_path + 'extract-relations-' + db_name + '.log'\nself._logger = self._logging_util.get_logger(log_path)\nself._fileHandler = self._logging_uti... | <|body_start_0|>
self._config = config
self._project_name = project_name
self._repo_name = repo_name
self._config['database'] = db_name
self._logging_util = LoggingUtil()
log_path = log_path + 'extract-relations-' + db_name + '.log'
self._logger = self._logging_ut... | Extract dependency information for all repo files and load into the mysql datatables | DependencyExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyExtractor:
"""Extract dependency information for all repo files and load into the mysql datatables"""
def __init__(self, config, db_name, project_name, repo_name, log_path):
"""initializer :param config: mysql database config dict :type config: dict :param db_name: mysql da... | stack_v2_sparse_classes_75kplus_train_070952 | 2,349 | permissive | [
{
"docstring": "initializer :param config: mysql database config dict :type config: dict :param db_name: mysql database name :type db_name: str :type project_name: str :param project_name: the name of an existing project in the DB :param repo_name: git repo name :type repo_name: str :type log_path: str :param l... | 2 | stack_v2_sparse_classes_30k_train_024613 | Implement the Python class `DependencyExtractor` described below.
Class description:
Extract dependency information for all repo files and load into the mysql datatables
Method signatures and docstrings:
- def __init__(self, config, db_name, project_name, repo_name, log_path): initializer :param config: mysql databas... | Implement the Python class `DependencyExtractor` described below.
Class description:
Extract dependency information for all repo files and load into the mysql datatables
Method signatures and docstrings:
- def __init__(self, config, db_name, project_name, repo_name, log_path): initializer :param config: mysql databas... | b82dbf8d6fb9a9e74bb656c618ed2fdc82dbd635 | <|skeleton|>
class DependencyExtractor:
"""Extract dependency information for all repo files and load into the mysql datatables"""
def __init__(self, config, db_name, project_name, repo_name, log_path):
"""initializer :param config: mysql database config dict :type config: dict :param db_name: mysql da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DependencyExtractor:
"""Extract dependency information for all repo files and load into the mysql datatables"""
def __init__(self, config, db_name, project_name, repo_name, log_path):
"""initializer :param config: mysql database config dict :type config: dict :param db_name: mysql database name :... | the_stack_v2_python_sparse | importers/dependencies/extract_relations.py | SOM-Research/Gitana | train | 68 |
29e643750d6747ecc7396d878cc8b9eced93da31 | [
"soup = BeautifulSoup(response.content, 'html.parser')\nmenu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]\nfor li in menu_tag.find_all('div'):\n url = li.a.get('href')\n if not url.startswith('http'):\n url = ''.join([self.domain, url])\n yield url",
"try:\n soup = BeautifulSoup(response... | <|body_start_0|>
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]
for li in menu_tag.find_all('div'):
url = li.a.get('href')
if not url.startswith('http'):
url = ''.join([self.domain, url])
... | 廖雪峰Python3教程 | LiaoxuefengPythonCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiaoxuefengPythonCrawler:
"""廖雪峰Python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response:爬虫返回的response对象 :return: 返回处理后的html文本"""
... | stack_v2_sparse_classes_75kplus_train_070953 | 8,633 | no_license | [
{
"docstring": "解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器",
"name": "parse_menu",
"signature": "def parse_menu(self, response)"
},
{
"docstring": "解析正文 :param response:爬虫返回的response对象 :return: 返回处理后的html文本",
"name": "parse_body",
"signature": "def parse_body(sel... | 2 | null | Implement the Python class `LiaoxuefengPythonCrawler` described below.
Class description:
廖雪峰Python3教程
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response:爬虫返回的response对象 :return:... | Implement the Python class `LiaoxuefengPythonCrawler` described below.
Class description:
廖雪峰Python3教程
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response:爬虫返回的response对象 :return:... | d97a0eec9838dccaa95e2542e9803ea6a9c3a83b | <|skeleton|>
class LiaoxuefengPythonCrawler:
"""廖雪峰Python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response:爬虫返回的response对象 :return: 返回处理后的html文本"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LiaoxuefengPythonCrawler:
"""廖雪峰Python3教程"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response: 爬虫返回的response对象 :return: url生成器"""
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='uk-nav uk-nav-side')[1]
for li in m... | the_stack_v2_python_sparse | miniproject/html2pdf/crawler_lxf.py | cangyunye/OriOfEvery | train | 2 |
eebb064fbbcd1ff76eae9bdf978ffdba53869b29 | [
"num = int(n)\nmax_l = len(bin(num)) - 2\nprint(num, max_l)\nfor i in range(max_l, 0, -1):\n high = num\n low = 2\n while low <= high:\n mid = (low + high) // 2\n val = mid ** i - num * mid\n if val > 1 - num:\n high = mid - 1\n elif val < 1 - num:\n low = ... | <|body_start_0|>
num = int(n)
max_l = len(bin(num)) - 2
print(num, max_l)
for i in range(max_l, 0, -1):
high = num
low = 2
while low <= high:
mid = (low + high) // 2
val = mid ** i - num * mid
if val > 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def smallestGoodBase(self, n):
""":type n: str :rtype: str 446ms"""
<|body_0|>
def smallestGoodBase_1(self, n):
""":type n: str :rtype: str 47ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = int(n)
max_l = len(bin(num)) - 2... | stack_v2_sparse_classes_75kplus_train_070954 | 1,799 | no_license | [
{
"docstring": ":type n: str :rtype: str 446ms",
"name": "smallestGoodBase",
"signature": "def smallestGoodBase(self, n)"
},
{
"docstring": ":type n: str :rtype: str 47ms",
"name": "smallestGoodBase_1",
"signature": "def smallestGoodBase_1(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035669 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestGoodBase(self, n): :type n: str :rtype: str 446ms
- def smallestGoodBase_1(self, n): :type n: str :rtype: str 47ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestGoodBase(self, n): :type n: str :rtype: str 446ms
- def smallestGoodBase_1(self, n): :type n: str :rtype: str 47ms
<|skeleton|>
class Solution:
def smallestGood... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def smallestGoodBase(self, n):
""":type n: str :rtype: str 446ms"""
<|body_0|>
def smallestGoodBase_1(self, n):
""":type n: str :rtype: str 47ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def smallestGoodBase(self, n):
""":type n: str :rtype: str 446ms"""
num = int(n)
max_l = len(bin(num)) - 2
print(num, max_l)
for i in range(max_l, 0, -1):
high = num
low = 2
while low <= high:
mid = (low + hi... | the_stack_v2_python_sparse | SmallestGoodBase_HARD_483.py | 953250587/leetcode-python | train | 2 | |
a0f755f14598f0143e33906c49a6ec6d97d8975b | [
"for line in f.readlines():\n line = line.strip()\n if len(line) <= 0 or line[0] == '#':\n continue\n key, value = line.split('=', 1)\n if not value.rfind('#') == -1:\n value = value[:value.rfind('#')]\n self._data[key] = value.strip()\nreturn self._data",
"for val in data.iteritems()... | <|body_start_0|>
for line in f.readlines():
line = line.strip()
if len(line) <= 0 or line[0] == '#':
continue
key, value = line.split('=', 1)
if not value.rfind('#') == -1:
value = value[:value.rfind('#')]
self._data[key... | <comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en> | K2V | [
"MIT",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class K2V:
"""<comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
def do_read(self, f):
"""<comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_070955 | 2,713 | permissive | [
{
"docstring": "<comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: English Comment </comment-en>",
"name": "do_read",
"signature": "def do_read(self, f)"
},
{
"docstring": "<comment-ja>データを、読み込んだデータとマージ(上書き)します。 書き込んだデータを再読みし、データを返却します。 @param data: マージデータ @param data: ... | 2 | stack_v2_sparse_classes_30k_test_001539 | Implement the Python class `K2V` described below.
Class description:
<comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en>
Method signatures and docstrings:
- def do_read(self, f): <comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: Engl... | Implement the Python class `K2V` described below.
Class description:
<comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en>
Method signatures and docstrings:
- def do_read(self, f): <comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: Engl... | f4ba1cf6f88cf76c3e4dbc444139d73134f7c9d1 | <|skeleton|>
class K2V:
"""<comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
def do_read(self, f):
"""<comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class K2V:
"""<comment-ja> key=value形式のファイルのread/writeを行うクラス </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
def do_read(self, f):
"""<comment-ja>設定ファイルの読み込みを行います。 @return: dict </comment-ja> <comment-en> TODO: English Comment </comment-en>"""
for line in f.readlines():
... | the_stack_v2_python_sparse | karesansui/lib/file/k2v.py | qmutz/karesansui | train | 0 |
e3c55aa3b270cd02875a38f1de2dc7645deb2a0f | [
"if not model.optimizer or not model.loss:\n raise Exception('model is not compiled. please compile your model first.')\nself.model = model\nself.model.build()\nself.init_weights = condense.keras.wrappers.get_internal_weights(self.model)\nself.mask = []\nself.t_sparsity = t_sparsity\nself.history = {}\nself.trai... | <|body_start_0|>
if not model.optimizer or not model.loss:
raise Exception('model is not compiled. please compile your model first.')
self.model = model
self.model.build()
self.init_weights = condense.keras.wrappers.get_internal_weights(self.model)
self.mask = []
... | Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer for training (defaults to SGD). loss: Loss function. history (dict): A di... | Trainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer for training (defaults to SGD). loss: ... | stack_v2_sparse_classes_75kplus_train_070956 | 5,659 | permissive | [
{
"docstring": "Constructor. Args: model (keras.models.Model): An unpruned keras model t_sparsity (float): desired sparsity of each layer",
"name": "__init__",
"signature": "def __init__(self, model, t_sparsity)"
},
{
"docstring": "This function runs the complete training process. Args: dataset:... | 5 | null | Implement the Python class `Trainer` described below.
Class description:
Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer... | Implement the Python class `Trainer` described below.
Class description:
Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer... | e28f008477fe75c24b43cc853b2dc6d923f01813 | <|skeleton|>
class Trainer:
"""Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer for training (defaults to SGD). loss: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trainer:
"""Helper class for training operations. Attributes: mask ([numpy.ndarray]): A list of numpy arrays. Each entry correspondes to the mask of a layer. t_sparsity (float): Target sparsity for each layer. optimizer (keras.optimizer.Optimizer): Optimizer for training (defaults to SGD). loss: Loss function... | the_stack_v2_python_sparse | condense/keras/lottery_ticket.py | SirBubbls/condense | train | 0 |
c993791030631c467bd3cd763652363c5e98a661 | [
"if root is None:\n return '*'\nelse:\n serial_root = ''\n queue = [root]\n while len(queue) != 0:\n head = queue[0]\n del queue[0]\n if head:\n serial_root += '{},'.format(head.val)\n queue.append(head.left)\n queue.append(head.right)\n else:... | <|body_start_0|>
if root is None:
return '*'
else:
serial_root = ''
queue = [root]
while len(queue) != 0:
head = queue[0]
del queue[0]
if head:
serial_root += '{},'.format(head.val)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_070957 | 1,969 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_014464 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9c9ff536a23f76ae76ae69ce840fa69ebe1ab313 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return '*'
else:
serial_root = ''
queue = [root]
while len(queue) != 0:
head = queue[0]
... | the_stack_v2_python_sparse | serialize_and_deserialize_binary_tree.py | Qinode/leet_q_python | train | 0 | |
6b843c7bc8491589952c6e8f60d55f55f1da313c | [
"session = tf.Session()\nk.set_session(session)\n(x_train, y_train), (x_test, y_test), _, _ = load_dataset('mnist')\nx_train, y_train, x_test, y_test = (x_train[:NB_TRAIN], y_train[:NB_TRAIN], x_test[:NB_TEST], y_test[:NB_TEST])\nim_shape = x_train[0].shape\ncomp_params = {'loss': 'categorical_crossentropy', 'optim... | <|body_start_0|>
session = tf.Session()
k.set_session(session)
(x_train, y_train), (x_test, y_test), _, _ = load_dataset('mnist')
x_train, y_train, x_test, y_test = (x_train[:NB_TRAIN], y_train[:NB_TRAIN], x_test[:NB_TEST], y_test[:NB_TEST])
im_shape = x_train[0].shape
co... | Test cases for the AdversarialTrainer class. | TestAdversarialTrainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdversarialTrainer:
"""Test cases for the AdversarialTrainer class."""
def test_one_attack_mnist(self):
"""Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNIST trained for 5 epochs. The test cast check if accuracy ... | stack_v2_sparse_classes_75kplus_train_070958 | 6,936 | permissive | [
{
"docstring": "Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNIST trained for 5 epochs. The test cast check if accuracy on adversarial samples increases after adversarially training the model. :return: None",
"name": "test_one_attack_mnist... | 3 | stack_v2_sparse_classes_30k_train_037957 | Implement the Python class `TestAdversarialTrainer` described below.
Class description:
Test cases for the AdversarialTrainer class.
Method signatures and docstrings:
- def test_one_attack_mnist(self): Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNI... | Implement the Python class `TestAdversarialTrainer` described below.
Class description:
Test cases for the AdversarialTrainer class.
Method signatures and docstrings:
- def test_one_attack_mnist(self): Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNI... | 40b1592dfd268b3a6d1aad1f8a4c847c9e01a270 | <|skeleton|>
class TestAdversarialTrainer:
"""Test cases for the AdversarialTrainer class."""
def test_one_attack_mnist(self):
"""Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNIST trained for 5 epochs. The test cast check if accuracy ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAdversarialTrainer:
"""Test cases for the AdversarialTrainer class."""
def test_one_attack_mnist(self):
"""Test the adversarial trainer using one FGSM attacker. The source and target models of the attack are two CNNs on MNIST trained for 5 epochs. The test cast check if accuracy on adversaria... | the_stack_v2_python_sparse | src/defences/adversarial_trainer_unittest.py | montyly/adversarial-robustness-toolbox | train | 0 |
dbfe82fa28ce2a9e38bab882de22687fb3800cb2 | [
"self.state = np.array([[detection[0]], [detection[1]], [detection[2]], [detection[3]], [1], [1]])\nself.p_matrix = np.eye(6, dtype=int)\nself.h_matrix = np.array([[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0]])\nself.r_matrix = np.eye(4)\nself.predicted_state = type(None)\nself.pre... | <|body_start_0|>
self.state = np.array([[detection[0]], [detection[1]], [detection[2]], [detection[3]], [1], [1]])
self.p_matrix = np.eye(6, dtype=int)
self.h_matrix = np.array([[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
self.r_matrix = np.eye(4)
... | Class KalmanFilter | KalmanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
"""Class KalmanFilter"""
def __init__(self, detection):
"""This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector."""
<|body_0|>
def predict(self):
"""Function ... | stack_v2_sparse_classes_75kplus_train_070959 | 3,453 | no_license | [
{
"docstring": "This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector.",
"name": "__init__",
"signature": "def __init__(self, detection)"
},
{
"docstring": "Function for prediction. This function predicts t... | 3 | stack_v2_sparse_classes_30k_train_017907 | Implement the Python class `KalmanFilter` described below.
Class description:
Class KalmanFilter
Method signatures and docstrings:
- def __init__(self, detection): This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector.
- def pre... | Implement the Python class `KalmanFilter` described below.
Class description:
Class KalmanFilter
Method signatures and docstrings:
- def __init__(self, detection): This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector.
- def pre... | 7e2095142e604c157bc19fdca9cbe8c294376710 | <|skeleton|>
class KalmanFilter:
"""Class KalmanFilter"""
def __init__(self, detection):
"""This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector."""
<|body_0|>
def predict(self):
"""Function ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KalmanFilter:
"""Class KalmanFilter"""
def __init__(self, detection):
"""This function initializes KalmanFilter object. Args: detection(list: 1x4): Detection of an object, which is used to initialize the state vector."""
self.state = np.array([[detection[0]], [detection[1]], [detection[2]... | the_stack_v2_python_sparse | src/stabilisierung/kalman.py | Heatdh/advanced_machine_detection_gui | train | 0 |
e29900b7a73545c7d5963500808284ae36feeef4 | [
"super().__init__()\nself.multioutputWrapper = True\nimport sklearn\nimport sklearn.ensemble\nself.model = sklearn.ensemble.AdaBoostRegressor",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{AdaBoostRegressor} is a meta-estimator that begins by fitting a regressor on\\n ... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = True
import sklearn
import sklearn.ensemble
self.model = sklearn.ensemble.AdaBoostRegressor
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{Ad... | An AdaBoost regressors | AdaBoostRegressor | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaBoostRegressor:
"""An AdaBoost regressors"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that sp... | stack_v2_sparse_classes_75kplus_train_070960 | 6,375 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 4 | stack_v2_sparse_classes_30k_train_023908 | Implement the Python class `AdaBoostRegressor` described below.
Class description:
An AdaBoost regressors
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a referen... | Implement the Python class `AdaBoostRegressor` described below.
Class description:
An AdaBoost regressors
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a referen... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class AdaBoostRegressor:
"""An AdaBoost regressors"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that sp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdaBoostRegressor:
"""An AdaBoost regressors"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
self.multioutputWrapper = True
import sklearn
import sklearn.ensemble
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/Ensemble/AdaBoostRegressor.py | idaholab/raven | train | 201 |
dc60cee322703e5b35e0f79b25a03572ec843277 | [
"if len(s) == 1:\n return 1\nelif len(s) == 0:\n return 0\nmax_count = 1\nres = []\nfor left in range(len(s)):\n for right in range(left, len(s)):\n if s[right] not in res:\n res.append(s[right])\n else:\n if len(res) > max_count:\n max_count = len(res)\n ... | <|body_start_0|>
if len(s) == 1:
return 1
elif len(s) == 0:
return 0
max_count = 1
res = []
for left in range(len(s)):
for right in range(left, len(s)):
if s[right] not in res:
res.append(s[right])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""常规做法,时间复杂度为O(n^2),空间复杂度为O(n)"""
<|body_0|>
def lengthOfLongestSubstring_2(self, s: str) -> int:
"""优化上诉代码,使用滑动窗口,时间复杂度为O(n)"""
<|body_1|>
def lengthOfLongestSubstring_3(self, s: str) -> int:... | stack_v2_sparse_classes_75kplus_train_070961 | 2,931 | no_license | [
{
"docstring": "常规做法,时间复杂度为O(n^2),空间复杂度为O(n)",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s: str) -> int"
},
{
"docstring": "优化上诉代码,使用滑动窗口,时间复杂度为O(n)",
"name": "lengthOfLongestSubstring_2",
"signature": "def lengthOfLongestSubstring_2(self, s: st... | 3 | stack_v2_sparse_classes_30k_train_008973 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 常规做法,时间复杂度为O(n^2),空间复杂度为O(n)
- def lengthOfLongestSubstring_2(self, s: str) -> int: 优化上诉代码,使用滑动窗口,时间复杂度为O(n)
- def lengthOfLong... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 常规做法,时间复杂度为O(n^2),空间复杂度为O(n)
- def lengthOfLongestSubstring_2(self, s: str) -> int: 优化上诉代码,使用滑动窗口,时间复杂度为O(n)
- def lengthOfLong... | 13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""常规做法,时间复杂度为O(n^2),空间复杂度为O(n)"""
<|body_0|>
def lengthOfLongestSubstring_2(self, s: str) -> int:
"""优化上诉代码,使用滑动窗口,时间复杂度为O(n)"""
<|body_1|>
def lengthOfLongestSubstring_3(self, s: str) -> int:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""常规做法,时间复杂度为O(n^2),空间复杂度为O(n)"""
if len(s) == 1:
return 1
elif len(s) == 0:
return 0
max_count = 1
res = []
for left in range(len(s)):
for right in range(left, len... | the_stack_v2_python_sparse | Algorithms/3_Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.py | lirui-ML/my_leetcode | train | 1 | |
5da0dd8aae32f282d4a2182b7aa81dc4343397b1 | [
"try:\n server = smtplib.SMTP(host, port)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login(username, password)\n return server\nexcept smtplib.SMTPException as e:\n logger.error('Could not establish SMTP connection: {}'.format(e))\n raise e",
"bcc = to\nmessage = MIMEMult... | <|body_start_0|>
try:
server = smtplib.SMTP(host, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
return server
except smtplib.SMTPException as e:
logger.error('Could not establish SM... | Creates connection and mail message body. | Emailer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Emailer:
"""Creates connection and mail message body."""
def run_server(self, host, port, username, password):
"""This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the ho... | stack_v2_sparse_classes_75kplus_train_070962 | 1,797 | no_license | [
{
"docstring": "This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the host server",
"name": "run_server",
"signature": "def run_server(self, host, port, username, password)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_024641 | Implement the Python class `Emailer` described below.
Class description:
Creates connection and mail message body.
Method signatures and docstrings:
- def run_server(self, host, port, username, password): This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: u... | Implement the Python class `Emailer` described below.
Class description:
Creates connection and mail message body.
Method signatures and docstrings:
- def run_server(self, host, port, username, password): This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: u... | e4bf166f3ffe226668396c8beba3d369b3b4428f | <|skeleton|>
class Emailer:
"""Creates connection and mail message body."""
def run_server(self, host, port, username, password):
"""This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the ho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Emailer:
"""Creates connection and mail message body."""
def run_server(self, host, port, username, password):
"""This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the host server"""
... | the_stack_v2_python_sparse | notification_service/notification/handlers/emailer.py | timegenconsulting/tp-django-site | train | 0 |
524d10d2d0262e049389a44a63ead03c686bcbc9 | [
"self.pave = pave\nself.cotes = list()\nfor i in range(0, 3):\n self.cotes.append(canevas.create_line(pave.sommets[i].x, pave.sommets[i].y, pave.sommets[i + 1].x, pave.sommets[i + 1].y))\nself.cotes.append(canevas.create_line(pave.sommets[3].x, pave.sommets[3].y, pave.sommets[0].x, pave.sommets[0].y))",
"if se... | <|body_start_0|>
self.pave = pave
self.cotes = list()
for i in range(0, 3):
self.cotes.append(canevas.create_line(pave.sommets[i].x, pave.sommets[i].y, pave.sommets[i + 1].x, pave.sommets[i + 1].y))
self.cotes.append(canevas.create_line(pave.sommets[3].x, pave.sommets[3].y, p... | Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas | Vue2DPave | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vue2DPave:
"""Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas"""
def __init__(self, pave, canevas):
"""il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les 4 premiers sont les plus hauts"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070963 | 1,160 | no_license | [
{
"docstring": "il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les 4 premiers sont les plus hauts",
"name": "__init__",
"signature": "def __init__(self, pave, canevas)"
},
{
"docstring": "met a jour les coordonnee des points",
"name": "afficher",
... | 2 | stack_v2_sparse_classes_30k_train_054120 | Implement the Python class `Vue2DPave` described below.
Class description:
Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas
Method signatures and docstrings:
- def __init__(self, pave, canevas): il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les ... | Implement the Python class `Vue2DPave` described below.
Class description:
Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas
Method signatures and docstrings:
- def __init__(self, pave, canevas): il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les ... | 003a9ec9bb2433c4d8690bd498a9eb27f412f04c | <|skeleton|>
class Vue2DPave:
"""Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas"""
def __init__(self, pave, canevas):
"""il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les 4 premiers sont les plus hauts"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vue2DPave:
"""Constructeur de la vue pave: Pave canevas: Canevas Cree le pave dans canevas"""
def __init__(self, pave, canevas):
"""il est suppose que les sommets du pave sont ranges dans le bon ordre (anti-horaire) et que les 4 premiers sont les plus hauts"""
self.pave = pave
sel... | the_stack_v2_python_sparse | gl_lib/sim/affichage/d2/vue/Vue2DPave.py | bezalielmarvel/GurrenLagann | train | 1 |
763f9490730109c2da7828925eac3779114b652c | [
"tags = frozenset(tags)\nfor key in self.keys():\n if key.issuperset(tags) and len(key.difference(tags)) == 1:\n yield key",
"tags = frozenset(tags)\nfor key in list(self.keys()):\n if key.issuperset(tags):\n yield key"
] | <|body_start_0|>
tags = frozenset(tags)
for key in self.keys():
if key.issuperset(tags) and len(key.difference(tags)) == 1:
yield key
<|end_body_0|>
<|body_start_1|>
tags = frozenset(tags)
for key in list(self.keys()):
if key.issuperset(tags):
... | The grand unified cache backend which contains all cache items. | _CacheRegistry | [
"LicenseRef-scancode-unknown-license-reference",
"mpich2",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that hav... | stack_v2_sparse_classes_75kplus_train_070964 | 6,128 | permissive | [
{
"docstring": "Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that have been instantiated via :func:`Bcfg2.Server.Cache.Cache`.",
"name": "iterate",
"signature": "def iterate(self, *tags)"
... | 2 | stack_v2_sparse_classes_30k_train_035235 | Implement the Python class `_CacheRegistry` described below.
Class description:
The grand unified cache backend which contains all cache items.
Method signatures and docstrings:
- def iterate(self, *tags): Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get item... | Implement the Python class `_CacheRegistry` described below.
Class description:
The grand unified cache backend which contains all cache items.
Method signatures and docstrings:
- def iterate(self, *tags): Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get item... | 8605cd3d0cb4d549cb8b43de945d447f6d82892a | <|skeleton|>
class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that hav... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that have been instan... | the_stack_v2_python_sparse | src/lib/Bcfg2/Server/Cache.py | Bcfg2/bcfg2 | train | 56 |
966bb138b7f9ba5ceb60cab5b7c522186e3e53be | [
"self.students = []\nself.grades = {}\nself.isSorted = True",
"if student in self.students:\n raise ValueError('Duplicates Students')\nself.students.append(student)\nself.grades[student.getIdNum()] = []\nself.isSorted = False",
"try:\n self.grades[student.getIdNum()].append(grade)\nexcept KeyError:\n r... | <|body_start_0|>
self.students = []
self.grades = {}
self.isSorted = True
<|end_body_0|>
<|body_start_1|>
if student in self.students:
raise ValueError('Duplicates Students')
self.students.append(student)
self.grades[student.getIdNum()] = []
self.isSo... | mapping from students to list of grades | Grades | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grades:
"""mapping from students to list of grades"""
def __init__(self):
"""Create empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assusme: Student is of type Student Add studend to Grade Book"""
<|body_1|>
def addGrades(self, stude... | stack_v2_sparse_classes_75kplus_train_070965 | 3,719 | no_license | [
{
"docstring": "Create empty grade book",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Assusme: Student is of type Student Add studend to Grade Book",
"name": "addStudent",
"signature": "def addStudent(self, student)"
},
{
"docstring": "Assume: greade ... | 6 | null | Implement the Python class `Grades` described below.
Class description:
mapping from students to list of grades
Method signatures and docstrings:
- def __init__(self): Create empty grade book
- def addStudent(self, student): Assusme: Student is of type Student Add studend to Grade Book
- def addGrades(self, student, ... | Implement the Python class `Grades` described below.
Class description:
mapping from students to list of grades
Method signatures and docstrings:
- def __init__(self): Create empty grade book
- def addStudent(self, student): Assusme: Student is of type Student Add studend to Grade Book
- def addGrades(self, student, ... | 3c3cdcd9b3318ef11d30b9b070d61a54b8e78c67 | <|skeleton|>
class Grades:
"""mapping from students to list of grades"""
def __init__(self):
"""Create empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assusme: Student is of type Student Add studend to Grade Book"""
<|body_1|>
def addGrades(self, stude... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grades:
"""mapping from students to list of grades"""
def __init__(self):
"""Create empty grade book"""
self.students = []
self.grades = {}
self.isSorted = True
def addStudent(self, student):
"""Assusme: Student is of type Student Add studend to Grade Book"""
... | the_stack_v2_python_sparse | OOP/MitPerson.py | dawidbo/algorithms | train | 0 |
62c3a26b7c35d636f8d2270ee3b902ad5e086f3b | [
"parser.parse_args()\ncurrent_user = User.query.get(get_jwt_identity())\npage = request.args.get('page', 1, type=int)\nper_page = request.args.get('per_page', current_app.config['USERS_PER_PAGE'], type=int)\nif per_page > current_app.config['USERS_PER_PAGE']:\n per_page = current_app.config['USERS_PER_PAGE']\nwh... | <|body_start_0|>
parser.parse_args()
current_user = User.query.get(get_jwt_identity())
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', current_app.config['USERS_PER_PAGE'], type=int)
if per_page > current_app.config['USERS_PER_PAGE']:
... | UsersAllApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersAllApi:
def get(self):
"""Read information of all users. Note : Cannot read information of users with higher role"""
<|body_0|>
def delete(self):
"""Delete all users. Cannot remove user with higher roles"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070966 | 8,850 | no_license | [
{
"docstring": "Read information of all users. Note : Cannot read information of users with higher role",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Delete all users. Cannot remove user with higher roles",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037313 | Implement the Python class `UsersAllApi` described below.
Class description:
Implement the UsersAllApi class.
Method signatures and docstrings:
- def get(self): Read information of all users. Note : Cannot read information of users with higher role
- def delete(self): Delete all users. Cannot remove user with higher ... | Implement the Python class `UsersAllApi` described below.
Class description:
Implement the UsersAllApi class.
Method signatures and docstrings:
- def get(self): Read information of all users. Note : Cannot read information of users with higher role
- def delete(self): Delete all users. Cannot remove user with higher ... | b1346990dcfd5bc03a8785747d9b9a31e1e86c7b | <|skeleton|>
class UsersAllApi:
def get(self):
"""Read information of all users. Note : Cannot read information of users with higher role"""
<|body_0|>
def delete(self):
"""Delete all users. Cannot remove user with higher roles"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsersAllApi:
def get(self):
"""Read information of all users. Note : Cannot read information of users with higher role"""
parser.parse_args()
current_user = User.query.get(get_jwt_identity())
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_... | the_stack_v2_python_sparse | app/api/account.py | kriti16/Jogger | train | 0 | |
1fe9edaa3431996ba1ef82fa3d46520818bce48c | [
"self.rov = rov\nself.i2c = busio.I2C(board.SCL, board.SDA)\nself.ads13 = ADS.ADS1115(self.i2c)\nself.adc46 = ADS.ADS1115(self.i2c, address=73)\na1 = AnalogIn(self.ads13, ADS.P0)\na2 = AnalogIn(self.ads13, ADS.P1)\na3 = AnalogIn(self.ads13, ADS.P2)\na4 = AnalogIn(self.adc46, ADS.P0)\na5 = AnalogIn(self.adc46, ADS.P... | <|body_start_0|>
self.rov = rov
self.i2c = busio.I2C(board.SCL, board.SDA)
self.ads13 = ADS.ADS1115(self.i2c)
self.adc46 = ADS.ADS1115(self.i2c, address=73)
a1 = AnalogIn(self.ads13, ADS.P0)
a2 = AnalogIn(self.ads13, ADS.P1)
a3 = AnalogIn(self.ads13, ADS.P2)
... | Acp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
<|body_0|>
def mainAmperemeter(self):
"""Функция опроса датчиков тока"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rov = rov
self.i2c... | stack_v2_sparse_classes_75kplus_train_070967 | 23,756 | no_license | [
{
"docstring": "Класс описывающий взаимодействие и опрос датчиков тока",
"name": "__init__",
"signature": "def __init__(self, rov: MainRov)"
},
{
"docstring": "Функция опроса датчиков тока",
"name": "mainAmperemeter",
"signature": "def mainAmperemeter(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035633 | Implement the Python class `Acp` described below.
Class description:
Implement the Acp class.
Method signatures and docstrings:
- def __init__(self, rov: MainRov): Класс описывающий взаимодействие и опрос датчиков тока
- def mainAmperemeter(self): Функция опроса датчиков тока | Implement the Python class `Acp` described below.
Class description:
Implement the Acp class.
Method signatures and docstrings:
- def __init__(self, rov: MainRov): Класс описывающий взаимодействие и опрос датчиков тока
- def mainAmperemeter(self): Функция опроса датчиков тока
<|skeleton|>
class Acp:
def __init_... | 00ebd2dba3781da5d9e426a61136652708a74987 | <|skeleton|>
class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
<|body_0|>
def mainAmperemeter(self):
"""Функция опроса датчиков тока"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Acp:
def __init__(self, rov: MainRov):
"""Класс описывающий взаимодействие и опрос датчиков тока"""
self.rov = rov
self.i2c = busio.I2C(board.SCL, board.SDA)
self.ads13 = ADS.ADS1115(self.i2c)
self.adc46 = ADS.ADS1115(self.i2c, address=73)
a1 = AnalogIn(self.ads... | the_stack_v2_python_sparse | Soft/Apparatus/client.py | Yarik9001/SoftProteus | train | 2 | |
dfda0895377ddb3175c4be9641eccc42b3eaef66 | [
"if ':' in symbol_path:\n module_name, symbol_name = symbol_path.split(':')\n module = self._import_module(module_name)\n symbol = eval(symbol_name, module.__dict__)\nelse:\n components = symbol_path.split('.')\n module_name = '.'.join(components[:-1])\n symbol_name = components[-1]\n module = ... | <|body_start_0|>
if ':' in symbol_path:
module_name, symbol_name = symbol_path.split(':')
module = self._import_module(module_name)
symbol = eval(symbol_name, module.__dict__)
else:
components = symbol_path.split('.')
module_name = '.'.join(com... | The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place). | ImportManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportManager:
"""The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place)."""
def import_symbol(self, symbol_path):
"""Import the ... | stack_v2_sparse_classes_75kplus_train_070968 | 2,192 | no_license | [
{
"docstring": "Import the symbol defined by the specified symbol path.",
"name": "import_symbol",
"signature": "def import_symbol(self, symbol_path)"
},
{
"docstring": "Import the module with the specified (and possibly dotted) name. Returns the imported module. This method is copied from the d... | 2 | null | Implement the Python class `ImportManager` described below.
Class description:
The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place).
Method signatures and docstr... | Implement the Python class `ImportManager` described below.
Class description:
The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place).
Method signatures and docstr... | 164e82df0655337ac4966273d9cc489d002d8987 | <|skeleton|>
class ImportManager:
"""The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place)."""
def import_symbol(self, symbol_path):
"""Import the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportManager:
"""The default import manager implementation. Its just a guess, but I think using an import manager to do all imports will make debugging easier (as opposed to just letting imports happen from all over the place)."""
def import_symbol(self, symbol_path):
"""Import the symbol define... | the_stack_v2_python_sparse | lib/python2.7/site-packages/envisage/import_manager.py | stephenosullivan/science | train | 0 |
be56379db7c2b6cd3f43763ecd014f3aac1c99b8 | [
"first = head\nsecond = first\nwhile n:\n n -= 1\n first = first.next\nif not first:\n return head.next\nwhile first.next:\n first = first.next\n second = second.next\nsecond.next = second.next.next\nreturn head",
"length = 0\ndummy = ListNode(0)\ndummy.next = head\nfirst = head\nwhile first:\n ... | <|body_start_0|>
first = head
second = first
while n:
n -= 1
first = first.next
if not first:
return head.next
while first.next:
first = first.next
second = second.next
second.next = second.next.next
retu... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:"""
<|body_0|>
def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_75kplus_train_070969 | 1,277 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:",
"name": "remove_nth_node",
"signature": "def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode'"
},
{
"docstring": "Approach: Two Pass Time Complexity: O(L) Space Complexi... | 2 | stack_v2_sparse_classes_30k_train_031399 | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode': Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:
- def remov... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode': Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:
- def remov... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:"""
<|body_0|>
def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkedList:
def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode':
"""Approach: One Pass Time Complexity: O(L) Space Complexity: O(1) :param head: :param n: :return:"""
first = head
second = first
while n:
n -= 1
first = first.next
if... | the_stack_v2_python_sparse | revisited_2021/linked_list/remove_nth_node.py | Shiv2157k/leet_code | train | 1 | |
d79ca91f1822fe786e28ed2993b56d4fb5268ddf | [
"dic = {}\nfor i in range(len(nums)):\n cur = nums[i]\n if cur in dic:\n dic[cur] += [i]\n else:\n dic[cur] = [i]\nfor k in dic:\n v = dic[k]\n v.sort()\n for i in range(len(v) - 1):\n if v[i] - v[i + 1] <= -k:\n return True\nreturn False",
"dic = {}\nfor i in ran... | <|body_start_0|>
dic = {}
for i in range(len(nums)):
cur = nums[i]
if cur in dic:
dic[cur] += [i]
else:
dic[cur] = [i]
for k in dic:
v = dic[k]
v.sort()
for i in range(len(v) - 1):
... | Ex219 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ex219:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_070970 | 1,328 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate0",
"signature": "def contai... | 2 | stack_v2_sparse_classes_30k_val_000579 | Implement the Python class `Ex219` described below.
Class description:
Implement the Ex219 class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate0(self, nums, k): :type nums: List[int] :type k: int :rtype: bo... | Implement the Python class `Ex219` described below.
Class description:
Implement the Ex219 class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate0(self, nums, k): :type nums: List[int] :type k: int :rtype: bo... | 8f9327a1879949f61b462cc6c82e00e7c27b8b07 | <|skeleton|>
class Ex219:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ex219:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
dic = {}
for i in range(len(nums)):
cur = nums[i]
if cur in dic:
dic[cur] += [i]
else:
dic[cur] = [i]
for... | the_stack_v2_python_sparse | LeetCode/Ex200/Ex219.py | JasonVann/CrackingCodingInterview | train | 0 | |
c62b07768b7cf7888f287c1c06011ae0b518a988 | [
"print(input_str, point_int)\ntry:\n if 180 >= int(input_str) >= 18:\n return (QValidator.Acceptable, input_str, point_int)\n elif 17 >= int(input_str) >= 1:\n return (QValidator.Intermediate, input_str, point_int)\n else:\n return (QValidator.Invalid, input_str, point_int)\nexcept:\n ... | <|body_start_0|>
print(input_str, point_int)
try:
if 180 >= int(input_str) >= 18:
return (QValidator.Acceptable, input_str, point_int)
elif 17 >= int(input_str) >= 1:
return (QValidator.Intermediate, input_str, point_int)
else:
... | 子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活 | AgeValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgeValidator:
"""子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活"""
def validate(self, input_str, point_int):
""":param input_str: 输入的文本 :param point_int: 光标位置 :return:"""
<|body_0|>
def fixup(self, p_str):
"""如果输入无效,且离开输入框,就会进入fixup方法 :param p_str: :re... | stack_v2_sparse_classes_75kplus_train_070971 | 1,913 | no_license | [
{
"docstring": ":param input_str: 输入的文本 :param point_int: 光标位置 :return:",
"name": "validate",
"signature": "def validate(self, input_str, point_int)"
},
{
"docstring": "如果输入无效,且离开输入框,就会进入fixup方法 :param p_str: :return:",
"name": "fixup",
"signature": "def fixup(self, p_str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010382 | Implement the Python class `AgeValidator` described below.
Class description:
子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活
Method signatures and docstrings:
- def validate(self, input_str, point_int): :param input_str: 输入的文本 :param point_int: 光标位置 :return:
- def fixup(self, p_str): 如果输入无效,且离开输入框,就会进入fixu... | Implement the Python class `AgeValidator` described below.
Class description:
子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活
Method signatures and docstrings:
- def validate(self, input_str, point_int): :param input_str: 输入的文本 :param point_int: 光标位置 :return:
- def fixup(self, p_str): 如果输入无效,且离开输入框,就会进入fixu... | 8287964874fd9cafe5024118a2611af226e936d3 | <|skeleton|>
class AgeValidator:
"""子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活"""
def validate(self, input_str, point_int):
""":param input_str: 输入的文本 :param point_int: 光标位置 :return:"""
<|body_0|>
def fixup(self, p_str):
"""如果输入无效,且离开输入框,就会进入fixup方法 :param p_str: :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AgeValidator:
"""子类化,然后实现两个方法,同样适用于浮点类型,还可以封装上下限参数,更加灵活 TODO: 封装上下限参数,更加灵活"""
def validate(self, input_str, point_int):
""":param input_str: 输入的文本 :param point_int: 光标位置 :return:"""
print(input_str, point_int)
try:
if 180 >= int(input_str) >= 18:
return... | the_stack_v2_python_sparse | my_notes/23.QLineEdit 输入验证器.py | madmadcat/QtCookBook_Demo | train | 0 |
b84140fc5837f7eec53c4595a2a00344c4917ea3 | [
"self.alpha = alpha\nself.beta = beta\nself.delta = delta\nself.candidates = candidates",
"best_candidate = self.candidates[0]\nfor i in range(1, len(self.candidates)):\n best_candidate = self.compare_candidates(best_candidate, self.candidates[i])\nreturn best_candidate[0]",
"p = (a_prob + b_prob) / 2\nsigma... | <|body_start_0|>
self.alpha = alpha
self.beta = beta
self.delta = delta
self.candidates = candidates
<|end_body_0|>
<|body_start_1|>
best_candidate = self.candidates[0]
for i in range(1, len(self.candidates)):
best_candidate = self.compare_candidates(best_can... | KTesting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KTesting:
def __init__(self, alpha, beta, delta, candidates):
"""Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis when it is true typically 0.05 :param beta: power level, probability of rejecting the null hypoth... | stack_v2_sparse_classes_75kplus_train_070972 | 3,853 | no_license | [
{
"docstring": "Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis when it is true typically 0.05 :param beta: power level, probability of rejecting the null hypothesis when the null hypothesis is false, typically 0.8 :param delta: alter... | 4 | stack_v2_sparse_classes_30k_train_034469 | Implement the Python class `KTesting` described below.
Class description:
Implement the KTesting class.
Method signatures and docstrings:
- def __init__(self, alpha, beta, delta, candidates): Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis ... | Implement the Python class `KTesting` described below.
Class description:
Implement the KTesting class.
Method signatures and docstrings:
- def __init__(self, alpha, beta, delta, candidates): Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis ... | dc2c3f569e99a14120ee7bd905358037a3c398cc | <|skeleton|>
class KTesting:
def __init__(self, alpha, beta, delta, candidates):
"""Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis when it is true typically 0.05 :param beta: power level, probability of rejecting the null hypoth... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KTesting:
def __init__(self, alpha, beta, delta, candidates):
"""Initialization of the tester for K-testing :param alpha: significance level, the probability of rejecting the null hypothesis when it is true typically 0.05 :param beta: power level, probability of rejecting the null hypothesis when the ... | the_stack_v2_python_sparse | KTesting.py | lucabonali/PricingDia | train | 0 | |
fbf6a1d1a7ceb90d6d05c76ced3fdb6f7de345e1 | [
"if self._debug:\n self._DebugPrintText(f'\\nReading threat tracking data at offset: {file_offset:d} (0x{file_offset:08x})\\n')\ndata_type_map = self._GetDataTypeMap('uint32le')\nvalues_data_size = self._ReadStructureFromByteStream(threat_tracking_data, 0, data_type_map, 'values data size')\nif values_data_size ... | <|body_start_0|>
if self._debug:
self._DebugPrintText(f'\nReading threat tracking data at offset: {file_offset:d} (0x{file_offset:08x})\n')
data_type_map = self._GetDataTypeMap('uint32le')
values_data_size = self._ReadStructureFromByteStream(threat_tracking_data, 0, data_type_map, 'v... | Windows Defender scan DetectionHistory file. | WindowsDefenderScanDetectionHistoryFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsDefenderScanDetectionHistoryFile:
"""Windows Defender scan DetectionHistory file."""
def _ReadThreatTrackingData(self, threat_tracking_data, file_offset):
"""Reads the threat tracking data. Args: threat_tracking_data (bytes): threat tracking data. file_offset (int): offset of ... | stack_v2_sparse_classes_75kplus_train_070973 | 8,091 | permissive | [
{
"docstring": "Reads the threat tracking data. Args: threat_tracking_data (bytes): threat tracking data. file_offset (int): offset of the threat tracking data relative to the start of the file. Raises: IOError: if the threat tracking data cannot be read.",
"name": "_ReadThreatTrackingData",
"signature"... | 5 | stack_v2_sparse_classes_30k_train_028913 | Implement the Python class `WindowsDefenderScanDetectionHistoryFile` described below.
Class description:
Windows Defender scan DetectionHistory file.
Method signatures and docstrings:
- def _ReadThreatTrackingData(self, threat_tracking_data, file_offset): Reads the threat tracking data. Args: threat_tracking_data (by... | Implement the Python class `WindowsDefenderScanDetectionHistoryFile` described below.
Class description:
Windows Defender scan DetectionHistory file.
Method signatures and docstrings:
- def _ReadThreatTrackingData(self, threat_tracking_data, file_offset): Reads the threat tracking data. Args: threat_tracking_data (by... | 55007dcac48efff42c497e739208ebfb88e4048d | <|skeleton|>
class WindowsDefenderScanDetectionHistoryFile:
"""Windows Defender scan DetectionHistory file."""
def _ReadThreatTrackingData(self, threat_tracking_data, file_offset):
"""Reads the threat tracking data. Args: threat_tracking_data (bytes): threat tracking data. file_offset (int): offset of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WindowsDefenderScanDetectionHistoryFile:
"""Windows Defender scan DetectionHistory file."""
def _ReadThreatTrackingData(self, threat_tracking_data, file_offset):
"""Reads the threat tracking data. Args: threat_tracking_data (bytes): threat tracking data. file_offset (int): offset of the threat tr... | the_stack_v2_python_sparse | dtformats/detection_history.py | libyal/dtformats | train | 109 |
dc51a51fdb8487c872371d1707baa72d27f6027e | [
"tag = get_object_or_404(Tag, pk=pk)\nself.check_object_permissions(request, tag)\nserializer = TagRetrieveUpdateDestroySerializer(tag, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"tag = get_object_or_404(Tag, pk=pk)\nself.check_object_permissions(request, tag)\nserializer = Ta... | <|body_start_0|>
tag = get_object_or_404(Tag, pk=pk)
self.check_object_permissions(request, tag)
serializer = TagRetrieveUpdateDestroySerializer(tag, many=False)
return Response(data=serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
tag = get_object_or_... | TagRetrieveUpdateDestroyAPIView | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_070974 | 2,948 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, pk=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
},
{
"docstring": "Delete",
"name": "delete",
"signature": "def delete(self, request, pk=None... | 3 | stack_v2_sparse_classes_30k_train_049592 | Implement the Python class `TagRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the TagRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(self, request, pk=None): Delete | Implement the Python class `TagRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the TagRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, pk=None): Retrieve
- def put(self, request, pk=None): Update
- def delete(self, request, pk=None): Delete
<|... | 289318b0333d830c089f4492716c38d409c365ed | <|skeleton|>
class TagRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
def delete(self, request, pk=None):
"""Delete"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagRetrieveUpdateDestroyAPIView:
def get(self, request, pk=None):
"""Retrieve"""
tag = get_object_or_404(Tag, pk=pk)
self.check_object_permissions(request, tag)
serializer = TagRetrieveUpdateDestroySerializer(tag, many=False)
return Response(data=serializer.data, status... | the_stack_v2_python_sparse | workery/tenant_api/views/tag.py | wahello/workery-django | train | 0 | |
ec55e7e8567fa0615f54ad5159259e02c2c55149 | [
"print('Querying database')\nif sort not in ['created_at', 'cook_time', 'num_of_servings']:\n sort = 'created_at'\nif order not in ['asc', 'desc']:\n order = 'desc'\npaginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order)\nreturn (recipe_pagination_schema.dump(paginated_recipes).data, HTT... | <|body_start_0|>
print('Querying database')
if sort not in ['created_at', 'cook_time', 'num_of_servings']:
sort = 'created_at'
if order not in ['asc', 'desc']:
order = 'desc'
paginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order)
retu... | RecipeListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeListResource:
def get(self, q, page, per_page, sort, order):
"""Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginated recipes as serialized and back to front end client. The q parameter passed the search string into the AP... | stack_v2_sparse_classes_75kplus_train_070975 | 8,070 | no_license | [
{
"docstring": "Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginated recipes as serialized and back to front end client. The q parameter passed the search string into the API",
"name": "get",
"signature": "def get(self, q, page, per_page, sort... | 2 | stack_v2_sparse_classes_30k_train_051081 | Implement the Python class `RecipeListResource` described below.
Class description:
Implement the RecipeListResource class.
Method signatures and docstrings:
- def get(self, q, page, per_page, sort, order): Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginat... | Implement the Python class `RecipeListResource` described below.
Class description:
Implement the RecipeListResource class.
Method signatures and docstrings:
- def get(self, q, page, per_page, sort, order): Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginat... | 875b8bc3cc5315efe8ccee8ce9b312056802c49d | <|skeleton|>
class RecipeListResource:
def get(self, q, page, per_page, sort, order):
"""Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginated recipes as serialized and back to front end client. The q parameter passed the search string into the AP... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecipeListResource:
def get(self, q, page, per_page, sort, order):
"""Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginated recipes as serialized and back to front end client. The q parameter passed the search string into the API"""
p... | the_stack_v2_python_sparse | resources/recipe.py | ShayanRiyaz/TheDailyCook | train | 1 | |
78477b9ee4ef6e06c74879c01d180ad2e6f44656 | [
"self._config = config\nformatter = logging.Formatter('%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d %(message)s')\nhandlers = []\nstream_handler = logging.StreamHandler()\nstream_handler.setFormatter(formatter)\nhandlers.append(stream_handler)\nif log_file is not None:\n if platform.system() == 'Windows':... | <|body_start_0|>
self._config = config
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d %(message)s')
handlers = []
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
handlers.append(stream_handler)
if... | Class for initializing and shutting down a pyobs process. | Application | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Class for initializing and shutting down a pyobs process."""
def __init__(self, config: str, log_file: Optional[str]=None, log_level: str='info', **kwargs: Any):
"""Initializes a pyobs application. Args: config: Name of config file. log_file: Name of log file, if any.... | stack_v2_sparse_classes_75kplus_train_070976 | 6,651 | permissive | [
{
"docstring": "Initializes a pyobs application. Args: config: Name of config file. log_file: Name of log file, if any. log_level: Logging level. log_rotate: Whether to rotate the log files.",
"name": "__init__",
"signature": "def __init__(self, config: str, log_file: Optional[str]=None, log_level: str=... | 5 | stack_v2_sparse_classes_30k_train_021400 | Implement the Python class `Application` described below.
Class description:
Class for initializing and shutting down a pyobs process.
Method signatures and docstrings:
- def __init__(self, config: str, log_file: Optional[str]=None, log_level: str='info', **kwargs: Any): Initializes a pyobs application. Args: config:... | Implement the Python class `Application` described below.
Class description:
Class for initializing and shutting down a pyobs process.
Method signatures and docstrings:
- def __init__(self, config: str, log_file: Optional[str]=None, log_level: str='info', **kwargs: Any): Initializes a pyobs application. Args: config:... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class Application:
"""Class for initializing and shutting down a pyobs process."""
def __init__(self, config: str, log_file: Optional[str]=None, log_level: str='info', **kwargs: Any):
"""Initializes a pyobs application. Args: config: Name of config file. log_file: Name of log file, if any.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Class for initializing and shutting down a pyobs process."""
def __init__(self, config: str, log_file: Optional[str]=None, log_level: str='info', **kwargs: Any):
"""Initializes a pyobs application. Args: config: Name of config file. log_file: Name of log file, if any. log_level: L... | the_stack_v2_python_sparse | pyobs/application.py | pyobs/pyobs-core | train | 9 |
c7746f5fdc97129331ce8be711368b5a9bff62c1 | [
"self.net = net\nself.state = None\nself.device = device",
"with torch.no_grad():\n\n def _to_torch(o):\n return torch.from_numpy(o).to(self.device)\n ob = nest.map_structure(_to_torch, ob)\n if self.state is None:\n out = self.net(ob)\n else:\n out = self.net(ob, self.state)\n ... | <|body_start_0|>
self.net = net
self.state = None
self.device = device
<|end_body_0|>
<|body_start_1|>
with torch.no_grad():
def _to_torch(o):
return torch.from_numpy(o).to(self.device)
ob = nest.map_structure(_to_torch, ob)
if self.s... | Wrap actor to convert actions to numpy. | Actor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
"""Wrap actor to convert actions to numpy."""
def __init__(self, net, device):
"""Init."""
<|body_0|>
def __call__(self, ob):
"""__call__."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.net = net
self.state = None
se... | stack_v2_sparse_classes_75kplus_train_070977 | 7,046 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, net, device)"
},
{
"docstring": "__call__.",
"name": "__call__",
"signature": "def __call__(self, ob)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032754 | Implement the Python class `Actor` described below.
Class description:
Wrap actor to convert actions to numpy.
Method signatures and docstrings:
- def __init__(self, net, device): Init.
- def __call__(self, ob): __call__. | Implement the Python class `Actor` described below.
Class description:
Wrap actor to convert actions to numpy.
Method signatures and docstrings:
- def __init__(self, net, device): Init.
- def __call__(self, ob): __call__.
<|skeleton|>
class Actor:
"""Wrap actor to convert actions to numpy."""
def __init__(s... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class Actor:
"""Wrap actor to convert actions to numpy."""
def __init__(self, net, device):
"""Init."""
<|body_0|>
def __call__(self, ob):
"""__call__."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Actor:
"""Wrap actor to convert actions to numpy."""
def __init__(self, net, device):
"""Init."""
self.net = net
self.state = None
self.device = device
def __call__(self, ob):
"""__call__."""
with torch.no_grad():
def _to_torch(o):
... | the_stack_v2_python_sparse | dl/rl/util/eval.py | cbschaff/dl | train | 1 |
3ac86ba72b75a93663d3dd805ac6814b720c6952 | [
"self.Type, self.Length, self.Flags, self.Reserved, self.SegmentNumber = struct.unpack_from(DMARTable.ATSRStruct.STRUCT_FORMAT, header_byte_array)\nself.DeviceScope = list()\nheader_byte_array = header_byte_array[DMARTable.ASTRHeaderLength:]\nbytes_left = self.Length - DMARTable.ASTRHeaderLength\nwhile bytes_left >... | <|body_start_0|>
self.Type, self.Length, self.Flags, self.Reserved, self.SegmentNumber = struct.unpack_from(DMARTable.ATSRStruct.STRUCT_FORMAT, header_byte_array)
self.DeviceScope = list()
header_byte_array = header_byte_array[DMARTable.ASTRHeaderLength:]
bytes_left = self.Length - DMART... | Object representing the ANDD struct. | ATSRStruct | [
"BSD-2-Clause-Patent"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATSRStruct:
"""Object representing the ANDD struct."""
def __init__(self, header_byte_array, length):
"""Inits the object."""
<|body_0|>
def toXml(self):
"""Converts the object to an xml representation."""
<|body_1|>
def __str__(self):
"""Str... | stack_v2_sparse_classes_75kplus_train_070978 | 21,782 | permissive | [
{
"docstring": "Inits the object.",
"name": "__init__",
"signature": "def __init__(self, header_byte_array, length)"
},
{
"docstring": "Converts the object to an xml representation.",
"name": "toXml",
"signature": "def toXml(self)"
},
{
"docstring": "String representation of the ... | 3 | stack_v2_sparse_classes_30k_train_051740 | Implement the Python class `ATSRStruct` described below.
Class description:
Object representing the ANDD struct.
Method signatures and docstrings:
- def __init__(self, header_byte_array, length): Inits the object.
- def toXml(self): Converts the object to an xml representation.
- def __str__(self): String representat... | Implement the Python class `ATSRStruct` described below.
Class description:
Object representing the ANDD struct.
Method signatures and docstrings:
- def __init__(self, header_byte_array, length): Inits the object.
- def toXml(self): Converts the object to an xml representation.
- def __str__(self): String representat... | 78295929b37af62a8cfc4c28eab72ed0c468f350 | <|skeleton|>
class ATSRStruct:
"""Object representing the ANDD struct."""
def __init__(self, header_byte_array, length):
"""Inits the object."""
<|body_0|>
def toXml(self):
"""Converts the object to an xml representation."""
<|body_1|>
def __str__(self):
"""Str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ATSRStruct:
"""Object representing the ANDD struct."""
def __init__(self, header_byte_array, length):
"""Inits the object."""
self.Type, self.Length, self.Flags, self.Reserved, self.SegmentNumber = struct.unpack_from(DMARTable.ATSRStruct.STRUCT_FORMAT, header_byte_array)
self.Devi... | the_stack_v2_python_sparse | edk2toollib/acpi/dmar_parser.py | tianocore/edk2-pytool-library | train | 47 |
6991f56dd3447ec6a6d384647d3d7b1c7592fa03 | [
"if target == 0 and path not in result:\n result.append(path)\n return\nif target < 0 or index >= len(candidates):\n return\nfor idx in range(index, len(candidates)):\n if idx > index + 1 and candidates[idx] == candidates[idx - 1]:\n continue\n self.back_track(candidates, idx + 1, target - can... | <|body_start_0|>
if target == 0 and path not in result:
result.append(path)
return
if target < 0 or index >= len(candidates):
return
for idx in range(index, len(candidates)):
if idx > index + 1 and candidates[idx] == candidates[idx - 1]:
... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]]):
"""Back tracking function :param candidates: :param index: :param target: :param path: :param result: :return:"""
<|body_0|>
def combination_sum(self, candi... | stack_v2_sparse_classes_75kplus_train_070979 | 1,394 | no_license | [
{
"docstring": "Back tracking function :param candidates: :param index: :param target: :param path: :param result: :return:",
"name": "back_track",
"signature": "def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]])"
},
{
"docstring": "App... | 2 | stack_v2_sparse_classes_30k_val_002528 | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]]): Back tracking function :param candidates: :param index: :param target: :... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]]): Back tracking function :param candidates: :param index: :param target: :... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]]):
"""Back tracking function :param candidates: :param index: :param target: :param path: :param result: :return:"""
<|body_0|>
def combination_sum(self, candi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Array:
def back_track(self, candidates: List[int], index: int, target: int, path: List[int], result: List[List[int]]):
"""Back tracking function :param candidates: :param index: :param target: :param path: :param result: :return:"""
if target == 0 and path not in result:
result.app... | the_stack_v2_python_sparse | revisited_2021/math_and_string/back_tracking/combination_sum_ii.py | Shiv2157k/leet_code | train | 1 | |
fe661f2f2d448500173afc330a038523a5d45ae8 | [
"if self.request.user.is_authenticated:\n if self.request.user.is_superuser:\n self.data_layer = 'admin_layer'\n else:\n self.data_layer = expressive_layer_name(self.request.user)",
"self.__set_layer_name()\ntry:\n unblocked_ids = self.request.session['datasets']\nexcept KeyError:\n unbl... | <|body_start_0|>
if self.request.user.is_authenticated:
if self.request.user.is_superuser:
self.data_layer = 'admin_layer'
else:
self.data_layer = expressive_layer_name(self.request.user)
<|end_body_0|>
<|body_start_1|>
self.__set_layer_name()
... | Template View to bring the necessary variables for the startup to the template | HomeView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
<|body_0|>
def get_context_data(self, **kwargs: object):
"""C... | stack_v2_sparse_classes_75kplus_train_070980 | 27,241 | permissive | [
{
"docstring": "Set name for layer in geoserver according to username or as admin_layer.",
"name": "__set_layer_name",
"signature": "def __set_layer_name(self)"
},
{
"docstring": "Collect data needed for startup of V-FOR-WaTer Portal home. :param kwargs: :return:",
"name": "get_context_data"... | 2 | stack_v2_sparse_classes_30k_train_053967 | Implement the Python class `HomeView` described below.
Class description:
Template View to bring the necessary variables for the startup to the template
Method signatures and docstrings:
- def __set_layer_name(self): Set name for layer in geoserver according to username or as admin_layer.
- def get_context_data(self,... | Implement the Python class `HomeView` described below.
Class description:
Template View to bring the necessary variables for the startup to the template
Method signatures and docstrings:
- def __set_layer_name(self): Set name for layer in geoserver according to username or as admin_layer.
- def get_context_data(self,... | e245101b5278ee1ee8c55f7dbde2445363c9aa26 | <|skeleton|>
class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
<|body_0|>
def get_context_data(self, **kwargs: object):
"""C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
if self.request.user.is_authenticated:
if self.request.user.is_superuser:
... | the_stack_v2_python_sparse | vfwheron/views.py | standardgalactic/vforwater-portal | train | 0 |
7a2042358fd7b844712b8bb31be745048b31da62 | [
"denoms = data.groupby(Config.DATE_COL).sum()['Denominator']\nnums = data.groupby(Config.DATE_COL).sum()[Config.CLI_COLS + Config.FLU1_COL]\nX = np.zeros((nums.shape[0], 6 + nums.shape[0]))\nnot_sunday = np.where(nums.index.dayofweek != 6)[0]\nX[not_sunday, np.array(nums.index.dayofweek)[not_sunday]] = 1\nX[np.wher... | <|body_start_0|>
denoms = data.groupby(Config.DATE_COL).sum()['Denominator']
nums = data.groupby(Config.DATE_COL).sum()[Config.CLI_COLS + Config.FLU1_COL]
X = np.zeros((nums.shape[0], 6 + nums.shape[0]))
not_sunday = np.where(nums.index.dayofweek != 6)[0]
X[not_sunday, np.array(n... | Class to handle weekday effects. | Weekday | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Weekday:
"""Class to handle weekday effects."""
def get_params(data):
"""Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. Instead, model log(numerator_t/denominator_t) = alpha_{wd(... | stack_v2_sparse_classes_75kplus_train_070981 | 5,067 | permissive | [
{
"docstring": "Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. Instead, model log(numerator_t/denominator_t) = alpha_{wd(t)} + phi_t where alpha is a vector of fixed effects for each weekday. For identifiab... | 2 | stack_v2_sparse_classes_30k_train_024716 | Implement the Python class `Weekday` described below.
Class description:
Class to handle weekday effects.
Method signatures and docstrings:
- def get_params(data): Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. I... | Implement the Python class `Weekday` described below.
Class description:
Class to handle weekday effects.
Method signatures and docstrings:
- def get_params(data): Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. I... | 0c0ca18f38892c850565edf8bed9d2acaf234354 | <|skeleton|>
class Weekday:
"""Class to handle weekday effects."""
def get_params(data):
"""Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. Instead, model log(numerator_t/denominator_t) = alpha_{wd(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Weekday:
"""Class to handle weekday effects."""
def get_params(data):
"""Correct a signal estimated as numerator/denominator for weekday effects. The ordinary estimate would be numerator_t/denominator_t for each time point t. Instead, model log(numerator_t/denominator_t) = alpha_{wd(t)} + phi_t w... | the_stack_v2_python_sparse | doctor_visits/delphi_doctor_visits/weekday.py | alexcoda/covidcast-indicators | train | 0 |
15b77d6a492c118e7039f94217ecc414cb1e4ff9 | [
"token = get_authorization_header(request).split()[1]\npayload = jwt.decode(token, SECRET_KEY)\nuser_id = payload['user_id']\nlist_of_ids = request.data.get('notification_ids')\ntry:\n self.queryset.filter(id__in=list_of_ids).update(has_read=True)\nexcept Exception as err:\n logger.log_error(str(err))\n re... | <|body_start_0|>
token = get_authorization_header(request).split()[1]
payload = jwt.decode(token, SECRET_KEY)
user_id = payload['user_id']
list_of_ids = request.data.get('notification_ids')
try:
self.queryset.filter(id__in=list_of_ids).update(has_read=True)
ex... | API for Notification | NotificationView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationView:
"""API for Notification"""
def patch(self, request):
"""Patch api method of notification"""
<|body_0|>
def get(self, request):
"""Get api method for Notification"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
token = get_autho... | stack_v2_sparse_classes_75kplus_train_070982 | 2,170 | no_license | [
{
"docstring": "Patch api method of notification",
"name": "patch",
"signature": "def patch(self, request)"
},
{
"docstring": "Get api method for Notification",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048974 | Implement the Python class `NotificationView` described below.
Class description:
API for Notification
Method signatures and docstrings:
- def patch(self, request): Patch api method of notification
- def get(self, request): Get api method for Notification | Implement the Python class `NotificationView` described below.
Class description:
API for Notification
Method signatures and docstrings:
- def patch(self, request): Patch api method of notification
- def get(self, request): Get api method for Notification
<|skeleton|>
class NotificationView:
"""API for Notificat... | b76de21b3318ab24e1add18a9aa4f437ed02e10e | <|skeleton|>
class NotificationView:
"""API for Notification"""
def patch(self, request):
"""Patch api method of notification"""
<|body_0|>
def get(self, request):
"""Get api method for Notification"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotificationView:
"""API for Notification"""
def patch(self, request):
"""Patch api method of notification"""
token = get_authorization_header(request).split()[1]
payload = jwt.decode(token, SECRET_KEY)
user_id = payload['user_id']
list_of_ids = request.data.get('n... | the_stack_v2_python_sparse | core/views_layer/notification.py | ameyk20/eon-backend | train | 0 |
975822c5523443a878f1754f38499bed17f1b114 | [
"self.client.login(username='oauth_test_user', password='123456')\nself.oauth2_settings.PKCE_REQUIRED = False\nauthorization_code = self.get_auth()\ntoken_request_data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': 'http://example.org'}\nauth_headers = self.get_basic_auth_header(... | <|body_start_0|>
self.client.login(username='oauth_test_user', password='123456')
self.oauth2_settings.PKCE_REQUIRED = False
authorization_code = self.get_auth()
token_request_data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': 'http://example.org'}
... | TestAuthorizationCodeTokenView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAuthorizationCodeTokenView:
def test_basic_auth(self):
"""Request an access token using basic authentication for client authentication"""
<|body_0|>
def test_secure_auth_pkce(self):
"""Request an access token using client_type: public and PKCE enabled with the S2... | stack_v2_sparse_classes_75kplus_train_070983 | 7,709 | permissive | [
{
"docstring": "Request an access token using basic authentication for client authentication",
"name": "test_basic_auth",
"signature": "def test_basic_auth(self)"
},
{
"docstring": "Request an access token using client_type: public and PKCE enabled with the S256 algorithm",
"name": "test_sec... | 2 | stack_v2_sparse_classes_30k_train_000946 | Implement the Python class `TestAuthorizationCodeTokenView` described below.
Class description:
Implement the TestAuthorizationCodeTokenView class.
Method signatures and docstrings:
- def test_basic_auth(self): Request an access token using basic authentication for client authentication
- def test_secure_auth_pkce(se... | Implement the Python class `TestAuthorizationCodeTokenView` described below.
Class description:
Implement the TestAuthorizationCodeTokenView class.
Method signatures and docstrings:
- def test_basic_auth(self): Request an access token using basic authentication for client authentication
- def test_secure_auth_pkce(se... | 304e093dc550da8636552dc601d6545c07ffc771 | <|skeleton|>
class TestAuthorizationCodeTokenView:
def test_basic_auth(self):
"""Request an access token using basic authentication for client authentication"""
<|body_0|>
def test_secure_auth_pkce(self):
"""Request an access token using client_type: public and PKCE enabled with the S2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAuthorizationCodeTokenView:
def test_basic_auth(self):
"""Request an access token using basic authentication for client authentication"""
self.client.login(username='oauth_test_user', password='123456')
self.oauth2_settings.PKCE_REQUIRED = False
authorization_code = self.ge... | the_stack_v2_python_sparse | physionet-django/oauth/tests.py | MIT-LCP/physionet-build | train | 50 | |
9c4ba942af0309d25def5bbec57b13a6bc4ad1ab | [
"SBIglobals.alert('verbose', self, 'Writting object to file {0}'.format(object_file))\ndumpFile = File(file_name=object_file, action='wb', overwrite=overwrite)\npickle.dump(self, dumpFile.descriptor)\ndumpFile.close()",
"SBIglobals.alert('verbose', StorableObject, 'Preparing to load object from file {0}'.format(o... | <|body_start_0|>
SBIglobals.alert('verbose', self, 'Writting object to file {0}'.format(object_file))
dumpFile = File(file_name=object_file, action='wb', overwrite=overwrite)
pickle.dump(self, dumpFile.descriptor)
dumpFile.close()
<|end_body_0|>
<|body_start_1|>
SBIglobals.alert... | StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ABSTRACT OBJECT, IT DOES NOT HAVE A CONSTRUCTOR] Methods: - dump(): Stores the ob... | StorableObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorableObject:
"""StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ABSTRACT OBJECT, IT DOES NOT HAVE A CON... | stack_v2_sparse_classes_75kplus_train_070984 | 2,933 | no_license | [
{
"docstring": "- dump(): Stores the object into a file - object_file (string): Name for the output file @Mandatory - overwrite (bool): Overwrite previous file of the same name @Raises FileError",
"name": "dump",
"signature": "def dump(self, object_file, overwrite=None)"
},
{
"docstring": "> loa... | 2 | stack_v2_sparse_classes_30k_train_030305 | Implement the Python class `StorableObject` described below.
Class description:
StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ... | Implement the Python class `StorableObject` described below.
Class description:
StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ... | e06e0ac107de3a025d9d4961518393109dfd55db | <|skeleton|>
class StorableObject:
"""StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ABSTRACT OBJECT, IT DOES NOT HAVE A CON... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StorableObject:
"""StorableObject is an abstract "dumping" class. This means that it is basically usefull for those who would like to extend this library. Basically, it gives the object the hability to be "dumped" on disk and be recovered afterwards. [AS AN ABSTRACT OBJECT, IT DOES NOT HAVE A CONSTRUCTOR] Met... | the_stack_v2_python_sparse | modpin/src/SBI/beans/StorableObject.py | structuralbioinformatics/MODPIN | train | 2 |
dac48cb07221cd71d02e6381d08eea2b33a0ed82 | [
"self.use_wget = use_wget\nself.quic_binary_dir = quic_binary_dir\nself.quic_server_address = quic_server_address\nself.quic_server_port = quic_server_port\nif not use_wget and (not os.path.isfile(quic_binary_dir + '/quic_client')):\n raise IOError('There is no quic_client in the given dir: %s.' % quic_binary_di... | <|body_start_0|>
self.use_wget = use_wget
self.quic_binary_dir = quic_binary_dir
self.quic_server_address = quic_server_address
self.quic_server_port = quic_server_port
if not use_wget and (not os.path.isfile(quic_binary_dir + '/quic_client')):
raise IOError('There is... | PageloadExperiment | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageloadExperiment:
def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port):
"""Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: P... | stack_v2_sparse_classes_75kplus_train_070985 | 6,722 | permissive | [
{
"docstring": "Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the quic server.",
"name": "__init__",
"signature": "def __init__(self, use_wget, quic_binary_dir, qui... | 4 | stack_v2_sparse_classes_30k_train_038393 | Implement the Python class `PageloadExperiment` described below.
Class description:
Implement the PageloadExperiment class.
Method signatures and docstrings:
- def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic... | Implement the Python class `PageloadExperiment` described below.
Class description:
Implement the PageloadExperiment class.
Method signatures and docstrings:
- def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class PageloadExperiment:
def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port):
"""Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PageloadExperiment:
def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port):
"""Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the qui... | the_stack_v2_python_sparse | net/tools/quic/benchmark/run_client.py | chromium/chromium | train | 17,408 | |
fb63b9593d4999ef940727f9f35396ebe7209495 | [
"result = []\nmax_val = len(S)\nindex = len(S) - 1\nmin_val = 0\nwhile index >= 0:\n if S[index] == 'I':\n result.insert(0, max_val)\n max_val -= 1\n else:\n result.insert(0, min_val)\n min_val += 1\n index -= 1\nresult.insert(0, (max_val + min_val) / 2)\nreturn result",
"resu... | <|body_start_0|>
result = []
max_val = len(S)
index = len(S) - 1
min_val = 0
while index >= 0:
if S[index] == 'I':
result.insert(0, max_val)
max_val -= 1
else:
result.insert(0, min_val)
min_va... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
max_val = len(S)
index =... | stack_v2_sparse_classes_75kplus_train_070986 | 2,287 | permissive | [
{
"docstring": ":type S: str :rtype: List[int]",
"name": "_diStringMatch",
"signature": "def _diStringMatch(self, S)"
},
{
"docstring": ":type S: str :rtype: List[int]",
"name": "diStringMatch",
"signature": "def diStringMatch(self, S)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001654 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _diStringMatch(self, S): :type S: str :rtype: List[int]
- def diStringMatch(self, S): :type S: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _diStringMatch(self, S): :type S: str :rtype: List[int]
- def diStringMatch(self, S): :type S: str :rtype: List[int]
<|skeleton|>
class Solution:
def _diStringMatch(sel... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _diStringMatch(self, S):
""":type S: str :rtype: List[int]"""
result = []
max_val = len(S)
index = len(S) - 1
min_val = 0
while index >= 0:
if S[index] == 'I':
result.insert(0, max_val)
max_val -= 1
... | the_stack_v2_python_sparse | 942.di-string-match.py | windard/leeeeee | train | 0 | |
d3b28c2f1d30d22d4fc175e5682cb8ac42306d3b | [
"if local_loc_dir is None:\n local_loc_dir = os.path.join(os.getcwd(), CaperBase.DEFAULT_LOC_DIR_NAME)\nif not AbsPath(local_loc_dir).is_valid:\n raise ValueError('local_loc_dir should be a valid local abspath. {f}'.format(f=local_loc_dir))\nif gcp_loc_dir and (not GCSURI(gcp_loc_dir).is_valid):\n raise Va... | <|body_start_0|>
if local_loc_dir is None:
local_loc_dir = os.path.join(os.getcwd(), CaperBase.DEFAULT_LOC_DIR_NAME)
if not AbsPath(local_loc_dir).is_valid:
raise ValueError('local_loc_dir should be a valid local abspath. {f}'.format(f=local_loc_dir))
if gcp_loc_dir and (... | CaperBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaperBase:
def __init__(self, local_loc_dir=None, gcp_loc_dir=None, aws_loc_dir=None, gcp_service_account_key_json=None):
"""Manages work/cache/temp directories for localization on the following storages: - Local*: Local path -> local_loc_dir** - gcp: GCS bucket path -> gcp_loc_dir - aws... | stack_v2_sparse_classes_75kplus_train_070987 | 7,780 | permissive | [
{
"docstring": "Manages work/cache/temp directories for localization on the following storages: - Local*: Local path -> local_loc_dir** - gcp: GCS bucket path -> gcp_loc_dir - aws: S3 bucket path -> aws_loc_dir * Note that it starts with capital L, which is a default backend of Cromwell's default configuration ... | 6 | stack_v2_sparse_classes_30k_train_001197 | Implement the Python class `CaperBase` described below.
Class description:
Implement the CaperBase class.
Method signatures and docstrings:
- def __init__(self, local_loc_dir=None, gcp_loc_dir=None, aws_loc_dir=None, gcp_service_account_key_json=None): Manages work/cache/temp directories for localization on the follo... | Implement the Python class `CaperBase` described below.
Class description:
Implement the CaperBase class.
Method signatures and docstrings:
- def __init__(self, local_loc_dir=None, gcp_loc_dir=None, aws_loc_dir=None, gcp_service_account_key_json=None): Manages work/cache/temp directories for localization on the follo... | 6759671f9f18dc1220fb4b9c26f99c0216e4e368 | <|skeleton|>
class CaperBase:
def __init__(self, local_loc_dir=None, gcp_loc_dir=None, aws_loc_dir=None, gcp_service_account_key_json=None):
"""Manages work/cache/temp directories for localization on the following storages: - Local*: Local path -> local_loc_dir** - gcp: GCS bucket path -> gcp_loc_dir - aws... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaperBase:
def __init__(self, local_loc_dir=None, gcp_loc_dir=None, aws_loc_dir=None, gcp_service_account_key_json=None):
"""Manages work/cache/temp directories for localization on the following storages: - Local*: Local path -> local_loc_dir** - gcp: GCS bucket path -> gcp_loc_dir - aws: S3 bucket pa... | the_stack_v2_python_sparse | caper/caper_base.py | ENCODE-DCC/caper | train | 44 | |
1afa227e05651e0d3dcc5cb1be9521895a2ed293 | [
"srcs = var_to_list(srcs)\ndeps = var_to_list(deps)\nextra_cppflags = var_to_list(extra_cppflags)\nextra_linkflags = var_to_list(extra_linkflags)\nCcTarget.__init__(self, name, target_type, srcs, deps, None, warning, defs, incs, [], [], extra_cppflags, extra_linkflags, blade, kwargs)",
"nvcc_flags = []\nif self.d... | <|body_start_0|>
srcs = var_to_list(srcs)
deps = var_to_list(deps)
extra_cppflags = var_to_list(extra_cppflags)
extra_linkflags = var_to_list(extra_linkflags)
CcTarget.__init__(self, name, target_type, srcs, deps, None, warning, defs, incs, [], [], extra_cppflags, extra_linkflags... | A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc. | CuTarget | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CuTarget:
"""A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc."""
def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs):
"""Init method. Init the... | stack_v2_sparse_classes_75kplus_train_070988 | 10,571 | permissive | [
{
"docstring": "Init method. Init the cu target.",
"name": "__init__",
"signature": "def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs)"
},
{
"docstring": "_get_cu_flags. Return the nvcc flags according to the BUILD file and oth... | 3 | stack_v2_sparse_classes_30k_train_039270 | Implement the Python class `CuTarget` described below.
Class description:
A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.
Method signatures and docstrings:
- def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflag... | Implement the Python class `CuTarget` described below.
Class description:
A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc.
Method signatures and docstrings:
- def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflag... | a7da427617885546c5b5e07aa7740b3dee690337 | <|skeleton|>
class CuTarget:
"""A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc."""
def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs):
"""Init method. Init the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CuTarget:
"""A scons cu target subclass. This class is derived from SconsCcTarget and it is the base class of cu_library, cu_binary etc."""
def __init__(self, name, target_type, srcs, deps, warning, defs, incs, extra_cppflags, extra_linkflags, blade, kwargs):
"""Init method. Init the cu target.""... | the_stack_v2_python_sparse | build_tools/typhoon-blade/src/blade/cu_targets.py | algo-data-platform/PredictorService | train | 3 |
66e263b8e5bfb56eb345baca954128e109d55ca1 | [
"import plone.app.dexterity\nself.loadZCML(package=plone.schemaeditor.tests, name='robot_testing.zcml')\nself.loadZCML(package=plone.app.dexterity, name='configure.zcml')\nself.loadZCML(package=plone.app.dexterity, name='overrides.zcml')",
"applyProfile(portal, 'plone.schemaeditor.tests:testing')\nsetRoles(portal... | <|body_start_0|>
import plone.app.dexterity
self.loadZCML(package=plone.schemaeditor.tests, name='robot_testing.zcml')
self.loadZCML(package=plone.app.dexterity, name='configure.zcml')
self.loadZCML(package=plone.app.dexterity, name='overrides.zcml')
<|end_body_0|>
<|body_start_1|>
... | PloneSchemaeditorRobotLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PloneSchemaeditorRobotLayer:
def setUpZope(self, app, configurationContext):
"""Set up Zope."""
<|body_0|>
def setUpPloneSite(self, portal):
"""Set up Plone."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import plone.app.dexterity
self.loa... | stack_v2_sparse_classes_75kplus_train_070989 | 1,894 | no_license | [
{
"docstring": "Set up Zope.",
"name": "setUpZope",
"signature": "def setUpZope(self, app, configurationContext)"
},
{
"docstring": "Set up Plone.",
"name": "setUpPloneSite",
"signature": "def setUpPloneSite(self, portal)"
}
] | 2 | null | Implement the Python class `PloneSchemaeditorRobotLayer` described below.
Class description:
Implement the PloneSchemaeditorRobotLayer class.
Method signatures and docstrings:
- def setUpZope(self, app, configurationContext): Set up Zope.
- def setUpPloneSite(self, portal): Set up Plone. | Implement the Python class `PloneSchemaeditorRobotLayer` described below.
Class description:
Implement the PloneSchemaeditorRobotLayer class.
Method signatures and docstrings:
- def setUpZope(self, app, configurationContext): Set up Zope.
- def setUpPloneSite(self, portal): Set up Plone.
<|skeleton|>
class PloneSche... | 8a7bdbdb98c3f9fc1073c6061cd2d3a0ec80caf5 | <|skeleton|>
class PloneSchemaeditorRobotLayer:
def setUpZope(self, app, configurationContext):
"""Set up Zope."""
<|body_0|>
def setUpPloneSite(self, portal):
"""Set up Plone."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PloneSchemaeditorRobotLayer:
def setUpZope(self, app, configurationContext):
"""Set up Zope."""
import plone.app.dexterity
self.loadZCML(package=plone.schemaeditor.tests, name='robot_testing.zcml')
self.loadZCML(package=plone.app.dexterity, name='configure.zcml')
self.l... | the_stack_v2_python_sparse | buildout-cache/eggs/plone.schemaeditor-1.3.11-py2.7.egg/plone/schemaeditor/testing.py | renansfs/Plone_SP | train | 0 | |
0243e3e47c3d0b8bd353a80df39fca7cb1d035e8 | [
"def dfs(res, k):\n if k <= n:\n res.append(k)\n t = 10 * k\n if t <= n:\n for i in range(10):\n dfs(res, t + i)\nres = []\nfor i in range(1, 10):\n dfs(res, i)\nreturn res",
"res = [i for i in range(1, n + 1)]\nres.sort(key=str)\nreturn res"
] | <|body_start_0|>
def dfs(res, k):
if k <= n:
res.append(k)
t = 10 * k
if t <= n:
for i in range(10):
dfs(res, t + i)
res = []
for i in range(1, 10):
dfs(res, i)
return res
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
"""https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way"""
<|body_0|>
def lexicalOrder(self, n):
"""Cheating using str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070990 | 654 | no_license | [
{
"docstring": "https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way",
"name": "lexicalOrder",
"signature": "def lexicalOrder(self, n)"
},
{
"docstring": "Cheating using str",
"name": "lexicalOrder",
"signature": "def lexicalOrder(self, n)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way
- def lexicalOrder(self, n): Cheating using str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way
- def lexicalOrder(self, n): Cheating using str
<|s... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
"""https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way"""
<|body_0|>
def lexicalOrder(self, n):
"""Cheating using str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lexicalOrder(self, n):
"""https://leetcode.com/problems/lexicographical-numbers/discuss/86240/How-to-think-it-in-the-DFS-way"""
def dfs(res, k):
if k <= n:
res.append(k)
t = 10 * k
if t <= n:
for i in... | the_stack_v2_python_sparse | Leetcode/386. Lexicographical Numbers.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
b4b801eb1a39b29b547817ca1179ca5e43eff53c | [
"count = db.import_data('D:\\\\UW\\\\PY220\\\\Examples and Assignments\\\\lesson05\\\\csv_files\\\\', 'products.csv', 'customers.csv', 'rentals.csv')\nexpected_count = ((4, 3, 4), (0, 0, 0))\nself.assertEqual(count, expected_count)",
"data = db\ndata.import_data('D:\\\\UW\\\\PY220\\\\Examples and Assignments\\\\l... | <|body_start_0|>
count = db.import_data('D:\\UW\\PY220\\Examples and Assignments\\lesson05\\csv_files\\', 'products.csv', 'customers.csv', 'rentals.csv')
expected_count = ((4, 3, 4), (0, 0, 0))
self.assertEqual(count, expected_count)
<|end_body_0|>
<|body_start_1|>
data = db
dat... | Testing the Parts of Database.py | TestDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDatabase:
"""Testing the Parts of Database.py"""
def test_import_data(self):
"""Test Importing Data"""
<|body_0|>
def test_show_available_products(self):
"""Test Showing Available Products"""
<|body_1|>
def test_show_rentals(self):
"""Tes... | stack_v2_sparse_classes_75kplus_train_070991 | 2,486 | no_license | [
{
"docstring": "Test Importing Data",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Test Showing Available Products",
"name": "test_show_available_products",
"signature": "def test_show_available_products(self)"
},
{
"docstring": "Test S... | 3 | stack_v2_sparse_classes_30k_train_001090 | Implement the Python class `TestDatabase` described below.
Class description:
Testing the Parts of Database.py
Method signatures and docstrings:
- def test_import_data(self): Test Importing Data
- def test_show_available_products(self): Test Showing Available Products
- def test_show_rentals(self): Test Showing Renta... | Implement the Python class `TestDatabase` described below.
Class description:
Testing the Parts of Database.py
Method signatures and docstrings:
- def test_import_data(self): Test Importing Data
- def test_show_available_products(self): Test Showing Available Products
- def test_show_rentals(self): Test Showing Renta... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestDatabase:
"""Testing the Parts of Database.py"""
def test_import_data(self):
"""Test Importing Data"""
<|body_0|>
def test_show_available_products(self):
"""Test Showing Available Products"""
<|body_1|>
def test_show_rentals(self):
"""Tes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDatabase:
"""Testing the Parts of Database.py"""
def test_import_data(self):
"""Test Importing Data"""
count = db.import_data('D:\\UW\\PY220\\Examples and Assignments\\lesson05\\csv_files\\', 'products.csv', 'customers.csv', 'rentals.csv')
expected_count = ((4, 3, 4), (0, 0, 0... | the_stack_v2_python_sparse | students/andrew_garcia/lesson05-assignment/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
ecaed313375e947cc4c22e7539e5e66343454fcd | [
"if not root:\n return\np = root.lchild\nroot.lchild = root.rchild\nroot.rchild = root.lchild\nself.Mirror(root.lchild)\nself.Mirror(root.rchild)",
"stackNode = [root]\nwhile stackNode:\n n = len(stackNode) - 1\n tree = stackNode[n]\n stackNode.pop()\n if tree.lchild != None or tree.rchild != None:... | <|body_start_0|>
if not root:
return
p = root.lchild
root.lchild = root.rchild
root.rchild = root.lchild
self.Mirror(root.lchild)
self.Mirror(root.rchild)
<|end_body_0|>
<|body_start_1|>
stackNode = [root]
while stackNode:
n = len(... | 给一个二叉树,将其转变成镜像 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给一个二叉树,将其转变成镜像"""
def Mirror(self, root):
"""递归实现"""
<|body_0|>
def Mirror2(self, root):
"""新建一个队列来存储这个每次遍历的树,当这个树有值的时候,就取这个数的最后一个元素 开始遍历,如果树的左子树不为空或者右子树不为空,就添加到队列里面,进行左右子树的更换,直到 左右子树都为空为止"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070992 | 1,192 | no_license | [
{
"docstring": "递归实现",
"name": "Mirror",
"signature": "def Mirror(self, root)"
},
{
"docstring": "新建一个队列来存储这个每次遍历的树,当这个树有值的时候,就取这个数的最后一个元素 开始遍历,如果树的左子树不为空或者右子树不为空,就添加到队列里面,进行左右子树的更换,直到 左右子树都为空为止",
"name": "Mirror2",
"signature": "def Mirror2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
给一个二叉树,将其转变成镜像
Method signatures and docstrings:
- def Mirror(self, root): 递归实现
- def Mirror2(self, root): 新建一个队列来存储这个每次遍历的树,当这个树有值的时候,就取这个数的最后一个元素 开始遍历,如果树的左子树不为空或者右子树不为空,就添加到队列里面,进行左右子树的更换,直到 左右子树都为空为止 | Implement the Python class `Solution` described below.
Class description:
给一个二叉树,将其转变成镜像
Method signatures and docstrings:
- def Mirror(self, root): 递归实现
- def Mirror2(self, root): 新建一个队列来存储这个每次遍历的树,当这个树有值的时候,就取这个数的最后一个元素 开始遍历,如果树的左子树不为空或者右子树不为空,就添加到队列里面,进行左右子树的更换,直到 左右子树都为空为止
<|skeleton|>
class Solution:
"""给一个... | e5d7441605d33ebf0e59d8a5d1ee5d6f97c96b71 | <|skeleton|>
class Solution:
"""给一个二叉树,将其转变成镜像"""
def Mirror(self, root):
"""递归实现"""
<|body_0|>
def Mirror2(self, root):
"""新建一个队列来存储这个每次遍历的树,当这个树有值的时候,就取这个数的最后一个元素 开始遍历,如果树的左子树不为空或者右子树不为空,就添加到队列里面,进行左右子树的更换,直到 左右子树都为空为止"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""给一个二叉树,将其转变成镜像"""
def Mirror(self, root):
"""递归实现"""
if not root:
return
p = root.lchild
root.lchild = root.rchild
root.rchild = root.lchild
self.Mirror(root.lchild)
self.Mirror(root.rchild)
def Mirror2(self, root):
... | the_stack_v2_python_sparse | 二叉树的镜像.py | 1a2a222/leetcode | train | 0 |
b19d04a16672a6e82ef0ac5031a632a46feb1e78 | [
"super(ModelLSTMCell3, self).__init__()\nself.trg_embeder = Embedding(100, 32)\nself.output_layer = Linear(32, 32)\nself.decoder_cell = LSTMCell(input_size=32, hidden_size=32)\nself.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4, embedding_fn=self.trg_embeder, output_fn=self.... | <|body_start_0|>
super(ModelLSTMCell3, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = LSTMCell(input_size=32, hidden_size=32)
self.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4... | LSTMCell model2 | ModelLSTMCell3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelLSTMCell3:
"""LSTMCell model2"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ModelLSTMCell3, self).__init__()
self.trg_embeder = Embedding(100, ... | stack_v2_sparse_classes_75kplus_train_070993 | 20,209 | no_license | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self)"
}
] | 2 | null | Implement the Python class `ModelLSTMCell3` described below.
Class description:
LSTMCell model2
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward | Implement the Python class `ModelLSTMCell3` described below.
Class description:
LSTMCell model2
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward
<|skeleton|>
class ModelLSTMCell3:
"""LSTMCell model2"""
def __init__(self):
"""initialize"""
<|body... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class ModelLSTMCell3:
"""LSTMCell model2"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelLSTMCell3:
"""LSTMCell model2"""
def __init__(self):
"""initialize"""
super(ModelLSTMCell3, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = LSTMCell(input_size=32, hidden_size=32)
self.decod... | the_stack_v2_python_sparse | framework/api/nn/test_dynamicdecode.py | PaddlePaddle/PaddleTest | train | 42 |
34b298a541fd26cfecc15d23d25cc5bfd9fa9857 | [
"self.clf_name = clf_name\nif self.clf_name == 'One-Class SVM':\n self.clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1)\nelif self.clf_name == 'Robust covariance':\n self.clf = EllipticEnvelope()\nelif self.clf_name == 'Isolation Forest':\n self.clf = IsolationForest()\nelif self.clf_name == 'Local O... | <|body_start_0|>
self.clf_name = clf_name
if self.clf_name == 'One-Class SVM':
self.clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1)
elif self.clf_name == 'Robust covariance':
self.clf = EllipticEnvelope()
elif self.clf_name == 'Isolation Forest':
... | An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html | BuildSimpleOutliersDetectionMethod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
<|body_0|>
def train(self, t... | stack_v2_sparse_classes_75kplus_train_070994 | 15,799 | permissive | [
{
"docstring": "Build Traditional Outliers classifier.",
"name": "__init__",
"signature": "def __init__(self, clf_name)"
},
{
"docstring": "Fit the SVM model. :param train_data: :param save_model: :param test_saved_model: :param model_dir_path: :param iteration_number: :return:",
"name": "tr... | 2 | stack_v2_sparse_classes_30k_train_037586 | Implement the Python class `BuildSimpleOutliersDetectionMethod` described below.
Class description:
An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html
Method signatures and docstrings:
- def __init__(self, clf_name): Build Traditional Outliers... | Implement the Python class `BuildSimpleOutliersDetectionMethod` described below.
Class description:
An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html
Method signatures and docstrings:
- def __init__(self, clf_name): Build Traditional Outliers... | a6b27c6847262e9703a0f3404c85c135415c1d4c | <|skeleton|>
class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
<|body_0|>
def train(self, t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
self.clf_name = clf_name
if self.clf_n... | the_stack_v2_python_sparse | DAE_Method/ae_utilities.py | proy3/Abnormal_Trajectory_Classifier | train | 9 |
588f9dbc549cf45e8aa3ef02de3105314dbc53fa | [
"if ty == 'trades':\n reader = BinReader(filePath, '>QIIf', 100)\n self._ts = []\n self._pr = []\n while reader.hasNext():\n now = reader.next()\n self._ts.append(now[0])\n self._pr.append(now[3])\nelif ty == 'quotes':\n reader = BinReader(filePath, '>QIIfIf', 100)\n self._ts ... | <|body_start_0|>
if ty == 'trades':
reader = BinReader(filePath, '>QIIf', 100)
self._ts = []
self._pr = []
while reader.hasNext():
now = reader.next()
self._ts.append(now[0])
self._pr.append(now[3])
elif ty =... | A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade price/mid quote price for trade/quote data | Computer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Computer:
"""A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade price/mid quote price for trade/quote data... | stack_v2_sparse_classes_75kplus_train_070995 | 2,886 | no_license | [
{
"docstring": "Parameters ------ filePath : str The file path of the data ty : str type of the data, either 'trades' or 'quotes'",
"name": "__init__",
"signature": "def __init__(self, filePath, ty)"
},
{
"docstring": "Compute the X-minute return Parameters ------ x : int Minute",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_045073 | Implement the Python class `Computer` described below.
Class description:
A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade pri... | Implement the Python class `Computer` described below.
Class description:
A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade pri... | 4aabbb41b2e9ce18172e010527c59d53ffb95984 | <|skeleton|>
class Computer:
"""A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade price/mid quote price for trade/quote data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Computer:
"""A class to compute X-minute returns of trades and mid-quotes Attributes ------ _ts : list A list of time stamps from the data _pr : list A list of prices from the data Methods ------ computeReturn(x) Return the X-time lag return of the trade price/mid quote price for trade/quote data"""
def ... | the_stack_v2_python_sparse | Homework1/PartB/ReturnComputer.py | nateehuang/AlgorTradingGithub | train | 0 |
99ee40f2bb8769328c9ee7f6026f46e1d68681dd | [
"product = ProductFactory(stock_amount=10)\nself.assertEqual(product.left_in_stock, 10)\nself.assertTrue(product.is_available())",
"product = ProductFactory(stock_amount=2)\nOrderProductRelationFactory(product=product, order__open=None)\nopr = OrderProductRelationFactory(product=product, order__open=None)\nself.a... | <|body_start_0|>
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
self.assertTrue(product.is_available())
<|end_body_0|>
<|body_start_1|>
product = ProductFactory(stock_amount=2)
OrderProductRelationFactory(product=product, order__open=None)
... | Test logic about availability of products. | ProductAvailabilityTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_75kplus_train_070996 | 26,437 | permissive | [
{
"docstring": "If no orders have been made, the product is still available.",
"name": "test_product_available_by_stock",
"signature": "def test_product_available_by_stock(self)"
},
{
"docstring": "If max orders have been made, the product is NOT available.",
"name": "test_product_not_availa... | 6 | stack_v2_sparse_classes_30k_train_017865 | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | Implement the Python class `ProductAvailabilityTest` described below.
Class description:
Test logic about availability of products.
Method signatures and docstrings:
- def test_product_available_by_stock(self): If no orders have been made, the product is still available.
- def test_product_not_available_by_stock(self... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
<|body_0|>
def test_product_not_available_by_stock(self):
"""If max orders have... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductAvailabilityTest:
"""Test logic about availability of products."""
def test_product_available_by_stock(self):
"""If no orders have been made, the product is still available."""
product = ProductFactory(stock_amount=10)
self.assertEqual(product.left_in_stock, 10)
sel... | the_stack_v2_python_sparse | src/shop/tests.py | bornhack/bornhack-website | train | 9 |
a1f933d74ddadf0191d5af6f71a2983c83ae273d | [
"Frame.__init__(self, master)\nself.pack()\nself.createWidgets()",
"top_frame = Frame(self)\ntop_frame.pack(side=TOP)\nself.textA = Entry(top_frame)\nself.labelA = Label(top_frame, text='Value A')\nself.labelA.pack(side=TOP)\nself.textA.pack()\nself.textB = Entry(top_frame)\nself.labelB = Label(top_frame, text='V... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
top_frame.pack(side=TOP)
self.textA = Entry(top_frame)
self.labelA = Label(top_frame, text='Value A')
self.labelA.pack(s... | app main window class | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""app main window class"""
def __init__(self, master=None):
"""Main frame init"""
<|body_0|>
def createWidgets(self):
"""Add all widgets to the main frame"""
<|body_1|>
def handle(self):
"""Get both values and if float, add them... | stack_v2_sparse_classes_75kplus_train_070997 | 1,570 | no_license | [
{
"docstring": "Main frame init",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all widgets to the main frame",
"name": "createWidgets",
"signature": "def createWidgets(self)"
},
{
"docstring": "Get both values and if float, add them up... | 3 | null | Implement the Python class `Application` described below.
Class description:
app main window class
Method signatures and docstrings:
- def __init__(self, master=None): Main frame init
- def createWidgets(self): Add all widgets to the main frame
- def handle(self): Get both values and if float, add them up | Implement the Python class `Application` described below.
Class description:
app main window class
Method signatures and docstrings:
- def __init__(self, master=None): Main frame init
- def createWidgets(self): Add all widgets to the main frame
- def handle(self): Get both values and if float, add them up
<|skeleton... | 049c654ed626e97d7fe2f8dc61d84c60f10d7558 | <|skeleton|>
class Application:
"""app main window class"""
def __init__(self, master=None):
"""Main frame init"""
<|body_0|>
def createWidgets(self):
"""Add all widgets to the main frame"""
<|body_1|>
def handle(self):
"""Get both values and if float, add them... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""app main window class"""
def __init__(self, master=None):
"""Main frame init"""
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
"""Add all widgets to the main frame"""
top_frame = Frame(self)
... | the_stack_v2_python_sparse | python2/IntroGUI_Homework/src/GUIadder.py | paulrefalo/Python-2---4 | train | 0 |
95d4ea44038bcf891ee17dbae1108832826f57e4 | [
"super().__init__(self.SCHEMA_NAME)\nself.redfish['error'] = collections.OrderedDict()\nif code not in config.get_registry_dict()['Base']['Messages']:\n raise OneViewRedfishResourceNotFoundException('Registry {} not found.'.format(code))\nself.redfish['error']['code'] = 'Base.1.1.' + code\nself.redfish['error'][... | <|body_start_0|>
super().__init__(self.SCHEMA_NAME)
self.redfish['error'] = collections.OrderedDict()
if code not in config.get_registry_dict()['Base']['Messages']:
raise OneViewRedfishResourceNotFoundException('Registry {} not found.'.format(code))
self.redfish['error']['cod... | Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against. | RedfishError | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
<|body_0|>
def add_extended_in... | stack_v2_sparse_classes_75kplus_train_070998 | 4,248 | permissive | [
{
"docstring": "Constructor Populates self.redfish with error message.",
"name": "__init__",
"signature": "def __init__(self, code, message)"
},
{
"docstring": "Adds an item to ExtendedInfo list using values from DMTF registry Adds an item to ExtendedInfo list using the values for Message, Sever... | 2 | stack_v2_sparse_classes_30k_train_000012 | Implement the Python class `RedfishError` described below.
Class description:
Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against.
Method signatures and docstrings:
- def __init__(self, code, message): Constructor Populates self.redfish with erro... | Implement the Python class `RedfishError` described below.
Class description:
Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against.
Method signatures and docstrings:
- def __init__(self, code, message): Constructor Populates self.redfish with erro... | ffc86ea0a9e5d192ab6a2fe21c1717957b55d1da | <|skeleton|>
class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
<|body_0|>
def add_extended_in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
super().__init__(self.SCHEMA_NAME)
self.... | the_stack_v2_python_sparse | oneview_redfish_toolkit/api/redfish_error.py | shobhit-sinha/oneview-redfish-toolkit | train | 2 |
ea0bc27f7a447543bc43b4cd56671c6acb1d1c93 | [
"count = {}\nstack = []\nstack.append(root)\nwhile stack:\n cur = stack.pop()\n if cur.val not in count:\n count[cur.val] = 1\n else:\n count[cur.val] += 1\n if cur.left:\n stack.append(cur.left)\n if cur.right:\n stack.append(cur.right)\nmax_v = max(count.values())\nres =... | <|body_start_0|>
count = {}
stack = []
stack.append(root)
while stack:
cur = stack.pop()
if cur.val not in count:
count[cur.val] = 1
else:
count[cur.val] += 1
if cur.left:
stack.append(cur.lef... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMode1(self, root):
""":type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的"""
<|body_0|>
def findMode(self, root):
""":type root: TreeNode :rtype: List[int] 方法二:递归,中序遍历,使用pre指针保存上一个节点"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_070999 | 2,193 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的",
"name": "findMode1",
"signature": "def findMode1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int] 方法二:递归,中序遍历,使用pre指针保存上一个节点",
"name": "findMode",
"signature": "def f... | 2 | stack_v2_sparse_classes_30k_train_001383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMode1(self, root): :type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的
- def findMode(self, root): :type root: TreeNode :rtype: List[int] 方法... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMode1(self, root): :type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的
- def findMode(self, root): :type root: TreeNode :rtype: List[int] 方法... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def findMode1(self, root):
""":type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的"""
<|body_0|>
def findMode(self, root):
""":type root: TreeNode :rtype: List[int] 方法二:递归,中序遍历,使用pre指针保存上一个节点"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMode1(self, root):
""":type root: TreeNode :rtype: List[int] 方法一:使用map记录每一个值出现的次数,最后按照value排序返回value最大的"""
count = {}
stack = []
stack.append(root)
while stack:
cur = stack.pop()
if cur.val not in count:
count[cu... | the_stack_v2_python_sparse | out/production/leetcode/501.二叉搜索树中的众数.py | yangyuxiang1996/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.