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
7b4c84e7a777047ad31b565d2f977cff2a792be6
[ "choices = choices.split(',')\nif len(choices) <= 1:\n raise commands.UserInputError('Not enough choices! Separate choices with commas, e.g. `choose A cat, A bear, A python`')\nfor index in range(0, len(choices)):\n choices[index] = choices[index].strip()\nif len(set(choices)) == 1:\n raise commands.UserIn...
<|body_start_0|> choices = choices.split(',') if len(choices) <= 1: raise commands.UserInputError('Not enough choices! Separate choices with commas, e.g. `choose A cat, A bear, A python`') for index in range(0, len(choices)): choices[index] = choices[index].strip() ...
Commands that give the bot's opinion on something.
Opinions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Opinions: """Commands that give the bot's opinion on something.""" async def choose(self, ctx, *, choices=''): """Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z.""" <|body_0|> async def ratewaifu(self, ctx, *, user: d...
stack_v2_sparse_classes_75kplus_train_074600
2,955
permissive
[ { "docstring": "Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z.", "name": "choose", "signature": "async def choose(self, ctx, *, choices='')" }, { "docstring": "Rate a user's waifu-ness. * user - The user to be rated.", "name": "ratewaifu...
2
stack_v2_sparse_classes_30k_train_040963
Implement the Python class `Opinions` described below. Class description: Commands that give the bot's opinion on something. Method signatures and docstrings: - async def choose(self, ctx, *, choices=''): Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z. - async def...
Implement the Python class `Opinions` described below. Class description: Commands that give the bot's opinion on something. Method signatures and docstrings: - async def choose(self, ctx, *, choices=''): Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z. - async def...
3a456ad06814181d13d4aabefc151756c55444f4
<|skeleton|> class Opinions: """Commands that give the bot's opinion on something.""" async def choose(self, ctx, *, choices=''): """Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z.""" <|body_0|> async def ratewaifu(self, ctx, *, user: d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Opinions: """Commands that give the bot's opinion on something.""" async def choose(self, ctx, *, choices=''): """Choose between one of various supplied things. Syntax: * choose x, y, z - Choose between x, y, and z.""" choices = choices.split(',') if len(choices) <= 1: ...
the_stack_v2_python_sparse
cogs/opinions.py
sokcheng/Kitsuchan-NG
train
1
44a34a1cd9914d512848c2c1ed61e93fb350fc2b
[ "session = DBConnect().getSession()\ntry:\n fundList = session.query(Fund).all()\n return fundList\nexcept InvalidRequestError:\n session.rollback()\n return False\nexcept Exception as e:\n logging.error(e)\n return False\nfinally:\n print('关闭session')\n session.close()", "session = DBConn...
<|body_start_0|> session = DBConnect().getSession() try: fundList = session.query(Fund).all() return fundList except InvalidRequestError: session.rollback() return False except Exception as e: logging.error(e) return...
FundRepository
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FundRepository: def getFundList(cls): """获取fund列表""" <|body_0|> def addCross(cls, fund): """添加cross信息""" <|body_1|> def updateCross(cls, fund): """更新cross信息""" <|body_2|> def getFundById(cls, id): """获取fund信息""" <|bod...
stack_v2_sparse_classes_75kplus_train_074601
2,835
no_license
[ { "docstring": "获取fund列表", "name": "getFundList", "signature": "def getFundList(cls)" }, { "docstring": "添加cross信息", "name": "addCross", "signature": "def addCross(cls, fund)" }, { "docstring": "更新cross信息", "name": "updateCross", "signature": "def updateCross(cls, fund)" ...
5
stack_v2_sparse_classes_30k_val_001172
Implement the Python class `FundRepository` described below. Class description: Implement the FundRepository class. Method signatures and docstrings: - def getFundList(cls): 获取fund列表 - def addCross(cls, fund): 添加cross信息 - def updateCross(cls, fund): 更新cross信息 - def getFundById(cls, id): 获取fund信息 - def deleteFundById(...
Implement the Python class `FundRepository` described below. Class description: Implement the FundRepository class. Method signatures and docstrings: - def getFundList(cls): 获取fund列表 - def addCross(cls, fund): 添加cross信息 - def updateCross(cls, fund): 更新cross信息 - def getFundById(cls, id): 获取fund信息 - def deleteFundById(...
b59aa7f6e9f2be3ebf90f11cb8bdcbfb47cfbda9
<|skeleton|> class FundRepository: def getFundList(cls): """获取fund列表""" <|body_0|> def addCross(cls, fund): """添加cross信息""" <|body_1|> def updateCross(cls, fund): """更新cross信息""" <|body_2|> def getFundById(cls, id): """获取fund信息""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FundRepository: def getFundList(cls): """获取fund列表""" session = DBConnect().getSession() try: fundList = session.query(Fund).all() return fundList except InvalidRequestError: session.rollback() return False except Exception...
the_stack_v2_python_sparse
repository/FundRepository.py
Zbl1007/wechat_and_fund__for_handsome
train
4
f566e586deb45031b1ca6f316e5f706fa765db5c
[ "self = object.__new__(cls)\nself.name = value\nself.value = value\nself.metadata_type = RoleManagerMetadataBase\nreturn self", "self.name = name\nself.value = value\nself.metadata_type = metadata_type\nself.INSTANCES[value] = self", "if self.value:\n boolean = True\nelse:\n boolean = False\nreturn boolea...
<|body_start_0|> self = object.__new__(cls) self.name = value self.value = value self.metadata_type = RoleManagerMetadataBase return self <|end_body_0|> <|body_start_1|> self.name = name self.value = value self.metadata_type = metadata_type self.I...
Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the predefined ``RoleManagerType``-s. These can be a...
RoleManagerType
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoleManagerType: """Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the prede...
stack_v2_sparse_classes_75kplus_train_074602
5,532
permissive
[ { "docstring": "Creates a new role manager type with the given value. Parameters ---------- value : `int` Value representing the role manager. Returns ------- self : `instance<cls>`", "name": "_from_value", "signature": "def _from_value(cls, value)" }, { "docstring": "Creates a new scheduled eve...
3
stack_v2_sparse_classes_30k_train_040966
Implement the Python class `RoleManagerType` described below. Class description: Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``Ro...
Implement the Python class `RoleManagerType` described below. Class description: Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``Ro...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class RoleManagerType: """Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the prede...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RoleManagerType: """Represents a managed role's manager type. Attributes ---------- name : `str` The name of the role manager type. value : `int` The identifier value the role manager type. Class Attributes ---------------- INSTANCES : `dict` of (`int`, ``RoleManagerType``) items Stores the predefined ``RoleM...
the_stack_v2_python_sparse
hata/discord/role/role/preinstanced.py
HuyaneMatsu/hata
train
3
fb63a824c4bf5f1ab1b465f2c9269fa7ccd1568c
[ "need, missing = (collections.Counter(t), len(t))\ncur_left = res_left = res_right = 0\nfor cur_right, c in enumerate(s, 1):\n missing -= need[c] > 0\n need[c] -= 1\n if not missing:\n while cur_left < cur_right and need[s[cur_left]] < 0:\n need[s[cur_left]] += 1\n cur_left += ...
<|body_start_0|> need, missing = (collections.Counter(t), len(t)) cur_left = res_left = res_right = 0 for cur_right, c in enumerate(s, 1): missing -= need[c] > 0 need[c] -= 1 if not missing: while cur_left < cur_right and need[s[cur_left]] < 0:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minWindow(self, s, t): """:type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still mis...
stack_v2_sparse_classes_75kplus_train_074603
2,478
no_license
[ { "docstring": ":type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still missing. In the loop, first add the new character t...
2
stack_v2_sparse_classes_30k_train_012463
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minWindow(self, s, t): :type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how ma...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minWindow(self, s, t): :type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how ma...
7e0e917c15d3e35f49da3a00ef395bd5ff180d79
<|skeleton|> class Solution: def minWindow(self, s, t): """:type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still mis...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minWindow(self, s, t): """:type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still missing. In the l...
the_stack_v2_python_sparse
LeetCode/076_minimum_window_substring.py
yao23/Machine_Learning_Playground
train
12
54ca611fca0b0a4aa66e57a06d4e3a2d36c25606
[ "gen_hash = archive_util.ArchiveHash(ArchiveUtilTest.FILE_CONTENT)\ngen_hash_mod = archive_util.ArchiveHash(ArchiveUtilTest.FILE_CONTENT_MOD)\nself.assertEqual(gen_hash, ArchiveUtilTest.FILE_CONTENT_MD5)\nself.assertNotEqual(gen_hash_mod, ArchiveUtilTest.FILE_CONTENT_MD5)", "archive_zip = archive_util.ArchiveComp...
<|body_start_0|> gen_hash = archive_util.ArchiveHash(ArchiveUtilTest.FILE_CONTENT) gen_hash_mod = archive_util.ArchiveHash(ArchiveUtilTest.FILE_CONTENT_MOD) self.assertEqual(gen_hash, ArchiveUtilTest.FILE_CONTENT_MD5) self.assertNotEqual(gen_hash_mod, ArchiveUtilTest.FILE_CONTENT_MD5) <|...
Tests for helpers/archive_util.py.
ArchiveUtilTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArchiveUtilTest: """Tests for helpers/archive_util.py.""" def testArchiveHash(self): """Test the hash. This test will fail if the type of hash generated changes.""" <|body_0|> def testArchiveCompress(self): """Test the compression. This test will fail if the type...
stack_v2_sparse_classes_75kplus_train_074604
2,262
permissive
[ { "docstring": "Test the hash. This test will fail if the type of hash generated changes.", "name": "testArchiveHash", "signature": "def testArchiveHash(self)" }, { "docstring": "Test the compression. This test will fail if the type of compression or the type of hash generated changes. The hash ...
2
stack_v2_sparse_classes_30k_train_054524
Implement the Python class `ArchiveUtilTest` described below. Class description: Tests for helpers/archive_util.py. Method signatures and docstrings: - def testArchiveHash(self): Test the hash. This test will fail if the type of hash generated changes. - def testArchiveCompress(self): Test the compression. This test ...
Implement the Python class `ArchiveUtilTest` described below. Class description: Tests for helpers/archive_util.py. Method signatures and docstrings: - def testArchiveHash(self): Test the hash. This test will fail if the type of hash generated changes. - def testArchiveCompress(self): Test the compression. This test ...
9277f9e0623eafe9a2f2cd387f3a2f0dfa9b94ba
<|skeleton|> class ArchiveUtilTest: """Tests for helpers/archive_util.py.""" def testArchiveHash(self): """Test the hash. This test will fail if the type of hash generated changes.""" <|body_0|> def testArchiveCompress(self): """Test the compression. This test will fail if the type...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ArchiveUtilTest: """Tests for helpers/archive_util.py.""" def testArchiveHash(self): """Test the hash. This test will fail if the type of hash generated changes.""" gen_hash = archive_util.ArchiveHash(ArchiveUtilTest.FILE_CONTENT) gen_hash_mod = archive_util.ArchiveHash(ArchiveUti...
the_stack_v2_python_sparse
server/gspeedometer/helpers/archive_util_test.py
Bugbustrs/bugb-mobiperf
train
0
ca69125610caffbe1d74cd51038584422126dafe
[ "self.__compressor = ParserCompressor(compressor_type)\nself.__parser_server = parser_server\nself.__timeout = int(timeout)", "data = {'action': 'parse', 'html': unicode(text)}\njdata = json.dumps(data)\ncdata = self.__compressor.compress(jdata)\ntry:\n result = requests.post(self.__parser_server, cdata, timeo...
<|body_start_0|> self.__compressor = ParserCompressor(compressor_type) self.__parser_server = parser_server self.__timeout = int(timeout) <|end_body_0|> <|body_start_1|> data = {'action': 'parse', 'html': unicode(text)} jdata = json.dumps(data) cdata = self.__compressor....
ParserClient
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParserClient: def __init__(self, parser_server, compressor_type=ParserCompressor.PARSER_ZLIB, timeout=10): """Instance of parser client :param string parser_server: url of parser :param string compressor_type: type of string compressor. @see ParserCompressor :param int timeout: connectio...
stack_v2_sparse_classes_75kplus_train_074605
3,112
no_license
[ { "docstring": "Instance of parser client :param string parser_server: url of parser :param string compressor_type: type of string compressor. @see ParserCompressor :param int timeout: connection timeout", "name": "__init__", "signature": "def __init__(self, parser_server, compressor_type=ParserCompress...
2
stack_v2_sparse_classes_30k_train_052262
Implement the Python class `ParserClient` described below. Class description: Implement the ParserClient class. Method signatures and docstrings: - def __init__(self, parser_server, compressor_type=ParserCompressor.PARSER_ZLIB, timeout=10): Instance of parser client :param string parser_server: url of parser :param s...
Implement the Python class `ParserClient` described below. Class description: Implement the ParserClient class. Method signatures and docstrings: - def __init__(self, parser_server, compressor_type=ParserCompressor.PARSER_ZLIB, timeout=10): Instance of parser client :param string parser_server: url of parser :param s...
7beb2e7db9fe9fb51834d3e633ddfd126391dcf2
<|skeleton|> class ParserClient: def __init__(self, parser_server, compressor_type=ParserCompressor.PARSER_ZLIB, timeout=10): """Instance of parser client :param string parser_server: url of parser :param string compressor_type: type of string compressor. @see ParserCompressor :param int timeout: connectio...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ParserClient: def __init__(self, parser_server, compressor_type=ParserCompressor.PARSER_ZLIB, timeout=10): """Instance of parser client :param string parser_server: url of parser :param string compressor_type: type of string compressor. @see ParserCompressor :param int timeout: connection timeout""" ...
the_stack_v2_python_sparse
pkg/parser_client/client.py
ygavenchuk/code_samples_py
train
0
ddf37877c7d17d389f42ff1651129f159edc0a06
[ "dataseries.VoxelDataSeries.__init__(self, *args, **kwargs)\nif self.overlay.ndim < 4:\n raise ValueError('Overlay is not a 4D image')", "data = dataseries.VoxelDataSeries.currentVoxelData(self, location)\ndata = calcPowerSpectrum(data)\nreturn data", "overlay = self.overlay\nydata = self.dataAtCurrentVoxel(...
<|body_start_0|> dataseries.VoxelDataSeries.__init__(self, *args, **kwargs) if self.overlay.ndim < 4: raise ValueError('Overlay is not a 4D image') <|end_body_0|> <|body_start_1|> data = dataseries.VoxelDataSeries.currentVoxelData(self, location) data = calcPowerSpectrum(dat...
The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.
VoxelPowerSpectrumSeries
[ "Apache-2.0", "CC-BY-3.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VoxelPowerSpectrumSeries: """The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.""" def __init__(self, *args, **kwargs): """Create a ``Voxel...
stack_v2_sparse_classes_75kplus_train_074606
19,177
permissive
[ { "docstring": "Create a ``VoxelPowerSpectrumSeries``. All arguments are passed to the :meth:`VoxelDataSeries.__init__` method. A :exc:`ValueError` is raised if the overlay is not a 4D :class:`.Image`.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Ov...
3
stack_v2_sparse_classes_30k_test_001635
Implement the Python class `VoxelPowerSpectrumSeries` described below. Class description: The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property. Method signatures and docstrings...
Implement the Python class `VoxelPowerSpectrumSeries` described below. Class description: The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property. Method signatures and docstrings...
37b45d034d60660b6de3e4bdf5dd6349ed6d853b
<|skeleton|> class VoxelPowerSpectrumSeries: """The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.""" def __init__(self, *args, **kwargs): """Create a ``Voxel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VoxelPowerSpectrumSeries: """The ``VoxelPowerSpectrumSeries`` class encapsulates the power spectrum of a single voxel from a 4D :class:`.Image` overlay. The voxel is dictated by the :attr:`.DisplayContext.location` property.""" def __init__(self, *args, **kwargs): """Create a ``VoxelPowerSpectrum...
the_stack_v2_python_sparse
fsleyes/plotting/powerspectrumseries.py
CGSchwarzMayo/fsleyes
train
0
8a9ccd5f07c2a995a3afdf3369c4a27b81cdff6f
[ "if not (api_utils.check_user_is_foundation_admin() or api_utils.check_user_is_vendor_admin(vendor_id)):\n return None\norg_users = db.get_organization_users(vendor_id)\nreturn [x for x in six.itervalues(org_users)]", "openid = base64.b64decode(openid)\nif not (api_utils.check_user_is_foundation_admin() or api...
<|body_start_0|> if not (api_utils.check_user_is_foundation_admin() or api_utils.check_user_is_vendor_admin(vendor_id)): return None org_users = db.get_organization_users(vendor_id) return [x for x in six.itervalues(org_users)] <|end_body_0|> <|body_start_1|> openid = base64...
/v1/vendors/<vendor_id>/users handler.
UsersController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UsersController: """/v1/vendors/<vendor_id>/users handler.""" def get(self, vendor_id): """Return list of users in the vendor's group.""" <|body_0|> def put(self, vendor_id, openid): """Add user to vendor group.""" <|body_1|> def delete(self, vendor_...
stack_v2_sparse_classes_75kplus_train_074607
11,223
permissive
[ { "docstring": "Return list of users in the vendor's group.", "name": "get", "signature": "def get(self, vendor_id)" }, { "docstring": "Add user to vendor group.", "name": "put", "signature": "def put(self, vendor_id, openid)" }, { "docstring": "Remove user from vendor group.", ...
3
stack_v2_sparse_classes_30k_train_044424
Implement the Python class `UsersController` described below. Class description: /v1/vendors/<vendor_id>/users handler. Method signatures and docstrings: - def get(self, vendor_id): Return list of users in the vendor's group. - def put(self, vendor_id, openid): Add user to vendor group. - def delete(self, vendor_id, ...
Implement the Python class `UsersController` described below. Class description: /v1/vendors/<vendor_id>/users handler. Method signatures and docstrings: - def get(self, vendor_id): Return list of users in the vendor's group. - def put(self, vendor_id, openid): Add user to vendor group. - def delete(self, vendor_id, ...
0af3a46e16037d13695ef74d35d2ef5909186d97
<|skeleton|> class UsersController: """/v1/vendors/<vendor_id>/users handler.""" def get(self, vendor_id): """Return list of users in the vendor's group.""" <|body_0|> def put(self, vendor_id, openid): """Add user to vendor group.""" <|body_1|> def delete(self, vendor_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UsersController: """/v1/vendors/<vendor_id>/users handler.""" def get(self, vendor_id): """Return list of users in the vendor's group.""" if not (api_utils.check_user_is_foundation_admin() or api_utils.check_user_is_vendor_admin(vendor_id)): return None org_users = db....
the_stack_v2_python_sparse
refstack/api/controllers/vendors.py
openstack-archive/refstack
train
0
d371197f3159147201db5b20c8b839c4526c1bee
[ "self.X = X\nself.Y = Y\nself.K = np.array(K)\nif self.K.shape[0] == 0:\n k = np.ones(self.X.shape[1]) * 0.0001\n self.K = np.diag(k)\nelif self.K.shape[0] != self.X.shape[1]:\n raise ValueError('Precision matrix shape, %i does not match feature matrix shape, %i' % (self.K.shape[0], self.X.shape[1]))", "...
<|body_start_0|> self.X = X self.Y = Y self.K = np.array(K) if self.K.shape[0] == 0: k = np.ones(self.X.shape[1]) * 0.0001 self.K = np.diag(k) elif self.K.shape[0] != self.X.shape[1]: raise ValueError('Precision matrix shape, %i does not match ...
This class fits linear models using bayesian and frequentist methods to data sets
linear_model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class linear_model: """This class fits linear models using bayesian and frequentist methods to data sets""" def __init__(self, X, Y, K=[]): """Parameters ---------- X: float feature matrix Y: float response vector K: float, optional precision matrix for multivariate normal prior on beta if...
stack_v2_sparse_classes_75kplus_train_074608
2,265
no_license
[ { "docstring": "Parameters ---------- X: float feature matrix Y: float response vector K: float, optional precision matrix for multivariate normal prior on beta if not specified, sets a low precision, approximating the frequentist fit Raises ------ ValueError If precision matrix shape does not match shape of fe...
3
stack_v2_sparse_classes_30k_train_054239
Implement the Python class `linear_model` described below. Class description: This class fits linear models using bayesian and frequentist methods to data sets Method signatures and docstrings: - def __init__(self, X, Y, K=[]): Parameters ---------- X: float feature matrix Y: float response vector K: float, optional ...
Implement the Python class `linear_model` described below. Class description: This class fits linear models using bayesian and frequentist methods to data sets Method signatures and docstrings: - def __init__(self, X, Y, K=[]): Parameters ---------- X: float feature matrix Y: float response vector K: float, optional ...
4b129e169c68b6db87f88fc80c7a703d3710beca
<|skeleton|> class linear_model: """This class fits linear models using bayesian and frequentist methods to data sets""" def __init__(self, X, Y, K=[]): """Parameters ---------- X: float feature matrix Y: float response vector K: float, optional precision matrix for multivariate normal prior on beta if...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class linear_model: """This class fits linear models using bayesian and frequentist methods to data sets""" def __init__(self, X, Y, K=[]): """Parameters ---------- X: float feature matrix Y: float response vector K: float, optional precision matrix for multivariate normal prior on beta if not specifie...
the_stack_v2_python_sparse
scripts/linear_models.py
janmichaelcabrera/SDS383D
train
0
20c96b2a15f9417079d418617824268e151a5b0a
[ "if not root:\n return ''\nres = str(root.val)\nif len(root.children) != 0:\n children_res = []\n for child in root.children:\n children_res.append(self.serialize(child))\n res = res + '[' + ' '.join(children_res) + ']'\nreturn res", "if len(data) == 0:\n return None\nstart = data.find('[')\...
<|body_start_0|> if not root: return '' res = str(root.val) if len(root.children) != 0: children_res = [] for child in root.children: children_res.append(self.serialize(child)) res = res + '[' + ' '.join(children_res) + ']' ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_074609
1,698
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def deserialize(self, ...
2
stack_v2_sparse_classes_30k_train_029949
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod...
d87acd5481a2dbfad7288b73750e6e086650a17d
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str""" if not root: return '' res = str(root.val) if len(root.children) != 0: children_res = [] for child in root.children: child...
the_stack_v2_python_sparse
428. Serialize and Deserialize N-ary Tree/428. Serialize and Deserialize N-ary Tree(AC).py
BohaoLiGithub/Leetcode
train
0
7a36aaf857a5828099e7d592894ea8df7b8f3cd4
[ "for li in list:\n if re.search(content, li.text):\n continue\n else:\n return False", "x = []\nfor li in list:\n if re.search(text, li.text):\n x.append(True)\n else:\n x.append(False)\na = False\nreturn not a in x" ]
<|body_start_0|> for li in list: if re.search(content, li.text): continue else: return False <|end_body_0|> <|body_start_1|> x = [] for li in list: if re.search(text, li.text): x.append(True) else: ...
SuperQueryFormPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuperQueryFormPage: def judge_search_content_inlist(self, list, content): """判断输入内容搜索后是否成功""" <|body_0|> def judge_search_text_inlist(self, list, text): """判断输入内容搜索后是否成功""" <|body_1|> <|end_skeleton|> <|body_start_0|> for li in list: if ...
stack_v2_sparse_classes_75kplus_train_074610
7,799
no_license
[ { "docstring": "判断输入内容搜索后是否成功", "name": "judge_search_content_inlist", "signature": "def judge_search_content_inlist(self, list, content)" }, { "docstring": "判断输入内容搜索后是否成功", "name": "judge_search_text_inlist", "signature": "def judge_search_text_inlist(self, list, text)" } ]
2
stack_v2_sparse_classes_30k_test_001380
Implement the Python class `SuperQueryFormPage` described below. Class description: Implement the SuperQueryFormPage class. Method signatures and docstrings: - def judge_search_content_inlist(self, list, content): 判断输入内容搜索后是否成功 - def judge_search_text_inlist(self, list, text): 判断输入内容搜索后是否成功
Implement the Python class `SuperQueryFormPage` described below. Class description: Implement the SuperQueryFormPage class. Method signatures and docstrings: - def judge_search_content_inlist(self, list, content): 判断输入内容搜索后是否成功 - def judge_search_text_inlist(self, list, text): 判断输入内容搜索后是否成功 <|skeleton|> class SuperQ...
78768989a79a14013b983024cf6e4838d51ed595
<|skeleton|> class SuperQueryFormPage: def judge_search_content_inlist(self, list, content): """判断输入内容搜索后是否成功""" <|body_0|> def judge_search_text_inlist(self, list, text): """判断输入内容搜索后是否成功""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SuperQueryFormPage: def judge_search_content_inlist(self, list, content): """判断输入内容搜索后是否成功""" for li in list: if re.search(content, li.text): continue else: return False def judge_search_text_inlist(self, list, text): """判断输入...
the_stack_v2_python_sparse
test_case/page_obj/view/queryform_list_view_page.py
pylk/pythonSelenium
train
0
6aea1337a2ef6d8c9615c81f0785b27608243a9c
[ "raw = self.session.get(f'{self.host}/{id}')\nsoup = self.soup(raw)\nmeta = self.MetaSet()\ncontent = soup.find(class_='post-single-content')\nmeta.register(None, content.text)\nmeta['image'] = soup.find('img', class_='alignnone')['src']\nmeta['judul'] = soup.title.text.split('Subtitle')[0]\nmeta.setItem('romaji', ...
<|body_start_0|> raw = self.session.get(f'{self.host}/{id}') soup = self.soup(raw) meta = self.MetaSet() content = soup.find(class_='post-single-content') meta.register(None, content.text) meta['image'] = soup.find('img', class_='alignnone')['src'] meta['judul'] =...
Drivenime
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Drivenime: def extract_meta(self, id: str) -> dict: """Ambil semua metadata dari halaman web Args: id: type 'str'""" <|body_0|> def extract_data(self, id: str) -> dict: """Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'...
stack_v2_sparse_classes_75kplus_train_074611
3,102
permissive
[ { "docstring": "Ambil semua metadata dari halaman web Args: id: type 'str'", "name": "extract_meta", "signature": "def extract_meta(self, id: str) -> dict" }, { "docstring": "Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'", "name": "extract_da...
3
stack_v2_sparse_classes_30k_val_001606
Implement the Python class `Drivenime` described below. Class description: Implement the Drivenime class. Method signatures and docstrings: - def extract_meta(self, id: str) -> dict: Ambil semua metadata dari halaman web Args: id: type 'str' - def extract_data(self, id: str) -> dict: Ambil semua situs unduhan dari ha...
Implement the Python class `Drivenime` described below. Class description: Implement the Drivenime class. Method signatures and docstrings: - def extract_meta(self, id: str) -> dict: Ambil semua metadata dari halaman web Args: id: type 'str' - def extract_data(self, id: str) -> dict: Ambil semua situs unduhan dari ha...
7aef096a6fd549ae7ab11092470609518371b10a
<|skeleton|> class Drivenime: def extract_meta(self, id: str) -> dict: """Ambil semua metadata dari halaman web Args: id: type 'str'""" <|body_0|> def extract_data(self, id: str) -> dict: """Ambil semua situs unduhan dari halaman web Args: id: jalur url dimulai setelah host, type 'str'...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Drivenime: def extract_meta(self, id: str) -> dict: """Ambil semua metadata dari halaman web Args: id: type 'str'""" raw = self.session.get(f'{self.host}/{id}') soup = self.soup(raw) meta = self.MetaSet() content = soup.find(class_='post-single-content') meta.re...
the_stack_v2_python_sparse
lk21/extractors/drivenime.py
JawsKen98/lk21
train
0
325629fb7e740c1288b401ac885bb7997ad22003
[ "Deferred.__init__(self, 'axes(%ld,%ld)' % (row, col))\nself.row = row\nself.col = col\nself.title = title\nself.plots = {}\nself.kwargs = kwargs\nself.ax = None", "assert self.ax is None, 'Internal error; function called twice?'\nnum = 1 + self.col + self.row * cols\nself.ax = fig.add_subplot(rows, cols, num, **...
<|body_start_0|> Deferred.__init__(self, 'axes(%ld,%ld)' % (row, col)) self.row = row self.col = col self.title = title self.plots = {} self.kwargs = kwargs self.ax = None <|end_body_0|> <|body_start_1|> assert self.ax is None, 'Internal error; function c...
Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep working in deferred mode. figure.render() Example ------- fig = figure() ax = ...
DynamicAx
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DynamicAx: """Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep working in deferred mode. figure.render()...
stack_v2_sparse_classes_75kplus_train_074612
16,719
permissive
[ { "docstring": "Creates internal object which defers the creation of various graphics to a later point", "name": "__init__", "signature": "def __init__(self, row: int, col: int, title: str, kwargs: dict)" }, { "docstring": "Creates the plot by calling all 'caught' functions calls in sequece", ...
2
stack_v2_sparse_classes_30k_train_028183
Implement the Python class `DynamicAx` described below. Class description: Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep wo...
Implement the Python class `DynamicAx` described below. Class description: Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep wo...
bca73adeecdbf71a1f5ee466ded67d6c1ed4e94d
<|skeleton|> class DynamicAx: """Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep working in deferred mode. figure.render()...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DynamicAx: """Wrapper around an matplotlib axis returned by DynamicFig, which is returned by figure(). All calls to the returned axis are delegated to matplotlib. The results of deferred function calls are again deferred objects, allowing (mostly) to keep working in deferred mode. figure.render() Example ----...
the_stack_v2_python_sparse
cdxbasics/dynaplot.py
hansbuehler/cdxbasics
train
2
82e68218f89e73b323abc0a0de2a2046b7f7d007
[ "wx.Frame.__init__(self, parent, title=title, size=(300, 200))\nvbox = wx.BoxSizer(wx.VERTICAL)\nstartButton = wx.Button(self, label='Start!')\nvbox.Add(startButton)\nself.SetSizer(vbox)\nself.Show(True)", "self.dirname = ''\ndlg = wx.FileDialog(self, 'Choose a file', self.dirname, '', '*.*', wx.OPEN)\nif dlg.Sho...
<|body_start_0|> wx.Frame.__init__(self, parent, title=title, size=(300, 200)) vbox = wx.BoxSizer(wx.VERTICAL) startButton = wx.Button(self, label='Start!') vbox.Add(startButton) self.SetSizer(vbox) self.Show(True) <|end_body_0|> <|body_start_1|> self.dirname = '...
MainWin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MainWin: def __init__(self, parent, title): """Init""" <|body_0|> def OnOpen(self, e): """Open a file""" <|body_1|> <|end_skeleton|> <|body_start_0|> wx.Frame.__init__(self, parent, title=title, size=(300, 200)) vbox = wx.BoxSizer(wx.VERTICA...
stack_v2_sparse_classes_75kplus_train_074613
970
no_license
[ { "docstring": "Init", "name": "__init__", "signature": "def __init__(self, parent, title)" }, { "docstring": "Open a file", "name": "OnOpen", "signature": "def OnOpen(self, e)" } ]
2
null
Implement the Python class `MainWin` described below. Class description: Implement the MainWin class. Method signatures and docstrings: - def __init__(self, parent, title): Init - def OnOpen(self, e): Open a file
Implement the Python class `MainWin` described below. Class description: Implement the MainWin class. Method signatures and docstrings: - def __init__(self, parent, title): Init - def OnOpen(self, e): Open a file <|skeleton|> class MainWin: def __init__(self, parent, title): """Init""" <|body_0|...
67e3576e98a7a6ed6b39874799c46e3f2746907e
<|skeleton|> class MainWin: def __init__(self, parent, title): """Init""" <|body_0|> def OnOpen(self, e): """Open a file""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MainWin: def __init__(self, parent, title): """Init""" wx.Frame.__init__(self, parent, title=title, size=(300, 200)) vbox = wx.BoxSizer(wx.VERTICAL) startButton = wx.Button(self, label='Start!') vbox.Add(startButton) self.SetSizer(vbox) self.Show(True) ...
the_stack_v2_python_sparse
Python/RedditSuite/reddit.py
rox04/pri_code
train
0
55f2fac48190665cf1b95037673e862225a2f573
[ "self.id = id\nself.title = title\nself.description = description\nself.mtype = mtype\nself.file_name = file_name\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nid = dictionary.get('id')\ntitle = dictionary.get('title')\ndescription = dictionary.get('description')\...
<|body_start_0|> self.id = id self.title = title self.description = description self.mtype = mtype self.file_name = file_name self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type description here. file_name (string): TODO: type descri...
AttachmentListItem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type descripti...
stack_v2_sparse_classes_75kplus_train_074614
2,692
permissive
[ { "docstring": "Constructor for the AttachmentListItem class", "name": "__init__", "signature": "def __init__(self, id=None, title=None, description=None, mtype=None, file_name=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionar...
2
stack_v2_sparse_classes_30k_train_014996
Implement the Python class `AttachmentListItem` described below. Class description: Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description h...
Implement the Python class `AttachmentListItem` described below. Class description: Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description h...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type descripti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AttachmentListItem: """Implementation of the 'AttachmentListItem' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. title (string): TODO: type description here. description (string): TODO: type description here. mtype (Type): TODO: type description here. file...
the_stack_v2_python_sparse
idfy_rest_client/models/attachment_list_item.py
dealflowteam/Idfy
train
0
587db44819c558ed266abf1d27e4d09cc81b2ac0
[ "self.wordIdx = collections.defaultdict(list)\nfor idx, word in enumerate(words):\n self.wordIdx[word].append(idx)", "iword1 = self.wordIdx[word1]\niword2 = self.wordIdx[word2]\nif not iword1 or not iword2:\n return -1\ni, j = (0, 0)\nsd, word1Idx, word2Idx = (1 << 31, -1, -1)\nwhile i < len(iword1) and j <...
<|body_start_0|> self.wordIdx = collections.defaultdict(list) for idx, word in enumerate(words): self.wordIdx[word].append(idx) <|end_body_0|> <|body_start_1|> iword1 = self.wordIdx[word1] iword2 = self.wordIdx[word2] if not iword1 or not iword2: return -...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """Adds a word into the data structure. :type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_75kplus_train_074615
1,152
no_license
[ { "docstring": "initialize your data structure here. :type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortes...
2
stack_v2_sparse_classes_30k_train_012999
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): initialize your data structure here. :type words: List[str] - def shortest(self, word1, word2): Adds a word into the data structure. :type word...
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): initialize your data structure here. :type words: List[str] - def shortest(self, word1, word2): Adds a word into the data structure. :type word...
45e6ba66104bb43efcce39adc92a4904f50c605d
<|skeleton|> class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """Adds a word into the data structure. :type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WordDistance: def __init__(self, words): """initialize your data structure here. :type words: List[str]""" self.wordIdx = collections.defaultdict(list) for idx, word in enumerate(words): self.wordIdx[word].append(idx) def shortest(self, word1, word2): """Adds a...
the_stack_v2_python_sparse
LeetCode/pythonSols/String/shortestDistance2.py
abhitrip/scratchpad
train
0
1b1e4af1469ce99c07cc767f733edde71fd82f04
[ "if target_type not in feconf.SUGGESTION_TARGET_TYPE_CHOICES:\n raise self.InvalidInputException('Invalid target_type: %s' % target_type)\nif suggestion_type not in feconf.SUGGESTION_TYPE_CHOICES:\n raise self.InvalidInputException('Invalid suggestion_type: %s' % suggestion_type)", "if target_type == feconf...
<|body_start_0|> if target_type not in feconf.SUGGESTION_TARGET_TYPE_CHOICES: raise self.InvalidInputException('Invalid target_type: %s' % target_type) if suggestion_type not in feconf.SUGGESTION_TYPE_CHOICES: raise self.InvalidInputException('Invalid suggestion_type: %s' % sugge...
Provides suggestions for a user and given suggestion type.
SuggestionsProviderHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuggestionsProviderHandler: """Provides suggestions for a user and given suggestion type.""" def _require_valid_suggestion_and_target_types(self, target_type: str, suggestion_type: str) -> None: """Checks whether the given target_type and suggestion_type are valid. Args: target_type:...
stack_v2_sparse_classes_75kplus_train_074616
44,777
permissive
[ { "docstring": "Checks whether the given target_type and suggestion_type are valid. Args: target_type: str. The type of the suggestion target. suggestion_type: str. The type of the suggestion. Raises: InvalidInputException. If the given target_type of suggestion_type are invalid.", "name": "_require_valid_s...
2
stack_v2_sparse_classes_30k_val_001623
Implement the Python class `SuggestionsProviderHandler` described below. Class description: Provides suggestions for a user and given suggestion type. Method signatures and docstrings: - def _require_valid_suggestion_and_target_types(self, target_type: str, suggestion_type: str) -> None: Checks whether the given targ...
Implement the Python class `SuggestionsProviderHandler` described below. Class description: Provides suggestions for a user and given suggestion type. Method signatures and docstrings: - def _require_valid_suggestion_and_target_types(self, target_type: str, suggestion_type: str) -> None: Checks whether the given targ...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class SuggestionsProviderHandler: """Provides suggestions for a user and given suggestion type.""" def _require_valid_suggestion_and_target_types(self, target_type: str, suggestion_type: str) -> None: """Checks whether the given target_type and suggestion_type are valid. Args: target_type:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SuggestionsProviderHandler: """Provides suggestions for a user and given suggestion type.""" def _require_valid_suggestion_and_target_types(self, target_type: str, suggestion_type: str) -> None: """Checks whether the given target_type and suggestion_type are valid. Args: target_type: str. The typ...
the_stack_v2_python_sparse
core/controllers/suggestion.py
oppia/oppia
train
6,172
39c9b5298d8c8cd7839c9e81598084b9101cdd20
[ "self.path = path\nself.loader = loader\nself._mtime = None\nself._cached = None\nself._auto_reload = auto_reload", "if self._mtime and (not self._auto_reload):\n return self._cached\ncurrent_mtime = os.path.getmtime(self.path)\nif not self._mtime or self._mtime < current_mtime:\n self._cached = self.loader...
<|body_start_0|> self.path = path self.loader = loader self._mtime = None self._cached = None self._auto_reload = auto_reload <|end_body_0|> <|body_start_1|> if self._mtime and (not self._auto_reload): return self._cached current_mtime = os.path.getmt...
Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader.
_CachedFile
[ "BSD-3-Clause", "BSD-2-Clause-Views", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _CachedFile: """Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader.""" def __init__(self, path, loader, auto_reload=False): """:param path: The path to the file to load. :param loader: A callable t...
stack_v2_sparse_classes_75kplus_train_074617
5,538
permissive
[ { "docstring": ":param path: The path to the file to load. :param loader: A callable that will be passed the file object and should return the parsed content. :param auto_reload: If True, the parsed content is discarded if the mtime of the file changes.", "name": "__init__", "signature": "def __init__(s...
2
null
Implement the Python class `_CachedFile` described below. Class description: Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader. Method signatures and docstrings: - def __init__(self, path, loader, auto_reload=False): :param path: ...
Implement the Python class `_CachedFile` described below. Class description: Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader. Method signatures and docstrings: - def __init__(self, path, loader, auto_reload=False): :param path: ...
91c7a4504ad7471ed3e30246763a03e6c1cc531b
<|skeleton|> class _CachedFile: """Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader.""" def __init__(self, path, loader, auto_reload=False): """:param path: The path to the file to load. :param loader: A callable t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _CachedFile: """Parses content from a file and caches the result. _CachedFile reads a file at a given path and parses the content using a provided loader.""" def __init__(self, path, loader, auto_reload=False): """:param path: The path to the file to load. :param loader: A callable that will be p...
the_stack_v2_python_sparse
h/assets.py
11-eleven-11/h
train
2
28214f4f210989418f9c7ac1507b0edb367ecdb1
[ "if HAS_ISBD and ISelectableBrowserDefault.providedBy(target):\n return target.getLayout()\nelse:\n view = target.getTypeInfo().getActionById('view') or 'base_view'\n if view == 'view':\n view = target.portal_type.lower() + '_view'\n return view", "data = [HelpCenterReferenceManualSection.Searc...
<|body_start_0|> if HAS_ISBD and ISelectableBrowserDefault.providedBy(target): return target.getLayout() else: view = target.getTypeInfo().getActionById('view') or 'base_view' if view == 'view': view = target.portal_type.lower() + '_view' r...
A section of a hierarchical document. It can contain sections and pages.
BungeniHelpCenterReferenceManualSection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BungeniHelpCenterReferenceManualSection: """A section of a hierarchical document. It can contain sections and pages.""" def getTargetObjectLayout(self, target): """Returns target object 'view' action page template""" <|body_0|> def SearchableText(self): """Append...
stack_v2_sparse_classes_75kplus_train_074618
34,826
no_license
[ { "docstring": "Returns target object 'view' action page template", "name": "getTargetObjectLayout", "signature": "def getTargetObjectLayout(self, target)" }, { "docstring": "Append references' searchable fields.", "name": "SearchableText", "signature": "def SearchableText(self)" } ]
2
stack_v2_sparse_classes_30k_test_001663
Implement the Python class `BungeniHelpCenterReferenceManualSection` described below. Class description: A section of a hierarchical document. It can contain sections and pages. Method signatures and docstrings: - def getTargetObjectLayout(self, target): Returns target object 'view' action page template - def Searcha...
Implement the Python class `BungeniHelpCenterReferenceManualSection` described below. Class description: A section of a hierarchical document. It can contain sections and pages. Method signatures and docstrings: - def getTargetObjectLayout(self, target): Returns target object 'view' action page template - def Searcha...
5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d
<|skeleton|> class BungeniHelpCenterReferenceManualSection: """A section of a hierarchical document. It can contain sections and pages.""" def getTargetObjectLayout(self, target): """Returns target object 'view' action page template""" <|body_0|> def SearchableText(self): """Append...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BungeniHelpCenterReferenceManualSection: """A section of a hierarchical document. It can contain sections and pages.""" def getTargetObjectLayout(self, target): """Returns target object 'view' action page template""" if HAS_ISBD and ISelectableBrowserDefault.providedBy(target): ...
the_stack_v2_python_sparse
plone.products/BungeniHelpCenter/branches/plone4/content/HelpCenter.py
malangalanga/bungeni-portal
train
0
4e11c631748b22e690812ceaec6da6e614889ae4
[ "if not head or not head.next:\n return head\npre = None\nwhile head:\n cur = head\n head = head.next\n cur.next = pre\n pre = cur\nreturn pre", "if not head or not head.next:\n return head\nlast = self.reverseList1(head.next)\nhead.next.next = head\nhead.next = None\nreturn last" ]
<|body_start_0|> if not head or not head.next: return head pre = None while head: cur = head head = head.next cur.next = pre pre = cur return pre <|end_body_0|> <|body_start_1|> if not head or not head.next: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList(self, head): """递归""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head or not head.next: return head pre = Non...
stack_v2_sparse_classes_75kplus_train_074619
1,145
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList1", "signature": "def reverseList1(self, head)" }, { "docstring": "递归", "name": "reverseList", "signature": "def reverseList(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_038652
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList1(self, head): :type head: ListNode :rtype: ListNode - def reverseList(self, head): 递归
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList1(self, head): :type head: ListNode :rtype: ListNode - def reverseList(self, head): 递归 <|skeleton|> class Solution: def reverseList1(self, head): """...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList(self, head): """递归""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" if not head or not head.next: return head pre = None while head: cur = head head = head.next cur.next = pre pre = cur return p...
the_stack_v2_python_sparse
out/production/leetcode/206.反转链表.py
yangyuxiang1996/leetcode
train
0
57298d850f1a1bc7ed11a0edb26354bce1ebbaa8
[ "super(FtwTorso, self).__init__(name=name)\nfor arg_name, filters_description in [('conv_filters', conv_filters), ('residual_filters', residual_filters)]:\n if not (isinstance(filters_description, Sequence) and all([len(layer_triple) == 3 and all([isinstance(arg, int) for arg in layer_triple]) for layer_triple i...
<|body_start_0|> super(FtwTorso, self).__init__(name=name) for arg_name, filters_description in [('conv_filters', conv_filters), ('residual_filters', residual_filters)]: if not (isinstance(filters_description, Sequence) and all([len(layer_triple) == 3 and all([isinstance(arg, int) for arg in...
Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material.
FtwTorso
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FtwTorso: """Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material.""" def __init__(self, conv_filters: Sequence[Tuple[int, int, int]]=((32, 8, 4), (64, 4, 2)), residual_filters: Sequence[Tuple[int, ...
stack_v2_sparse_classes_75kplus_train_074620
4,978
no_license
[ { "docstring": "Initializes the FtwTorso module. Args: conv_filters: Sequence of int triples (num_channels, kernel_size, stride) indicating the number of channels, the kernel size (also called filter size) and stride for each (non-residual) convolutional layer in the sequence. residual_filters: Sequence of int ...
2
null
Implement the Python class `FtwTorso` described below. Class description: Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material. Method signatures and docstrings: - def __init__(self, conv_filters: Sequence[Tuple[int, int, in...
Implement the Python class `FtwTorso` described below. Class description: Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material. Method signatures and docstrings: - def __init__(self, conv_filters: Sequence[Tuple[int, int, in...
1c2b2768f2c5996c8cc998d0271f3857949bdaeb
<|skeleton|> class FtwTorso: """Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material.""" def __init__(self, conv_filters: Sequence[Tuple[int, int, int]]=((32, 8, 4), (64, 4, 2)), residual_filters: Sequence[Tuple[int, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FtwTorso: """Visual embedding module as used in the FTW paper. See also the FTW paper for more information, especially Figure S11 of the supplementary material.""" def __init__(self, conv_filters: Sequence[Tuple[int, int, int]]=((32, 8, 4), (64, 4, 2)), residual_filters: Sequence[Tuple[int, int, int]]=((...
the_stack_v2_python_sparse
ftw/tf/networks/vision.py
RaoulDrake/ftw
train
3
c7d4d9c555f6a4d6ea6c1d92f47256ba6f4e935d
[ "self.mode = mode\nself.ids_rulesets = ids_rulesets\nself.protected_networks = protected_networks", "if dictionary is None:\n return None\nmode = dictionary.get('mode')\nids_rulesets = dictionary.get('idsRulesets')\nprotected_networks = meraki_sdk.models.protected_networks_model.ProtectedNetworksModel.from_dic...
<|body_start_0|> self.mode = mode self.ids_rulesets = ids_rulesets self.protected_networks = protected_networks <|end_body_0|> <|body_start_1|> if dictionary is None: return None mode = dictionary.get('mode') ids_rulesets = dictionary.get('idsRulesets') ...
Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_rulesets (string): Set the detection ruleset 'connectivity'/'balanced'/'securi...
UpdateNetworkSecurityIntrusionSettingsModel
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateNetworkSecurityIntrusionSettingsModel: """Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_ruleset...
stack_v2_sparse_classes_75kplus_train_074621
2,701
permissive
[ { "docstring": "Constructor for the UpdateNetworkSecurityIntrusionSettingsModel class", "name": "__init__", "signature": "def __init__(self, mode=None, ids_rulesets=None, protected_networks=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary...
2
stack_v2_sparse_classes_30k_train_049925
Implement the Python class `UpdateNetworkSecurityIntrusionSettingsModel` described below. Class description: Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leav...
Implement the Python class `UpdateNetworkSecurityIntrusionSettingsModel` described below. Class description: Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leav...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class UpdateNetworkSecurityIntrusionSettingsModel: """Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_ruleset...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UpdateNetworkSecurityIntrusionSettingsModel: """Implementation of the 'updateNetworkSecurityIntrusionSettings' model. TODO: type model description here. Attributes: mode (string): Set mode to 'disabled'/'detection'/'prevention' (optional - omitting will leave current config unchanged) ids_rulesets (string): S...
the_stack_v2_python_sparse
meraki_sdk/models/update_network_security_intrusion_settings_model.py
RaulCatalano/meraki-python-sdk
train
1
6d630a1d642c165be92d9a1b29c563976f692ff1
[ "if name in ['E', 'X', 'Z']:\n raise ValueError('you are attempting to redefine %s; but you should never redefine E, X or Z in gap3 (because things will break!)' % name)\nsuper(GAP3Element, self).__init__(parent, value, is_name, name)\nparent._synchronize()\nif parent.eval('IsRec(%s)' % self._name) == 'true':\n ...
<|body_start_0|> if name in ['E', 'X', 'Z']: raise ValueError('you are attempting to redefine %s; but you should never redefine E, X or Z in gap3 (because things will break!)' % name) super(GAP3Element, self).__init__(parent, value, is_name, name) parent._synchronize() if par...
A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: False); if True, then ``value`` is the variable name for the object - ``name`` -...
GAP3Element
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GAP3Element: """A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: False); if True, then ``value`` is the va...
stack_v2_sparse_classes_75kplus_train_074622
34,820
no_license
[ { "docstring": "See ``GAP3Element`` for full documentation. EXAMPLES:: sage: from sage.interfaces.gap3 import GAP3Element #optional - gap3 sage: gap3 = Gap3() #optional - gap3 sage: GAP3Element(gap3, value='3+2') #optional - gap3 5 sage: GAP3Element(gap3, value='sage0', is_name=True) #optional - gap3 5 TESTS:: ...
3
stack_v2_sparse_classes_30k_train_042622
Implement the Python class `GAP3Element` described below. Class description: A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: Fa...
Implement the Python class `GAP3Element` described below. Class description: A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: Fa...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class GAP3Element: """A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: False); if True, then ``value`` is the va...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GAP3Element: """A GAP3 element .. NOTE:: If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. INPUT: - ``parent`` -- the GAP3 session - ``value`` -- the GAP3 command as a string - ``is_name`` -- bool (default: False); if True, then ``value`` is the variable name f...
the_stack_v2_python_sparse
sage/src/sage/interfaces/gap3.py
bopopescu/geosci
train
0
cc4cad806f79a8d13adb1915a63c06201e65d2c7
[ "context = super().get_context_data(**kwargs)\ncontext['rocnik'] = Rocnik.objects.get(pk=self.kwargs['rocnik_pk'])\ncontext['subheader'] = self.subheader\nreturn context", "self.request.session['zdrojovy_formular'] = 'zavody:import_textu_casu'\ncontext = self.get_context_data()\ncontext['formset'] = ImportyCilove...
<|body_start_0|> context = super().get_context_data(**kwargs) context['rocnik'] = Rocnik.objects.get(pk=self.kwargs['rocnik_pk']) context['subheader'] = self.subheader return context <|end_body_0|> <|body_start_1|> self.request.session['zdrojovy_formular'] = 'zavody:import_textu...
Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3: 00:09.6 00:02.8 2: 00:06.7 00:01.9 1: 00:04.8 00:04.8
ImportCasuTextView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImportCasuTextView: """Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3: 00:09.6 00:02.8 2: 00:06.7 00:01.9 1:...
stack_v2_sparse_classes_75kplus_train_074623
27,940
no_license
[ { "docstring": "prida do 'rocnik' a 'subheader'", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "zobrazi formset s daty ze souboru", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
null
Implement the Python class `ImportCasuTextView` described below. Class description: Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3...
Implement the Python class `ImportCasuTextView` described below. Class description: Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3...
b3d6bfa0090cbb2a546a632e735b98ae653efc7d
<|skeleton|> class ImportCasuTextView: """Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3: 00:09.6 00:02.8 2: 00:06.7 00:01.9 1:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImportCasuTextView: """Vkladani casu zkopirovaneho ze stopek do textoveho pole a jeho zpracovani http://play.google.com/store/apps/details?id=uk.co.dedmondson.timer.split 03:02.4 (ignorovat) 01:50.4 (ignorovat) --------------------------------- (ignorovat) 3: 00:09.6 00:02.8 2: 00:06.7 00:01.9 1: 00:04.8 00:0...
the_stack_v2_python_sparse
zavody/views.py
gumish/hanes
train
0
cf8ad7922cb70a6d2afaa818d62998ace58c1142
[ "app.setStyle('Fusion')\nwith open(self._STYLESHEET) as stylesheet:\n app.setStyleSheet(stylesheet.read())", "darkPalette = QPalette()\ndarkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))\ndarkPalette.setColor(QPalette.Button, QColor(53, 53, 53))\ndarkPalette.setColor(QPalette.Light, QColor(180, 1...
<|body_start_0|> app.setStyle('Fusion') with open(self._STYLESHEET) as stylesheet: app.setStyleSheet(stylesheet.read()) <|end_body_0|> <|body_start_1|> darkPalette = QPalette() darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180)) darkPalette.setColor(QPal...
DarkStyle
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DarkStyle: def _apply_base_theme(self, app): """Apply base theme to the application. Args: app (QApplication): QApplication instance.""" <|body_0|> def apply_style(self, app): """Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ...
stack_v2_sparse_classes_75kplus_train_074624
5,792
permissive
[ { "docstring": "Apply base theme to the application. Args: app (QApplication): QApplication instance.", "name": "_apply_base_theme", "signature": "def _apply_base_theme(self, app)" }, { "docstring": "Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance...
2
stack_v2_sparse_classes_30k_train_036046
Implement the Python class `DarkStyle` described below. Class description: Implement the DarkStyle class. Method signatures and docstrings: - def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance. - def apply_style(self, app): Apply Dark Theme to the Qt...
Implement the Python class `DarkStyle` described below. Class description: Implement the DarkStyle class. Method signatures and docstrings: - def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance. - def apply_style(self, app): Apply Dark Theme to the Qt...
7a79feab40ec801198ea5d519948ccbfd0203df3
<|skeleton|> class DarkStyle: def _apply_base_theme(self, app): """Apply base theme to the application. Args: app (QApplication): QApplication instance.""" <|body_0|> def apply_style(self, app): """Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DarkStyle: def _apply_base_theme(self, app): """Apply base theme to the application. Args: app (QApplication): QApplication instance.""" app.setStyle('Fusion') with open(self._STYLESHEET) as stylesheet: app.setStyleSheet(stylesheet.read()) def apply_style(self, app): ...
the_stack_v2_python_sparse
folderplay/gui/styles.py
hurlenko/folderplay
train
1
4b834bff6afa2a4141d3f6a309837a88f7372d2d
[ "self.name = name\nself.independent_probs = independent_probs\nself.augmentors = []\nself.probs = []", "augm_images = images\nif self.independent_probs:\n for i in xrange(len(self.augmentors)):\n augmentor = self.augmentors[i]\n prob = self.probs[i]\n if prob is None:\n augm_ima...
<|body_start_0|> self.name = name self.independent_probs = independent_probs self.augmentors = [] self.probs = [] <|end_body_0|> <|body_start_1|> augm_images = images if self.independent_probs: for i in xrange(len(self.augmentors)): augmentor ...
Class to define the set of augmentors with specified probability.
AugmentFactory
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AugmentFactory: """Class to define the set of augmentors with specified probability.""" def __init__(self, independent_probs=True, name='IndependentAugmentFactory'): """Constructor. :param independent_probs: Whether to normalize input probabilities :param name: Class name""" ...
stack_v2_sparse_classes_75kplus_train_074625
24,391
permissive
[ { "docstring": "Constructor. :param independent_probs: Whether to normalize input probabilities :param name: Class name", "name": "__init__", "signature": "def __init__(self, independent_probs=True, name='IndependentAugmentFactory')" }, { "docstring": "Carry out augmentation of image batch :para...
4
stack_v2_sparse_classes_30k_train_016540
Implement the Python class `AugmentFactory` described below. Class description: Class to define the set of augmentors with specified probability. Method signatures and docstrings: - def __init__(self, independent_probs=True, name='IndependentAugmentFactory'): Constructor. :param independent_probs: Whether to normaliz...
Implement the Python class `AugmentFactory` described below. Class description: Class to define the set of augmentors with specified probability. Method signatures and docstrings: - def __init__(self, independent_probs=True, name='IndependentAugmentFactory'): Constructor. :param independent_probs: Whether to normaliz...
c553a56088f0055baba838b68c9299e19683227e
<|skeleton|> class AugmentFactory: """Class to define the set of augmentors with specified probability.""" def __init__(self, independent_probs=True, name='IndependentAugmentFactory'): """Constructor. :param independent_probs: Whether to normalize input probabilities :param name: Class name""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AugmentFactory: """Class to define the set of augmentors with specified probability.""" def __init__(self, independent_probs=True, name='IndependentAugmentFactory'): """Constructor. :param independent_probs: Whether to normalize input probabilities :param name: Class name""" self.name = n...
the_stack_v2_python_sparse
tensorflow_toolkit/action_detection/action_detection/nn/data/augmentation.py
DmitriySidnev/openvino_training_extensions
train
0
615f20e83a11cc1bf9b1899748835559aa3d6293
[ "if not root:\n return 'null'\noutput = []\nmy_queue = []\nmy_queue.append(root)\nwhile my_queue:\n l = len(my_queue)\n for i in range(l):\n curr_node = my_queue.pop(0)\n if curr_node:\n output.append(curr_node.val)\n my_queue.append(curr_node.left)\n my_queue...
<|body_start_0|> if not root: return 'null' output = [] my_queue = [] my_queue.append(root) while my_queue: l = len(my_queue) for i in range(l): curr_node = my_queue.pop(0) if curr_node: outpu...
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_074626
2,255
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_008609
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:...
3f5ad6164c147e7b51b7850dcd279150fa8a7600
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return 'null' output = [] my_queue = [] my_queue.append(root) while my_queue: l = len(my_queue) for i in ...
the_stack_v2_python_sparse
Round_1/297. Serialize and Deserialize Binary Tree/solution_2.py
buptwxd2/leetcode
train
0
4ad36df7c63f624ea5457349ab79c2488c67db01
[ "confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S')\nwarfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%d %H:%M:%S')\ncon = logging.StreamHandler(sys.stdout)\ncon.setLevel(logging.DEBUG)\ncon.setFormatter(confor)\nwar = logging.handlers.RotatingFileHa...
<|body_start_0|> confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S') warfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%d %H:%M:%S') con = logging.StreamHandler(sys.stdout) con.setLevel(logging.DEBUG) con.setFormatte...
Ironworks logger
IronworksLogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IronworksLogger: """Ironworks logger""" def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): """init the logger""" <|body_0|> def log(self, toLog, logLevel): """wrapper for logger output""" <|body_1|> <|end_skeleton|> <|body_start_0|> confor = lo...
stack_v2_sparse_classes_75kplus_train_074627
2,179
permissive
[ { "docstring": "init the logger", "name": "__init__", "signature": "def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT)" }, { "docstring": "wrapper for logger output", "name": "log", "signature": "def log(self, toLog, logLevel)" } ]
2
stack_v2_sparse_classes_30k_train_019442
Implement the Python class `IronworksLogger` described below. Class description: Ironworks logger Method signatures and docstrings: - def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): init the logger - def log(self, toLog, logLevel): wrapper for logger output
Implement the Python class `IronworksLogger` described below. Class description: Ironworks logger Method signatures and docstrings: - def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): init the logger - def log(self, toLog, logLevel): wrapper for logger output <|skeleton|> class IronworksLogger: """Ironworks lo...
37be48e37f63530dd7bf82618948ef82522699a0
<|skeleton|> class IronworksLogger: """Ironworks logger""" def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): """init the logger""" <|body_0|> def log(self, toLog, logLevel): """wrapper for logger output""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IronworksLogger: """Ironworks logger""" def __init__(self, LOG_FILE, VERBOSE, DEVELOPMENT): """init the logger""" confor = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s', '%H:%M:%S') warfor = logging.Formatter('%(asctime)s :: %(levelname)-8s :: %(message)s', '%b-%...
the_stack_v2_python_sparse
ironworks/logger.py
hephaestus9/Ironworks
train
1
b8a5f73c7b8a0095184545117285054f43085ab4
[ "sol_spo = torch.unsqueeze(torch.tensor(sol_spo), 1)\nobjval_predictions_true = torch.dot(sol_spo[:, 0], coeffs_true[:, 0])\nctx.save_for_backward(sol_spo, sol_true)\nreturn torch.tensor([objval_predictions_true])", "grad_input = grad_output.clone()\nsol_spo, sol_true = ctx.saved_tensors\nsubgradient = 2 * (sol_t...
<|body_start_0|> sol_spo = torch.unsqueeze(torch.tensor(sol_spo), 1) objval_predictions_true = torch.dot(sol_spo[:, 0], coeffs_true[:, 0]) ctx.save_for_backward(sol_spo, sol_true) return torch.tensor([objval_predictions_true]) <|end_body_0|> <|body_start_1|> grad_input = grad_ou...
We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.
SPOLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SPOLoss: """We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.""" def forward(ctx, coeffs_predictions, coeffs_true, sol_spo, sol_true): """In the forward pass we receive ...
stack_v2_sparse_classes_75kplus_train_074628
4,260
no_license
[ { "docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.", ...
2
stack_v2_sparse_classes_30k_train_042219
Implement the Python class `SPOLoss` described below. Class description: We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. Method signatures and docstrings: - def forward(ctx, coeffs_predictions, coeffs_...
Implement the Python class `SPOLoss` described below. Class description: We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. Method signatures and docstrings: - def forward(ctx, coeffs_predictions, coeffs_...
5b52289da54162aff35bc8c2ecc9a2959f6f96b7
<|skeleton|> class SPOLoss: """We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.""" def forward(ctx, coeffs_predictions, coeffs_true, sol_spo, sol_true): """In the forward pass we receive ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SPOLoss: """We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors.""" def forward(ctx, coeffs_predictions, coeffs_true, sol_spo, sol_true): """In the forward pass we receive a Tensor cont...
the_stack_v2_python_sparse
model_execution/spo_torch.py
lyeskhalil/mipGNN
train
16
64be7b63fe73434be9d0f771faf85ec51e86d8c7
[ "assert_is_instance(l_plus, np.ndarray, 'L plus has to be a np array')\nassert_is_instance(l_minus, np.ndarray, 'L minus has to be a np array')\nassert_condition(l_plus.shape == l_minus.shape, TypeError, 'It is not an splitting')\nassert_is_instance(level, IMultigridLevel, 'Not the right level')\nself.order = kwarg...
<|body_start_0|> assert_is_instance(l_plus, np.ndarray, 'L plus has to be a np array') assert_is_instance(l_minus, np.ndarray, 'L minus has to be a np array') assert_condition(l_plus.shape == l_minus.shape, TypeError, 'It is not an splitting') assert_is_instance(level, IMultigridLevel, '...
A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.
SplitSmoother
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplitSmoother: """A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.""" def __init__(self, l_plus, l_minus, level, *args, **kwargs): """init method of the split...
stack_v2_sparse_classes_75kplus_train_074629
9,259
no_license
[ { "docstring": "init method of the split smoother l_plus and l_minus have to be centralized", "name": "__init__", "signature": "def __init__(self, l_plus, l_minus, level, *args, **kwargs)" }, { "docstring": "Does the relaxation step several times on the lvl the hardship in this case is to use th...
2
stack_v2_sparse_classes_30k_train_010589
Implement the Python class `SplitSmoother` described below. Class description: A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level. Method signatures and docstrings: - def __init__(self, l_plus, l...
Implement the Python class `SplitSmoother` described below. Class description: A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level. Method signatures and docstrings: - def __init__(self, l_plus, l...
90aed34cf43d633e44f56444f6c5d4fa39619663
<|skeleton|> class SplitSmoother: """A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.""" def __init__(self, l_plus, l_minus, level, *args, **kwargs): """init method of the split...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SplitSmoother: """A general Smoothing class which arises from splitting the main stencil This class of smoothers is easy to derive and really broad, it is statically linked to a certain level.""" def __init__(self, l_plus, l_minus, level, *args, **kwargs): """init method of the split smoother l_p...
the_stack_v2_python_sparse
pypint/plugins/multigrid/multigrid_smoother.py
Parallel-in-Time/PyPinT
train
0
0985bfbd2365501d77a0cd68fa92eb909cedfe54
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.room'.casefold():\n from .room import Ro...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') try: mapping_value = parse_node.get_child_node('@odata.type').get_str_value() except AttributeError: mapping_value = None if mapping_value and mapping_value.casefold() ==...
Place
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Place: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Place: """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: Place""" ...
stack_v2_sparse_classes_75kplus_train_074630
3,774
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: Place", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(parse_n...
3
stack_v2_sparse_classes_30k_train_009632
Implement the Python class `Place` described below. Class description: Implement the Place class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Place: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
Implement the Python class `Place` described below. Class description: Implement the Place class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Place: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Place: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Place: """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: Place""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Place: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Place: """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: Place""" if not pars...
the_stack_v2_python_sparse
msgraph/generated/models/place.py
microsoftgraph/msgraph-sdk-python
train
135
a9eae3a6b0841ad39c5e6ec171b437b7b8ba1f8a
[ "node = data['node']\ncreator = data['creator']\nvalid_node_types = ('Article', 'Review')\nif 'type' not in node.json or node.json['type'] not in valid_node_types:\n raise exceptions.ValidationError(dict(node=f\"Node type must be one of {', '.join(valid_node_types)}.\"))\nproject = node.project\nif not project:\...
<|body_start_0|> node = data['node'] creator = data['creator'] valid_node_types = ('Article', 'Review') if 'type' not in node.json or node.json['type'] not in valid_node_types: raise exceptions.ValidationError(dict(node=f"Node type must be one of {', '.join(valid_node_types)}...
A serializer for DOIs.
DoiSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoiSerializer: """A serializer for DOIs.""" def validate(self, data): """Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissions and the project's account has sufficient quota.""" ...
stack_v2_sparse_classes_75kplus_train_074631
2,035
permissive
[ { "docstring": "Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissions and the project's account has sufficient quota.", "name": "validate", "signature": "def validate(self, data)" }, { "docstr...
2
stack_v2_sparse_classes_30k_test_000332
Implement the Python class `DoiSerializer` described below. Class description: A serializer for DOIs. Method signatures and docstrings: - def validate(self, data): Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissi...
Implement the Python class `DoiSerializer` described below. Class description: A serializer for DOIs. Method signatures and docstrings: - def validate(self, data): Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissi...
b0edf060f4cc5494eef81fce62a563bd5b4e8e31
<|skeleton|> class DoiSerializer: """A serializer for DOIs.""" def validate(self, data): """Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissions and the project's account has sufficient quota.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DoiSerializer: """A serializer for DOIs.""" def validate(self, data): """Validate data before creating a DOI. Validate that the node is a supported type and is linked to a project. Check that the creator has sufficient permissions and the project's account has sufficient quota.""" node = ...
the_stack_v2_python_sparse
manager/dois/api/serializers.py
stencila/hub
train
31
88c2a61fbfb3da88d294081601db0875b7473e46
[ "self.SetTitle('This is an example Dialog')\nself.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)\nreturn True", "if messageId == c4d.DLG_OK:\n print('User Click on Ok')\n return True\nelif messageId == c4d.DLG_CANCEL:\n print('User Click on Cancel')\n self.Close()\n return True\nreturn True" ]
<|body_start_0|> self.SetTitle('This is an example Dialog') self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) return True <|end_body_0|> <|body_start_1|> if messageId == c4d.DLG_OK: print('User Click on Ok') return True elif messageId == c4d.DLG_CANCEL: ...
ExampleDialog
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.""" <|body_0|> def Command(self, messageId, bc): """This Method is called automatically when the user clicks on a gadget and/or chan...
stack_v2_sparse_classes_75kplus_train_074632
3,303
permissive
[ { "docstring": "This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.", "name": "CreateLayout", "signature": "def CreateLayout(self)" }, { "docstring": "This Method is called automatically when the user clicks on a gadget and/or changes its value this func...
2
null
Implement the Python class `ExampleDialog` described below. Class description: Implement the ExampleDialog class. Method signatures and docstrings: - def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog. - def Command(self, messageId, bc): This Method is...
Implement the Python class `ExampleDialog` described below. Class description: Implement the ExampleDialog class. Method signatures and docstrings: - def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog. - def Command(self, messageId, bc): This Method is...
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.""" <|body_0|> def Command(self, messageId, bc): """This Method is called automatically when the user clicks on a gadget and/or chan...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExampleDialog: def CreateLayout(self): """This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.""" self.SetTitle('This is an example Dialog') self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) return True def Command(self, messageId, bc):...
the_stack_v2_python_sparse
plugins/py-commanddata_dialog_r13/py-commanddata_dialog_r13.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
2511485a94b491a6866d7d46d3a113899922744c
[ "GridGlobals.__init__(self)\nLogger.info('Surface: ON')\nself.n = 15\nfor i in range(self.r):\n for j in range(self.c):\n self.arr[i][j] = SurArrs(Globals.get_mat_reten(i, j), Globals.get_mat_inf_index(i, j), Globals.get_mat_hcrit(i, j), Globals.get_mat_aa(i, j), Globals.get_mat_b(i, j))\nStream.__init__(...
<|body_start_0|> GridGlobals.__init__(self) Logger.info('Surface: ON') self.n = 15 for i in range(self.r): for j in range(self.c): self.arr[i][j] = SurArrs(Globals.get_mat_reten(i, j), Globals.get_mat_inf_index(i, j), Globals.get_mat_hcrit(i, j), Globals.get_m...
Contains data and methods to calculate the surface and rill runoff.
Surface
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Surface: """Contains data and methods to calculate the surface and rill runoff.""" def __init__(self): """The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm method.""" <|body_0|> def return_str_vals(self...
stack_v2_sparse_classes_75kplus_train_074633
9,525
no_license
[ { "docstring": "The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm method.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "TODO. :param i: row index :param j: col index :param sep: separator :param dt:...
2
stack_v2_sparse_classes_30k_train_014150
Implement the Python class `Surface` described below. Class description: Contains data and methods to calculate the surface and rill runoff. Method signatures and docstrings: - def __init__(self): The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm me...
Implement the Python class `Surface` described below. Class description: Contains data and methods to calculate the surface and rill runoff. Method signatures and docstrings: - def __init__(self): The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm me...
0dd7a646e3833983d0d6fa9f737adcc8a2c7cec1
<|skeleton|> class Surface: """Contains data and methods to calculate the surface and rill runoff.""" def __init__(self): """The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm method.""" <|body_0|> def return_str_vals(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Surface: """Contains data and methods to calculate the surface and rill runoff.""" def __init__(self): """The constructor Make all numpy arrays and establish the inflow procedure based on D8 or Multi Flow Direction Algorithm method.""" GridGlobals.__init__(self) Logger.info('Surfa...
the_stack_v2_python_sparse
model/smoderp2d/core/surface.py
jerabekjak/smoderp2d-optim-sens
train
1
9a455f034e6782f596cd0ba088aa2aa7f448f04e
[ "sTitle = 'Failure Reason'\nif sMode == WuiFormContentBase.ksMode_Add:\n sTitle = 'Add' + sTitle\nelif sMode == WuiFormContentBase.ksMode_Edit:\n sTitle = 'Edit' + sTitle\nelse:\n assert sMode == WuiFormContentBase.ksMode_Show\nWuiFormContentBase.__init__(self, oFailureReasonData, sMode, 'FailureReason', o...
<|body_start_0|> sTitle = 'Failure Reason' if sMode == WuiFormContentBase.ksMode_Add: sTitle = 'Add' + sTitle elif sMode == WuiFormContentBase.ksMode_Edit: sTitle = 'Edit' + sTitle else: assert sMode == WuiFormContentBase.ksMode_Show WuiFormCon...
WUI Failure Reason HTML content generator.
WuiAdminFailureReason
[ "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-2.0-or-later", "MPL-1.0", "LicenseRef-scancode-generic-exception", "Apache-2.0", "OpenSSL", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WuiAdminFailureReason: """WUI Failure Reason HTML content generator.""" def __init__(self, oFailureReasonData, sMode, oDisp): """Prepare & initialize parent""" <|body_0|> def _populateForm(self, oForm, oData): """Construct an HTML form""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus_train_074634
7,957
permissive
[ { "docstring": "Prepare & initialize parent", "name": "__init__", "signature": "def __init__(self, oFailureReasonData, sMode, oDisp)" }, { "docstring": "Construct an HTML form", "name": "_populateForm", "signature": "def _populateForm(self, oForm, oData)" } ]
2
stack_v2_sparse_classes_30k_val_001108
Implement the Python class `WuiAdminFailureReason` described below. Class description: WUI Failure Reason HTML content generator. Method signatures and docstrings: - def __init__(self, oFailureReasonData, sMode, oDisp): Prepare & initialize parent - def _populateForm(self, oForm, oData): Construct an HTML form
Implement the Python class `WuiAdminFailureReason` described below. Class description: WUI Failure Reason HTML content generator. Method signatures and docstrings: - def __init__(self, oFailureReasonData, sMode, oDisp): Prepare & initialize parent - def _populateForm(self, oForm, oData): Construct an HTML form <|ske...
6f78952d58da52ea4f0e55b2ab297f28e80c1160
<|skeleton|> class WuiAdminFailureReason: """WUI Failure Reason HTML content generator.""" def __init__(self, oFailureReasonData, sMode, oDisp): """Prepare & initialize parent""" <|body_0|> def _populateForm(self, oForm, oData): """Construct an HTML form""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WuiAdminFailureReason: """WUI Failure Reason HTML content generator.""" def __init__(self, oFailureReasonData, sMode, oDisp): """Prepare & initialize parent""" sTitle = 'Failure Reason' if sMode == WuiFormContentBase.ksMode_Add: sTitle = 'Add' + sTitle elif sMo...
the_stack_v2_python_sparse
third_party/virtualbox/src/VBox/ValidationKit/testmanager/webui/wuiadminfailurereason.py
thalium/icebox
train
585
277dd2c2997935969ff24de53b6f84f65d796bd9
[ "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!')" ]
<|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...
Proto file describing the Ad service. Service to manage ads.
AdServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdServiceServicer: """Proto file describing the Ad service. Service to manage ads.""" def GetAd(self, request, context): """Returns the requested ad in full detail.""" <|body_0|> def MutateAds(self, request, context): """Updates ads. Operation statuses are return...
stack_v2_sparse_classes_75kplus_train_074635
2,941
permissive
[ { "docstring": "Returns the requested ad in full detail.", "name": "GetAd", "signature": "def GetAd(self, request, context)" }, { "docstring": "Updates ads. Operation statuses are returned.", "name": "MutateAds", "signature": "def MutateAds(self, request, context)" } ]
2
stack_v2_sparse_classes_30k_train_052640
Implement the Python class `AdServiceServicer` described below. Class description: Proto file describing the Ad service. Service to manage ads. Method signatures and docstrings: - def GetAd(self, request, context): Returns the requested ad in full detail. - def MutateAds(self, request, context): Updates ads. Operatio...
Implement the Python class `AdServiceServicer` described below. Class description: Proto file describing the Ad service. Service to manage ads. Method signatures and docstrings: - def GetAd(self, request, context): Returns the requested ad in full detail. - def MutateAds(self, request, context): Updates ads. Operatio...
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
<|skeleton|> class AdServiceServicer: """Proto file describing the Ad service. Service to manage ads.""" def GetAd(self, request, context): """Returns the requested ad in full detail.""" <|body_0|> def MutateAds(self, request, context): """Updates ads. Operation statuses are return...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdServiceServicer: """Proto file describing the Ad service. Service to manage ads.""" def GetAd(self, request, context): """Returns the requested ad in full detail.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotI...
the_stack_v2_python_sparse
google/ads/google_ads/v3/proto/services/ad_service_pb2_grpc.py
fiboknacky/google-ads-python
train
0
5129f7af8e5c13ef606d107840dfac07714c3bc7
[ "self.best = 0\nvisited = set()\nm, n = (len(grid), len(grid[0]))\n\ndef dfs(i, j, curr):\n visited.add((i, j))\n curr += grid[i][j]\n for di, dj in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\n ii, jj = (i + di, j + dj)\n if ii >= 0 and ii < m and (jj >= 0) and (jj < n) and (grid[ii][jj] > 0) and ((...
<|body_start_0|> self.best = 0 visited = set() m, n = (len(grid), len(grid[0])) def dfs(i, j, curr): visited.add((i, j)) curr += grid[i][j] for di, dj in [[1, 0], [-1, 0], [0, 1], [0, -1]]: ii, jj = (i + di, j + dj) if ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getMaximumGold(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def solve2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.best = 0 visited = set...
stack_v2_sparse_classes_75kplus_train_074636
2,972
no_license
[ { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "getMaximumGold", "signature": "def getMaximumGold(self, grid)" }, { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "solve2", "signature": "def solve2(self, grid)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMaximumGold(self, grid): :type grid: List[List[int]] :rtype: int - def solve2(self, grid): :type grid: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMaximumGold(self, grid): :type grid: List[List[int]] :rtype: int - def solve2(self, grid): :type grid: List[List[int]] :rtype: int <|skeleton|> class Solution: def g...
a5cb862f0c5a3cfd21468141800568c2dedded0a
<|skeleton|> class Solution: def getMaximumGold(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def solve2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getMaximumGold(self, grid): """:type grid: List[List[int]] :rtype: int""" self.best = 0 visited = set() m, n = (len(grid), len(grid[0])) def dfs(i, j, curr): visited.add((i, j)) curr += grid[i][j] for di, dj in [[1, 0],...
the_stack_v2_python_sparse
python/leetcode/dfs/1219_path_max_gold.py
Levintsky/topcoder
train
0
f56805e3c587874938203ecd1151a3e777b151ba
[ "logger.info('Getting Datary members')\nurl = urljoin(self.URL_BASE, 'search/members')\nparams = {'limit': kwargs.get('limit', None), 'hint': kwargs.get('hint', member_name)}\nresponse = self.request(url, 'GET', **{'headers': self.headers, 'params': params})\nmembers_data = response.json() if response else {}\nmemb...
<|body_start_0|> logger.info('Getting Datary members') url = urljoin(self.URL_BASE, 'search/members') params = {'limit': kwargs.get('limit', None), 'hint': kwargs.get('hint', member_name)} response = self.request(url, 'GET', **{'headers': self.headers, 'params': params}) members_...
Datary Members module class
DataryMembers
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataryMembers: """Datary Members module class""" def get_members(self, member_uuid='', member_name='', **kwargs): """============== ============= ==================================== Parameter Type Description ============== ============= ==================================== member_u...
stack_v2_sparse_classes_75kplus_train_074637
3,174
permissive
[ { "docstring": "============== ============= ==================================== Parameter Type Description ============== ============= ==================================== member_uuid str member_uuid uuid member_name str member_name hint str hint to filter name limit int number of results limit (default=20) ...
2
stack_v2_sparse_classes_30k_train_007972
Implement the Python class `DataryMembers` described below. Class description: Datary Members module class Method signatures and docstrings: - def get_members(self, member_uuid='', member_name='', **kwargs): ============== ============= ==================================== Parameter Type Description ============== ==...
Implement the Python class `DataryMembers` described below. Class description: Datary Members module class Method signatures and docstrings: - def get_members(self, member_uuid='', member_name='', **kwargs): ============== ============= ==================================== Parameter Type Description ============== ==...
2790a50e1ad262cbe3210665dc34f497625e923d
<|skeleton|> class DataryMembers: """Datary Members module class""" def get_members(self, member_uuid='', member_name='', **kwargs): """============== ============= ==================================== Parameter Type Description ============== ============= ==================================== member_u...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataryMembers: """Datary Members module class""" def get_members(self, member_uuid='', member_name='', **kwargs): """============== ============= ==================================== Parameter Type Description ============== ============= ==================================== member_uuid str membe...
the_stack_v2_python_sparse
datary/members/members.py
Datary/python-sdk
train
0
46b02a81b9d82f942a988fccb6c9aabc65694f49
[ "filter = {'enable': 0, 'name': data['name'], 'project': data['project']}\ncount = VariableModel.query.filter_by(**filter).count()\nif not count:\n model = VariableModel(**data)\n db.session.add(model)\n db.session.commit()\nreturn count", "model = VariableModel.query.get(data['id'])\nif model is not Non...
<|body_start_0|> filter = {'enable': 0, 'name': data['name'], 'project': data['project']} count = VariableModel.query.filter_by(**filter).count() if not count: model = VariableModel(**data) db.session.add(model) db.session.commit() return count <|end_b...
VariableService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VariableService: def create(self, data): """:param data: :return:""" <|body_0|> def detele(self, data): """:param data: :return:""" <|body_1|> def update(self, data): """# 使用id作为条件,更新数据库重的数据记录。 # 通过id查不到数据时增作为一条新的记录存入。 :param data: :return:""" ...
stack_v2_sparse_classes_75kplus_train_074638
8,621
permissive
[ { "docstring": ":param data: :return:", "name": "create", "signature": "def create(self, data)" }, { "docstring": ":param data: :return:", "name": "detele", "signature": "def detele(self, data)" }, { "docstring": "# 使用id作为条件,更新数据库重的数据记录。 # 通过id查不到数据时增作为一条新的记录存入。 :param data: :ret...
4
stack_v2_sparse_classes_30k_train_004082
Implement the Python class `VariableService` described below. Class description: Implement the VariableService class. Method signatures and docstrings: - def create(self, data): :param data: :return: - def detele(self, data): :param data: :return: - def update(self, data): # 使用id作为条件,更新数据库重的数据记录。 # 通过id查不到数据时增作为一条新的记...
Implement the Python class `VariableService` described below. Class description: Implement the VariableService class. Method signatures and docstrings: - def create(self, data): :param data: :return: - def detele(self, data): :param data: :return: - def update(self, data): # 使用id作为条件,更新数据库重的数据记录。 # 通过id查不到数据时增作为一条新的记...
54dc4000263ab9e8873f0d429a7fe48b11fb727a
<|skeleton|> class VariableService: def create(self, data): """:param data: :return:""" <|body_0|> def detele(self, data): """:param data: :return:""" <|body_1|> def update(self, data): """# 使用id作为条件,更新数据库重的数据记录。 # 通过id查不到数据时增作为一条新的记录存入。 :param data: :return:""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VariableService: def create(self, data): """:param data: :return:""" filter = {'enable': 0, 'name': data['name'], 'project': data['project']} count = VariableModel.query.filter_by(**filter).count() if not count: model = VariableModel(**data) db.session.a...
the_stack_v2_python_sparse
clover/environment/service.py
taoyanli0808/clover
train
18
a5428b1a799611dac61e81dbc7ee2f8a16a80f57
[ "if str2bool(value):\n return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)\nelse:\n return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES)", "if str2bool(value):\n return queryset.filter(Build.OVERDUE_FILTER)\nelse:\n return queryset.exclude(Build.OVERDUE_FILTER)", "value =...
<|body_start_0|> if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) else: return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) <|end_body_0|> <|body_start_1|> if str2bool(value): return queryset.filter(Build.OV...
Custom filterset for BuildList API endpoint.
BuildFilter
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_75kplus_train_074639
20,912
permissive
[ { "docstring": "Filter the queryset to either include or exclude orders which are active.", "name": "filter_active", "signature": "def filter_active(self, queryset, name, value)" }, { "docstring": "Filter the queryset to either include or exclude orders which are overdue.", "name": "filter_o...
5
stack_v2_sparse_classes_30k_test_002230
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)...
the_stack_v2_python_sparse
InvenTree/build/api.py
inventree/InvenTree
train
3,077
2b86ad7377237ff364c0cc9cf19b7013f0ddf576
[ "errors = {}\ninfo = None\ntry:\n info = await _validate_input(self.hass, user_input)\nexcept CannotConnect:\n errors['base'] = 'cannot_connect'\nexcept InvalidAuth:\n errors['base'] = 'invalid_auth'\nexcept Exception:\n LOGGER.exception('Unexpected exception')\n errors['base'] = 'unknown'\nreturn (i...
<|body_start_0|> errors = {} info = None try: info = await _validate_input(self.hass, user_input) except CannotConnect: errors['base'] = 'cannot_connect' except InvalidAuth: errors['base'] = 'invalid_auth' except Exception: ...
Handle a config flow for Shark IQ.
SharkIqConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharkIqConfigFlow: """Handle a config flow for Shark IQ.""" async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]: """Validate form input.""" <|body_0|> async def async_step_user(self, user_input: dict[str, s...
stack_v2_sparse_classes_75kplus_train_074640
3,907
permissive
[ { "docstring": "Validate form input.", "name": "_async_validate_input", "signature": "async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]" }, { "docstring": "Handle the initial step.", "name": "async_step_user", "signature"...
3
stack_v2_sparse_classes_30k_train_039535
Implement the Python class `SharkIqConfigFlow` described below. Class description: Handle a config flow for Shark IQ. Method signatures and docstrings: - async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]: Validate form input. - async def async_step_us...
Implement the Python class `SharkIqConfigFlow` described below. Class description: Handle a config flow for Shark IQ. Method signatures and docstrings: - async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]: Validate form input. - async def async_step_us...
bfa315be51371a1b63e04342a0b275a57ae148bd
<|skeleton|> class SharkIqConfigFlow: """Handle a config flow for Shark IQ.""" async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]: """Validate form input.""" <|body_0|> async def async_step_user(self, user_input: dict[str, s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SharkIqConfigFlow: """Handle a config flow for Shark IQ.""" async def _async_validate_input(self, user_input: Mapping[str, Any]) -> tuple[dict[str, str] | None, dict[str, str]]: """Validate form input.""" errors = {} info = None try: info = await _validate_inpu...
the_stack_v2_python_sparse
homeassistant/components/sharkiq/config_flow.py
bdraco/home-assistant
train
13
35134a0b7f7b9fa786f613844caaffa15f45440d
[ "storage = get_storage()\noutages = storage.read_report_outages(str(report_id))\nreturn jsonify(ReportOutageSchema(many=True).dump(outages))", "body = request.get_json()\ntry:\n outage_object = OutagePostSchema().load(body)\nexcept ValidationError as err:\n raise BadAPIRequest(err.messages)\nif outage_objec...
<|body_start_0|> storage = get_storage() outages = storage.read_report_outages(str(report_id)) return jsonify(ReportOutageSchema(many=True).dump(outages)) <|end_body_0|> <|body_start_1|> body = request.get_json() try: outage_object = OutagePostSchema().load(body) ...
ReportOutageView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportOutageView: def get(self, report_id): """--- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content: application/json: schema: $ref: '#/components/schemas/ReportOutageSchema' 401: $ref: '#/components/resp...
stack_v2_sparse_classes_75kplus_train_074641
15,383
permissive
[ { "docstring": "--- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content: application/json: schema: $ref: '#/components/schemas/ReportOutageSchema' 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/respon...
2
null
Implement the Python class `ReportOutageView` described below. Class description: Implement the ReportOutageView class. Method signatures and docstrings: - def get(self, report_id): --- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content...
Implement the Python class `ReportOutageView` described below. Class description: Implement the ReportOutageView class. Method signatures and docstrings: - def get(self, report_id): --- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content...
280800c73eb7cfd49029462b352887e78f1ff91b
<|skeleton|> class ReportOutageView: def get(self, report_id): """--- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content: application/json: schema: $ref: '#/components/schemas/ReportOutageSchema' 401: $ref: '#/components/resp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReportOutageView: def get(self, report_id): """--- summary: Get report outage data. tags: - Reports parameters: - report_id responses: 200: description: Successfully retrieved content: application/json: schema: $ref: '#/components/schemas/ReportOutageSchema' 401: $ref: '#/components/responses/401-Unau...
the_stack_v2_python_sparse
sfa_api/reports.py
SolarArbiter/solarforecastarbiter-api
train
9
760b969fe36b47e6d3ed46d2248849b5cf74baaf
[ "with sqlite3.connect('example.db') as conn:\n c = conn.cursor()\n try:\n c.execute('create table stocks\\n (date text, trans text, symbol text, qty real, price real)')\n except sqlite3.OperationalError:\n pass\n timestamp = time()\n date = datetime.fromtimestamp(timestamp).str...
<|body_start_0|> with sqlite3.connect('example.db') as conn: c = conn.cursor() try: c.execute('create table stocks\n (date text, trans text, symbol text, qty real, price real)') except sqlite3.OperationalError: pass timesta...
A simplified class to buy stock in Amazon
Amazon
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s...
stack_v2_sparse_classes_75kplus_train_074642
2,429
no_license
[ { "docstring": "Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were purchased", "name": "buy_amazon", "signature": "def buy_amazon(self, quantity, purchase_price)" },...
4
stack_v2_sparse_classes_30k_train_005683
Implement the Python class `Amazon` described below. Class description: A simplified class to buy stock in Amazon Method signatures and docstrings: - def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p...
Implement the Python class `Amazon` described below. Class description: A simplified class to buy stock in Amazon Method signatures and docstrings: - def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p...
fb2d1a903fd287e0dbc963963f322eccdc1546bb
<|skeleton|> class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Amazon: """A simplified class to buy stock in Amazon""" def buy_amazon(self, quantity, purchase_price): """Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were pu...
the_stack_v2_python_sparse
NSS/practice/python_and_sql/amazon.py
megducharme/Python_Exercises
train
0
fbff203e89c00707a55d7a3e9c31efc42194a2e9
[ "mocker.patch.object(Display, 'start', retuen_value=None)\nmocker.patch.object(webdriver, 'Chrome', side_effect=self.MockChrome)\nmocker.patch.object(webdriver, 'ChromeOptions', side_effect=self.MockChromeOptions)\ndriver = init_driver(include_url=include_url)\nassert ('--headless' in driver.options) != include_url...
<|body_start_0|> mocker.patch.object(Display, 'start', retuen_value=None) mocker.patch.object(webdriver, 'Chrome', side_effect=self.MockChrome) mocker.patch.object(webdriver, 'ChromeOptions', side_effect=self.MockChromeOptions) driver = init_driver(include_url=include_url) assert...
TestRasterizeIncludeUrl
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRasterizeIncludeUrl: def test_headless_chrome_option(self, mocker, include_url): """Given: - A parameter that mention whether to include the URL bar in the screenshot. When: - Running the 'rasterize' function. Then: - Verify that it runs as expected.""" <|body_0|> def te...
stack_v2_sparse_classes_75kplus_train_074643
13,311
permissive
[ { "docstring": "Given: - A parameter that mention whether to include the URL bar in the screenshot. When: - Running the 'rasterize' function. Then: - Verify that it runs as expected.", "name": "test_headless_chrome_option", "signature": "def test_headless_chrome_option(self, mocker, include_url)" }, ...
2
stack_v2_sparse_classes_30k_train_029038
Implement the Python class `TestRasterizeIncludeUrl` described below. Class description: Implement the TestRasterizeIncludeUrl class. Method signatures and docstrings: - def test_headless_chrome_option(self, mocker, include_url): Given: - A parameter that mention whether to include the URL bar in the screenshot. When...
Implement the Python class `TestRasterizeIncludeUrl` described below. Class description: Implement the TestRasterizeIncludeUrl class. Method signatures and docstrings: - def test_headless_chrome_option(self, mocker, include_url): Given: - A parameter that mention whether to include the URL bar in the screenshot. When...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestRasterizeIncludeUrl: def test_headless_chrome_option(self, mocker, include_url): """Given: - A parameter that mention whether to include the URL bar in the screenshot. When: - Running the 'rasterize' function. Then: - Verify that it runs as expected.""" <|body_0|> def te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestRasterizeIncludeUrl: def test_headless_chrome_option(self, mocker, include_url): """Given: - A parameter that mention whether to include the URL bar in the screenshot. When: - Running the 'rasterize' function. Then: - Verify that it runs as expected.""" mocker.patch.object(Display, 'start'...
the_stack_v2_python_sparse
Packs/rasterize/Integrations/rasterize/rasterize_test.py
demisto/content
train
1,023
529500ebaa23b4e2bb0464f784198acbf60b74e6
[ "if from_unicode:\n table = str.maketrans(cls.ALLOWED_CHARACTERS, cls.TRANSLATED_CHARACTERS)\nelse:\n table = str.maketrans(cls.TRANSLATED_CHARACTERS, cls.ALLOWED_CHARACTERS)\nreturn name.translate(table)", "argument = '-'.join(argument.split())\nif not 2 <= len(argument) <= 96:\n raise BadArgument('Chan...
<|body_start_0|> if from_unicode: table = str.maketrans(cls.ALLOWED_CHARACTERS, cls.TRANSLATED_CHARACTERS) else: table = str.maketrans(cls.TRANSLATED_CHARACTERS, cls.ALLOWED_CHARACTERS) return name.translate(table) <|end_body_0|> <|body_start_1|> argument = '-'.j...
A converter that ensures an added off-topic name is valid.
OffTopicName
[ "MIT", "BSD-3-Clause", "Python-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OffTopicName: """A converter that ensures an added off-topic name is valid.""" def translate_name(cls, name: str, *, from_unicode: bool=True) -> str: """Translates `name` into a format that is allowed in discord channel names. If `from_unicode` is True, the name is translated from a ...
stack_v2_sparse_classes_75kplus_train_074644
19,551
permissive
[ { "docstring": "Translates `name` into a format that is allowed in discord channel names. If `from_unicode` is True, the name is translated from a discord-safe format, back to normalized text.", "name": "translate_name", "signature": "def translate_name(cls, name: str, *, from_unicode: bool=True) -> str...
2
null
Implement the Python class `OffTopicName` described below. Class description: A converter that ensures an added off-topic name is valid. Method signatures and docstrings: - def translate_name(cls, name: str, *, from_unicode: bool=True) -> str: Translates `name` into a format that is allowed in discord channel names. ...
Implement the Python class `OffTopicName` described below. Class description: A converter that ensures an added off-topic name is valid. Method signatures and docstrings: - def translate_name(cls, name: str, *, from_unicode: bool=True) -> str: Translates `name` into a format that is allowed in discord channel names. ...
f2048684291cc6358565e96ef3562512fbeb2505
<|skeleton|> class OffTopicName: """A converter that ensures an added off-topic name is valid.""" def translate_name(cls, name: str, *, from_unicode: bool=True) -> str: """Translates `name` into a format that is allowed in discord channel names. If `from_unicode` is True, the name is translated from a ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OffTopicName: """A converter that ensures an added off-topic name is valid.""" def translate_name(cls, name: str, *, from_unicode: bool=True) -> str: """Translates `name` into a format that is allowed in discord channel names. If `from_unicode` is True, the name is translated from a discord-safe ...
the_stack_v2_python_sparse
bot/converters.py
python-discord/bot
train
1,479
b3b2488d4f3f93176b87d8bb9e5a89c801738696
[ "if self.comment:\n return '{} reported a comment.'.format(self.reporter.profile.screen_name())\nelse:\n return '{} reported a subject entitled \"{}\" posted by \"{}\".'.format(self.reporter.profile.screen_name(), self.subject, self.subject.author)", "if boards_slug:\n reports = Report.objects.filter(act...
<|body_start_0|> if self.comment: return '{} reported a comment.'.format(self.reporter.profile.screen_name()) else: return '{} reported a subject entitled "{}" posted by "{}".'.format(self.reporter.profile.screen_name(), self.subject, self.subject.author) <|end_body_0|> <|body_s...
Model that represents a report.
Report
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Report: """Model that represents a report.""" def __str__(self): """Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at the time of report creation.""" <|body_0|> de...
stack_v2_sparse_classes_75kplus_train_074645
2,055
permissive
[ { "docstring": "Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at the time of report creation.", "name": "__str__", "signature": "def __str__(self)" }, { "docstring": "Returns a list of re...
2
stack_v2_sparse_classes_30k_test_001439
Implement the Python class `Report` described below. Class description: Model that represents a report. Method signatures and docstrings: - def __str__(self): Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at t...
Implement the Python class `Report` described below. Class description: Model that represents a report. Method signatures and docstrings: - def __str__(self): Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at t...
753ec3b5a38f4f5d15bd451400b0374f7ffcdfa6
<|skeleton|> class Report: """Model that represents a report.""" def __str__(self): """Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at the time of report creation.""" <|body_0|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Report: """Model that represents a report.""" def __str__(self): """Unicode representation for a report model based on report type check. P.S: This model needs to have a CharField with choices [REPORT_TYPES] to be selected at the time of report creation.""" if self.comment: re...
the_stack_v2_python_sparse
reports/models.py
bangrobe/elmer
train
0
188a339b9f054563058781511166e34648cc4dd2
[ "def max_depth(self, root):\n if not root:\n return 0\n l_d = self.max_depth(root.left)\n r_d = self.max_depth(root.right)\n if l_d == -1 or r_d == -1 or abs(l_d - r_d) >= 2:\n return -1\n return (l_d if l_d > r_d else r_d) + 1\nreturn self.max_depth(root) != -1", "self.c = True\n\nde...
<|body_start_0|> def max_depth(self, root): if not root: return 0 l_d = self.max_depth(root.left) r_d = self.max_depth(root.right) if l_d == -1 or r_d == -1 or abs(l_d - r_d) >= 2: return -1 return (l_d if l_d > r_d else...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isBalanced(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isBalancedEasy(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> def max_depth(self, root): if n...
stack_v2_sparse_classes_75kplus_train_074646
1,231
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isBalanced", "signature": "def isBalanced(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isBalancedEasy", "signature": "def isBalancedEasy(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_014293
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isBalanced(self, root): :type root: TreeNode :rtype: bool - def isBalancedEasy(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isBalanced(self, root): :type root: TreeNode :rtype: bool - def isBalancedEasy(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class Solution: def isBalance...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def isBalanced(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isBalancedEasy(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isBalanced(self, root): """:type root: TreeNode :rtype: bool""" def max_depth(self, root): if not root: return 0 l_d = self.max_depth(root.left) r_d = self.max_depth(root.right) if l_d == -1 or r_d == -1 or abs(l_d -...
the_stack_v2_python_sparse
cs_notes/tree/recursive/balanced_binary_tree.py
hwc1824/LeetCodeSolution
train
0
b2f0f1994b67e2fa43f1ceaea58a66aed4775d50
[ "result = ''\nfor i in range(len(self.table)):\n e = self.table[i]\n if not e == None:\n result += str(i) + ': '\n result += e.EntryToStr() + '\\n'\nreturn result", "hashval = 0\nfor letter in name:\n hashval += ord(letter) - ord('a')\nhallnum = hashval % len(self.table)\nreturn hallnum", ...
<|body_start_0|> result = '' for i in range(len(self.table)): e = self.table[i] if not e == None: result += str(i) + ': ' result += e.EntryToStr() + '\n' return result <|end_body_0|> <|body_start_1|> hashval = 0 for letter ...
The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the number of elements in occupying the hashtable
HashTable
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HashTable: """The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the number of elements in occupying the ha...
stack_v2_sparse_classes_75kplus_train_074647
4,321
permissive
[ { "docstring": "HashTableToStr: HashTable -> String", "name": "HashTableToStr", "signature": "def HashTableToStr(self)" }, { "docstring": "hash_function: K NatNum -> NatNum Compute a hash of the val string that is in [0 ... n).", "name": "hash_function", "signature": "def hash_function(s...
6
null
Implement the Python class `HashTable` described below. Class description: The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the...
Implement the Python class `HashTable` described below. Class description: The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the...
fdf458c3f066509a7786eba0cc1896c720facf8b
<|skeleton|> class HashTable: """The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the number of elements in occupying the ha...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HashTable: """The HashTable data structure contains a collection of values where each value is located by a hashable key. No two values may have the same key, but more than one key may have the same value. table is the list holding the hash table size is the number of elements in occupying the hashtable""" ...
the_stack_v2_python_sparse
Computer Science 1/Labs/lab9/hashtable.py
pab3507/RIT
train
0
af910c21e747ee2cd5297bab45d2fdc2de4348a5
[ "tensor_data = np.random.rand(4, 2).astype(np.float16)\nwith Graph('test_graph', 'Reference') as test_graph:\n input_tensor = Tensor(tensor_data=tensor_data)\n act = input_data(input_tensor, 'input')\ngraph_proto, tensor_data_array = test_graph.to_proto()\nnode = get_node_proto(graph_proto, 'input')\nself.ass...
<|body_start_0|> tensor_data = np.random.rand(4, 2).astype(np.float16) with Graph('test_graph', 'Reference') as test_graph: input_tensor = Tensor(tensor_data=tensor_data) act = input_data(input_tensor, 'input') graph_proto, tensor_data_array = test_graph.to_proto() ...
FP16Test
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FP16Test: def test_fp16_even(self): """Test float16 packing when tensor's last dimension is of even size""" <|body_0|> def test_fp16_odd(self): """Test float16 packing when tensor's last dimension is of odd size""" <|body_1|> def test_fp16_odd_odd(self):...
stack_v2_sparse_classes_75kplus_train_074648
6,830
permissive
[ { "docstring": "Test float16 packing when tensor's last dimension is of even size", "name": "test_fp16_even", "signature": "def test_fp16_even(self)" }, { "docstring": "Test float16 packing when tensor's last dimension is of odd size", "name": "test_fp16_odd", "signature": "def test_fp16...
3
stack_v2_sparse_classes_30k_train_047453
Implement the Python class `FP16Test` described below. Class description: Implement the FP16Test class. Method signatures and docstrings: - def test_fp16_even(self): Test float16 packing when tensor's last dimension is of even size - def test_fp16_odd(self): Test float16 packing when tensor's last dimension is of odd...
Implement the Python class `FP16Test` described below. Class description: Implement the FP16Test class. Method signatures and docstrings: - def test_fp16_even(self): Test float16 packing when tensor's last dimension is of even size - def test_fp16_odd(self): Test float16 packing when tensor's last dimension is of odd...
01ef7892bb25cb08c13cea6125efc1528a8de260
<|skeleton|> class FP16Test: def test_fp16_even(self): """Test float16 packing when tensor's last dimension is of even size""" <|body_0|> def test_fp16_odd(self): """Test float16 packing when tensor's last dimension is of odd size""" <|body_1|> def test_fp16_odd_odd(self):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FP16Test: def test_fp16_even(self): """Test float16 packing when tensor's last dimension is of even size""" tensor_data = np.random.rand(4, 2).astype(np.float16) with Graph('test_graph', 'Reference') as test_graph: input_tensor = Tensor(tensor_data=tensor_data) ...
the_stack_v2_python_sparse
smaug/python/tensor_test.py
mrbeann/smaug
train
0
753eefe82065abea9c232797c7265e06b6527696
[ "self.dropout_rate = dropout_rate\nself.num_layers = num_layers\nself.lengths = lengths\nif embedded_chars is not None:\n self.embedding_dims = embedded_chars.shape[-1].value\nself.is_training = is_training\nself.rnn_size = rnn_size", "with tf.variable_scope('rnn_layer'):\n cell_fw = [get_rnn_cell(self.rnn_...
<|body_start_0|> self.dropout_rate = dropout_rate self.num_layers = num_layers self.lengths = lengths if embedded_chars is not None: self.embedding_dims = embedded_chars.shape[-1].value self.is_training = is_training self.rnn_size = rnn_size <|end_body_0|> <|...
BLSTM
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BLSTM: def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None): """BLSTM网络""" <|body_0|> def blstm_layer(self, input): """:return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_75kplus_train_074649
2,643
no_license
[ { "docstring": "BLSTM网络", "name": "__init__", "signature": "def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None)" }, { "docstring": ":return:", "name": "blstm_layer", "signature": "def blstm_layer(self, input)" } ]
2
stack_v2_sparse_classes_30k_test_000950
Implement the Python class `BLSTM` described below. Class description: Implement the BLSTM class. Method signatures and docstrings: - def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None): BLSTM网络 - def blstm_layer(self, input): :return:
Implement the Python class `BLSTM` described below. Class description: Implement the BLSTM class. Method signatures and docstrings: - def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None): BLSTM网络 - def blstm_layer(self, input): :return: <|skeleton...
ad6b3299ebbe32837f3d6e20c2c9190d6a8c934a
<|skeleton|> class BLSTM: def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None): """BLSTM网络""" <|body_0|> def blstm_layer(self, input): """:return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BLSTM: def __init__(self, embedded_chars=None, rnn_size=None, num_layers=None, dropout_rate=None, lengths=None, is_training=None): """BLSTM网络""" self.dropout_rate = dropout_rate self.num_layers = num_layers self.lengths = lengths if embedded_chars is not None: ...
the_stack_v2_python_sparse
models/layers/lstm_layers.py
qiufengyuyi/sequence_tagging
train
444
eb2daeed6c976b9c8d840e001297060c3de78b48
[ "timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)", "query_hash = hash(query)\nevent_data = IOSKikMessageEventData()\nevent_data.body = self._GetRowValue(query_hash, row, 'ZBODY')\nevent_data.displayname...
<|body_start_0|> timestamp = self._GetRowValue(query_hash, row, value_name) if timestamp is None: return None return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp) <|end_body_0|> <|body_start_1|> query_hash = hash(query) event_data = IOSKikMessageEventData() ...
SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite
IOSKikPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IOSKikPlugin: """SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): h...
stack_v2_sparse_classes_75kplus_train_074650
7,030
permissive
[ { "docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.", "name...
2
null
Implement the Python class `IOSKikPlugin` described below. Class description: SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a da...
Implement the Python class `IOSKikPlugin` described below. Class description: SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a da...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class IOSKikPlugin: """SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): h...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IOSKikPlugin: """SQLite parser plugin for iOS Kik messenger database files. The OS Kik messenger database file is typically stored in: kik.sqlite""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the qu...
the_stack_v2_python_sparse
plaso/parsers/sqlite_plugins/ios_kik.py
log2timeline/plaso
train
1,506
68a1369ce6e0c512ef47948f8fb1704befa16506
[ "from shap import TreeExplainer\nself.model = model\nself.feature_names = feature_names\nself.feature_types = feature_types\nself.feature_names_in_ = None\nself.feature_types_in_ = None\nif data is not None:\n data, n_samples = preclean_X(data, feature_names, feature_types)\n data, self.feature_names_in_, sel...
<|body_start_0|> from shap import TreeExplainer self.model = model self.feature_names = feature_names self.feature_types = feature_types self.feature_names_in_ = None self.feature_types_in_ = None if data is not None: data, n_samples = preclean_X(data,...
Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap
ShapTree
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShapTree: """Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap""" def __init__(self, model, data, feature_names=None, feature_types=None, **kwargs): """Initializes cl...
stack_v2_sparse_classes_75kplus_train_074651
2,765
permissive
[ { "docstring": "Initializes class. Args: model: A tree object that works with Tree SHAP. data: Data used to initialize SHAP with. feature_names: List of feature names. feature_types: List of feature types. **kwargs: Kwargs that will be sent to shap.TreeExplainer", "name": "__init__", "signature": "def _...
2
stack_v2_sparse_classes_30k_train_008330
Implement the Python class `ShapTree` described below. Class description: Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap Method signatures and docstrings: - def __init__(self, model, data, feature_...
Implement the Python class `ShapTree` described below. Class description: Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap Method signatures and docstrings: - def __init__(self, model, data, feature_...
e6f38ea195aecbbd9d28c7183a83c65ada16e1ae
<|skeleton|> class ShapTree: """Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap""" def __init__(self, model, data, feature_names=None, feature_types=None, **kwargs): """Initializes cl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ShapTree: """Exposes tree specific SHAP approximation, in interpret API form. If using this please cite the original authors as can be found here: https://github.com/slundberg/shap""" def __init__(self, model, data, feature_names=None, feature_types=None, **kwargs): """Initializes class. Args: mo...
the_stack_v2_python_sparse
python/interpret-core/interpret/greybox/_shaptree.py
interpretml/interpret
train
3,731
90425e2dbd2b60857448beaf3e25a0ebedece362
[ "reply = self.send('home')\nself.poll_until_idle()\nreturn reply", "reply = self.send('move abs {0:d}'.format(position))\nif blocking:\n self.poll_until_idle()\nreturn reply", "reply = self.send('move rel {0:d}'.format(distance))\nif blocking:\n self.poll_until_idle()\nreturn reply", "reply = self.send(...
<|body_start_0|> reply = self.send('home') self.poll_until_idle() return reply <|end_body_0|> <|body_start_1|> reply = self.send('move abs {0:d}'.format(position)) if blocking: self.poll_until_idle() return reply <|end_body_1|> <|body_start_2|> reply...
Provides mixin giving ability to move device, axis or lockstep.
AsciiMovementMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsciiMovementMixin: """Provides mixin giving ability to move device, axis or lockstep.""" def home(self): """Sends the "home" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply received was not sent by the expected device or axis. Returns...
stack_v2_sparse_classes_75kplus_train_074652
4,039
no_license
[ { "docstring": "Sends the \"home\" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply received was not sent by the expected device or axis. Returns: An AsciiReply containing the first reply received.", "name": "home", "signature": "def home(self)" }, { ...
5
stack_v2_sparse_classes_30k_train_014896
Implement the Python class `AsciiMovementMixin` described below. Class description: Provides mixin giving ability to move device, axis or lockstep. Method signatures and docstrings: - def home(self): Sends the "home" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply rece...
Implement the Python class `AsciiMovementMixin` described below. Class description: Provides mixin giving ability to move device, axis or lockstep. Method signatures and docstrings: - def home(self): Sends the "home" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply rece...
560367ddb85f72f0de458ee39d66ecbe8de1e1e7
<|skeleton|> class AsciiMovementMixin: """Provides mixin giving ability to move device, axis or lockstep.""" def home(self): """Sends the "home" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply received was not sent by the expected device or axis. Returns...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AsciiMovementMixin: """Provides mixin giving ability to move device, axis or lockstep.""" def home(self): """Sends the "home" command, then polls the device or axis until it is idle. Raises: UnexpectedReplyError: The reply received was not sent by the expected device or axis. Returns: An AsciiRep...
the_stack_v2_python_sparse
__v1/zaber/serial/asciimovementmixin.py
howwallace/howw-stage-controls
train
0
2bf9f4f5ff93083a043872b4d83613e29206eb38
[ "app_list = super().get_app_list(request)\nfor app in app_list:\n app['models'].sort(key=lambda m: model_order[m['name']])\nreturn app_list", "app_dict = self._build_app_dict(request, app_label)\nif not app_dict:\n raise Http404('The requested admin page does not exist.')\napp_dict['models'].sort(key=lambda...
<|body_start_0|> app_list = super().get_app_list(request) for app in app_list: app['models'].sort(key=lambda m: model_order[m['name']]) return app_list <|end_body_0|> <|body_start_1|> app_dict = self._build_app_dict(request, app_label) if not app_dict: ra...
A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically.
AppAdminSite
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppAdminSite: """A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically.""" def get_app_list(self, request): """Return a sorted list of all the installed apps that have been registered in this site, with custom ordering.""" ...
stack_v2_sparse_classes_75kplus_train_074653
3,472
permissive
[ { "docstring": "Return a sorted list of all the installed apps that have been registered in this site, with custom ordering.", "name": "get_app_list", "signature": "def get_app_list(self, request)" }, { "docstring": "Overwrites the default AdminSite behaviour to use custom ordering with the mode...
2
null
Implement the Python class `AppAdminSite` described below. Class description: A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically. Method signatures and docstrings: - def get_app_list(self, request): Return a sorted list of all the installed apps that have been...
Implement the Python class `AppAdminSite` described below. Class description: A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically. Method signatures and docstrings: - def get_app_list(self, request): Return a sorted list of all the installed apps that have been...
802a28b3a4ce33754b8a986f6d2eb616aad017d4
<|skeleton|> class AppAdminSite: """A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically.""" def get_app_list(self, request): """Return a sorted list of all the installed apps that have been registered in this site, with custom ordering.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AppAdminSite: """A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically.""" def get_app_list(self, request): """Return a sorted list of all the installed apps that have been registered in this site, with custom ordering.""" app_list = ...
the_stack_v2_python_sparse
packages/django-backend/app/admin.py
ZechyW/cs-toolkit
train
1
ae99ad175c99f95fdb10c9342cb983b20ff621f9
[ "if not events:\n events = {}\nself.subscriptions = {}\nself.subscription_count = 0\nfor event_name in events.keys():\n self.subscribe(event_name, events.get(event_name))", "self.subscription_count += 1\nif not self.subscriptions.get(event_name):\n self.subscriptions[event_name] = {}\nself.subscriptions[...
<|body_start_0|> if not events: events = {} self.subscriptions = {} self.subscription_count = 0 for event_name in events.keys(): self.subscribe(event_name, events.get(event_name)) <|end_body_0|> <|body_start_1|> self.subscription_count += 1 if not...
EventProvider
EventProvider
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventProvider: """EventProvider""" def __init__(self, events=None): """:param events: (dict.<str, callable>) An object with event name keys and callback function values, optional""" <|body_0|> def subscribe(self, event_name, callback_func): """Subscribe to events...
stack_v2_sparse_classes_75kplus_train_074654
2,752
permissive
[ { "docstring": ":param events: (dict.<str, callable>) An object with event name keys and callback function values, optional", "name": "__init__", "signature": "def __init__(self, events=None)" }, { "docstring": "Subscribe to events :param event_name: (str) Event name, required :param callback_fu...
4
stack_v2_sparse_classes_30k_val_000412
Implement the Python class `EventProvider` described below. Class description: EventProvider Method signatures and docstrings: - def __init__(self, events=None): :param events: (dict.<str, callable>) An object with event name keys and callback function values, optional - def subscribe(self, event_name, callback_func)...
Implement the Python class `EventProvider` described below. Class description: EventProvider Method signatures and docstrings: - def __init__(self, events=None): :param events: (dict.<str, callable>) An object with event name keys and callback function values, optional - def subscribe(self, event_name, callback_func)...
f3e9b1bb6c8e1984e3d758ab1fe1a71225ade13e
<|skeleton|> class EventProvider: """EventProvider""" def __init__(self, events=None): """:param events: (dict.<str, callable>) An object with event name keys and callback function values, optional""" <|body_0|> def subscribe(self, event_name, callback_func): """Subscribe to events...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventProvider: """EventProvider""" def __init__(self, events=None): """:param events: (dict.<str, callable>) An object with event name keys and callback function values, optional""" if not events: events = {} self.subscriptions = {} self.subscription_count = 0 ...
the_stack_v2_python_sparse
target_tools/event_provider.py
5amfung/target-python-sdk
train
0
c512fea2319e3bb9f5a3963ac9424e8dd08e50ba
[ "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...
AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.
AccountGrantsServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountGrantsServicer: """AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.""" def Create(self, request, context): """Create registers a new AccountGrant.""" <|body_0|> def Get(self, request, context): ...
stack_v2_sparse_classes_75kplus_train_074655
7,980
permissive
[ { "docstring": "Create registers a new AccountGrant.", "name": "Create", "signature": "def Create(self, request, context)" }, { "docstring": "Get reads one AccountGrant by ID.", "name": "Get", "signature": "def Get(self, request, context)" }, { "docstring": "Delete removes a Acco...
4
stack_v2_sparse_classes_30k_train_016614
Implement the Python class `AccountGrantsServicer` described below. Class description: AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource. Method signatures and docstrings: - def Create(self, request, context): Create registers a new AccountGrant. - d...
Implement the Python class `AccountGrantsServicer` described below. Class description: AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource. Method signatures and docstrings: - def Create(self, request, context): Create registers a new AccountGrant. - d...
1f3a53ef8c404e64d9324f9fd13f5c39c71eaca5
<|skeleton|> class AccountGrantsServicer: """AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.""" def Create(self, request, context): """Create registers a new AccountGrant.""" <|body_0|> def Get(self, request, context): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccountGrantsServicer: """AccountGrants assign a resource directly to an account, giving the account the permission to connect to that resource.""" def Create(self, request, context): """Create registers a new AccountGrant.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) contex...
the_stack_v2_python_sparse
strongdm/account_grants_pb2_grpc.py
strongdm/strongdm-sdk-python
train
9
c045c01f855321240ac01a0ec8a6421caf0a0035
[ "super(EncodingLayer, self).__init__()\nif first:\n features_out = features_in\n features_in = 1\nelse:\n features_in = features_in\n features_out = 2 * features_in\nself.basic = BasicBlock(features_in, features_out)\nself.pooling = pooling", "if self.pooling is not None:\n x = self.pooling(x)\nout...
<|body_start_0|> super(EncodingLayer, self).__init__() if first: features_out = features_in features_in = 1 else: features_in = features_in features_out = 2 * features_in self.basic = BasicBlock(features_in, features_out) self.pooli...
Definition of encoding layer in FusionNet architecture.
EncodingLayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncodingLayer: """Definition of encoding layer in FusionNet architecture.""" def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None): """Initialisation. Args: features_in: Number of input feature channels. first: Whether this is the first encoding layer. pool...
stack_v2_sparse_classes_75kplus_train_074656
8,294
permissive
[ { "docstring": "Initialisation. Args: features_in: Number of input feature channels. first: Whether this is the first encoding layer. pooling: (Optional) max pooling layer.", "name": "__init__", "signature": "def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None)" }, { ...
2
stack_v2_sparse_classes_30k_train_006868
Implement the Python class `EncodingLayer` described below. Class description: Definition of encoding layer in FusionNet architecture. Method signatures and docstrings: - def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None): Initialisation. Args: features_in: Number of input feature channe...
Implement the Python class `EncodingLayer` described below. Class description: Definition of encoding layer in FusionNet architecture. Method signatures and docstrings: - def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None): Initialisation. Args: features_in: Number of input feature channe...
fc0db7ca69d4149c736b8d0923272f14fb5693fe
<|skeleton|> class EncodingLayer: """Definition of encoding layer in FusionNet architecture.""" def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None): """Initialisation. Args: features_in: Number of input feature channels. first: Whether this is the first encoding layer. pool...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EncodingLayer: """Definition of encoding layer in FusionNet architecture.""" def __init__(self, features_in: int, first: bool=False, pooling: nn.Module=None): """Initialisation. Args: features_in: Number of input feature channels. first: Whether this is the first encoding layer. pooling: (Optiona...
the_stack_v2_python_sparse
models/fusionnet.py
charleshouston/unet-pytorch
train
2
3d60b1e2bb7a94bdc268eb7268657a3716a05f9f
[ "Parametre.__init__(self, 'supprimer', 'del')\nself.schema = '<texte_libre>'\nself.aide_courte = 'supprime une ou plusieurs routes'\nself.aide_longue = \"Cette commande permet de supprimer une ou plusieurs routes. La syntaxe pour supprimer une route est de préciser sa salle d'origine et de destination, comme %route...
<|body_start_0|> Parametre.__init__(self, 'supprimer', 'del') self.schema = '<texte_libre>' self.aide_courte = 'supprime une ou plusieurs routes' self.aide_longue = "Cette commande permet de supprimer une ou plusieurs routes. La syntaxe pour supprimer une route est de préciser sa salle d...
Commande 'route supprimer'
PrmSupprimer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmSupprimer: """Commande 'route supprimer'""" def __init__(self): """Constructeur du paramètre.""" <|body_0|> def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_074657
3,607
permissive
[ { "docstring": "Constructeur du paramètre.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Méthode d'interprétation de commande", "name": "interpreter", "signature": "def interpreter(self, personnage, dic_masques)" } ]
2
stack_v2_sparse_classes_30k_train_034782
Implement the Python class `PrmSupprimer` described below. Class description: Commande 'route supprimer' Method signatures and docstrings: - def __init__(self): Constructeur du paramètre. - def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
Implement the Python class `PrmSupprimer` described below. Class description: Commande 'route supprimer' Method signatures and docstrings: - def __init__(self): Constructeur du paramètre. - def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande <|skeleton|> class PrmSupprimer: """Co...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmSupprimer: """Commande 'route supprimer'""" def __init__(self): """Constructeur du paramètre.""" <|body_0|> def interpreter(self, personnage, dic_masques): """Méthode d'interprétation de commande""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PrmSupprimer: """Commande 'route supprimer'""" def __init__(self): """Constructeur du paramètre.""" Parametre.__init__(self, 'supprimer', 'del') self.schema = '<texte_libre>' self.aide_courte = 'supprime une ou plusieurs routes' self.aide_longue = "Cette commande p...
the_stack_v2_python_sparse
src/secondaires/route/commandes/route/supprimer.py
vincent-lg/tsunami
train
5
3979e02579609ca834bdde7ff64ba4cae70ffdc0
[ "super().__init__()\nself.in_chans_x = in_chans_x\nself.in_chans_g = in_chans_g\nself.out_chans = out_chans\nself.W_x = nn.Sequential(nn.Conv2d(self.in_chans_x, out_chans, kernel_size=2, padding=0, stride=2, bias=False))\nself.W_g = nn.Sequential(nn.Conv2d(self.in_chans_g, out_chans, kernel_size=1, padding=0, bias=...
<|body_start_0|> super().__init__() self.in_chans_x = in_chans_x self.in_chans_g = in_chans_g self.out_chans = out_chans self.W_x = nn.Sequential(nn.Conv2d(self.in_chans_x, out_chans, kernel_size=2, padding=0, stride=2, bias=False)) self.W_g = nn.Sequential(nn.Conv2d(self...
A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout.
AttentionGate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentionGate: """A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout.""" def __init__(self, in_chans_x: int, in_chans_g: int, out_chans: int): """Parameters ---------- in_chans_x : int Number of inp...
stack_v2_sparse_classes_75kplus_train_074658
6,188
permissive
[ { "docstring": "Parameters ---------- in_chans_x : int Number of input channels of the input tensor `x`. in_chans_g : int Number of input channels of the input tensor `g`. out_chans : int Number of output channels.", "name": "__init__", "signature": "def __init__(self, in_chans_x: int, in_chans_g: int, ...
2
stack_v2_sparse_classes_30k_train_022838
Implement the Python class `AttentionGate` described below. Class description: A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout. Method signatures and docstrings: - def __init__(self, in_chans_x: int, in_chans_g: int, out_chans: i...
Implement the Python class `AttentionGate` described below. Class description: A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout. Method signatures and docstrings: - def __init__(self, in_chans_x: int, in_chans_g: int, out_chans: i...
6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066
<|skeleton|> class AttentionGate: """A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout.""" def __init__(self, in_chans_x: int, in_chans_g: int, out_chans: int): """Parameters ---------- in_chans_x : int Number of inp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AttentionGate: """A Convolutional Block that consists of two convolution layers each followed by instance normalization, LeakyReLU, activation and dropout.""" def __init__(self, in_chans_x: int, in_chans_g: int, out_chans: int): """Parameters ---------- in_chans_x : int Number of input channels o...
the_stack_v2_python_sparse
mridc/collections/segmentation/models/attention_unet_base/attention_unet_block.py
wdika/mridc
train
40
359dce2dc2a424056a9dedcfdc7643319dd07957
[ "super().__init__()\nself.input_mean = torch.Tensor([0.3521554, 0.30068502, 0.28527516])\nself.input_std = torch.Tensor([0.18182722, 0.18656468, 0.15938024])\nc = 3\nself.use_skip = use_skip\nself.n_conv = len(layers)\nskip_layer_size = [3] + layers[:-1]\nfor i, l in enumerate(layers):\n self.add_module('conv%d'...
<|body_start_0|> super().__init__() self.input_mean = torch.Tensor([0.3521554, 0.30068502, 0.28527516]) self.input_std = torch.Tensor([0.18182722, 0.18656468, 0.15938024]) c = 3 self.use_skip = use_skip self.n_conv = len(layers) skip_layer_size = [3] + layers[:-1]...
Detector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Detector: def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True): """Your code here. Setup your detection network""" <|body_0|> def forward(self, x): """Your code here. Implement a forward pass through the network, use forward...
stack_v2_sparse_classes_75kplus_train_074659
7,454
no_license
[ { "docstring": "Your code here. Setup your detection network", "name": "__init__", "signature": "def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True)" }, { "docstring": "Your code here. Implement a forward pass through the network, use forward for train...
3
stack_v2_sparse_classes_30k_train_002068
Implement the Python class `Detector` described below. Class description: Implement the Detector class. Method signatures and docstrings: - def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True): Your code here. Setup your detection network - def forward(self, x): Your code he...
Implement the Python class `Detector` described below. Class description: Implement the Detector class. Method signatures and docstrings: - def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True): Your code here. Setup your detection network - def forward(self, x): Your code he...
4483422fa668e8fb29858ed09431f3d9404303f8
<|skeleton|> class Detector: def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True): """Your code here. Setup your detection network""" <|body_0|> def forward(self, x): """Your code here. Implement a forward pass through the network, use forward...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Detector: def __init__(self, layers=[16, 32, 64, 128], n_output_channels=3, kernel_size=3, use_skip=True): """Your code here. Setup your detection network""" super().__init__() self.input_mean = torch.Tensor([0.3521554, 0.30068502, 0.28527516]) self.input_std = torch.Tensor([0....
the_stack_v2_python_sparse
homework_4/models.py
lyxmegan/Deep_Learning_Projects
train
1
437135c9f7cbbd59d03d39f8684de6ff0f36bafa
[ "if Solution.ALGO == 0:\n return self.longestValidParenthesesStack(s)\nreturn self.longestValidParenthesesDp(s)", "n = len(s)\nif n == 0:\n return 0\nstack = []\nlongest = 0\ni = 0\nfor j in xrange(n):\n if s[j] == '(':\n stack.append(j)\n elif len(stack) == 0:\n i = j + 1\n else:\n ...
<|body_start_0|> if Solution.ALGO == 0: return self.longestValidParenthesesStack(s) return self.longestValidParenthesesDp(s) <|end_body_0|> <|body_start_1|> n = len(s) if n == 0: return 0 stack = [] longest = 0 i = 0 for j in xrang...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParentheses(self, s): """Returns the length of the longest valid parenthesis string in s.""" <|body_0|> def longestValidParenthesesStack(self, s): """Returns the length of the longest valid parenthesis string in s. This a O(n) time and space...
stack_v2_sparse_classes_75kplus_train_074660
3,015
permissive
[ { "docstring": "Returns the length of the longest valid parenthesis string in s.", "name": "longestValidParentheses", "signature": "def longestValidParentheses(self, s)" }, { "docstring": "Returns the length of the longest valid parenthesis string in s. This a O(n) time and space algorithm that ...
3
stack_v2_sparse_classes_30k_train_042437
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): Returns the length of the longest valid parenthesis string in s. - def longestValidParenthesesStack(self, s): Returns the length of the long...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): Returns the length of the longest valid parenthesis string in s. - def longestValidParenthesesStack(self, s): Returns the length of the long...
0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859
<|skeleton|> class Solution: def longestValidParentheses(self, s): """Returns the length of the longest valid parenthesis string in s.""" <|body_0|> def longestValidParenthesesStack(self, s): """Returns the length of the longest valid parenthesis string in s. This a O(n) time and space...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def longestValidParentheses(self, s): """Returns the length of the longest valid parenthesis string in s.""" if Solution.ALGO == 0: return self.longestValidParenthesesStack(s) return self.longestValidParenthesesDp(s) def longestValidParenthesesStack(self, s):...
the_stack_v2_python_sparse
leetcode/algorithms/longest-valid-parenthesis/solution.py
i7sharath/algorithms-1
train
0
800e556eac6165aa814f0ed3e300451e5aeae838
[ "nastran_filename1 = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending.bdf')\nskin_filename = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending_skin.bdf')\nlog = get_logger(level='warning')\nwrite_skin_solid_faces(nastran_filename1, skin_filename, write_solids=True, write_shells=True, size=8, is_d...
<|body_start_0|> nastran_filename1 = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending.bdf') skin_filename = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending_skin.bdf') log = get_logger(level='warning') write_skin_solid_faces(nastran_filename1, skin_filename, write_sol...
defines UGRID tests
TestUgridGui
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestUgridGui: """defines UGRID tests""" def test_ugrid_gui_01(self): """tests solid_bending.bdf""" <|body_0|> def test_ugrid_gui_02(self): """tests plate_with_circular_hole""" <|body_1|> def test_ugrid2d_gui(self): """simple UGRID2D model""" ...
stack_v2_sparse_classes_75kplus_train_074661
4,389
no_license
[ { "docstring": "tests solid_bending.bdf", "name": "test_ugrid_gui_01", "signature": "def test_ugrid_gui_01(self)" }, { "docstring": "tests plate_with_circular_hole", "name": "test_ugrid_gui_02", "signature": "def test_ugrid_gui_02(self)" }, { "docstring": "simple UGRID2D model", ...
4
stack_v2_sparse_classes_30k_train_031186
Implement the Python class `TestUgridGui` described below. Class description: defines UGRID tests Method signatures and docstrings: - def test_ugrid_gui_01(self): tests solid_bending.bdf - def test_ugrid_gui_02(self): tests plate_with_circular_hole - def test_ugrid2d_gui(self): simple UGRID2D model - def test_ugrid3d...
Implement the Python class `TestUgridGui` described below. Class description: defines UGRID tests Method signatures and docstrings: - def test_ugrid_gui_01(self): tests solid_bending.bdf - def test_ugrid_gui_02(self): tests plate_with_circular_hole - def test_ugrid2d_gui(self): simple UGRID2D model - def test_ugrid3d...
d9ffdb4ac845b13bcf6aea96ff5d37cc026c5267
<|skeleton|> class TestUgridGui: """defines UGRID tests""" def test_ugrid_gui_01(self): """tests solid_bending.bdf""" <|body_0|> def test_ugrid_gui_02(self): """tests plate_with_circular_hole""" <|body_1|> def test_ugrid2d_gui(self): """simple UGRID2D model""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestUgridGui: """defines UGRID tests""" def test_ugrid_gui_01(self): """tests solid_bending.bdf""" nastran_filename1 = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending.bdf') skin_filename = os.path.join(NASTRAN_PATH, 'solid_bending', 'solid_bending_skin.bdf') log...
the_stack_v2_python_sparse
pyNastran/converters/aflr/ugrid/test_ugrid_gui.py
ratalex/pyNastran
train
0
6f577324a94c6e2a4e08df062d3dd9d01aa40184
[ "json_parser = RequestParser()\njson_parser.add_argument('name', required=True, location='json')\njson_parser.add_argument('is_visible', type=inputs.int_range(0, 1), required=True, location='json')\njson_parser.add_argument('sequence', type=inputs.positive, location='json')\nargs = json_parser.parse_args()\nchannel...
<|body_start_0|> json_parser = RequestParser() json_parser.add_argument('name', required=True, location='json') json_parser.add_argument('is_visible', type=inputs.int_range(0, 1), required=True, location='json') json_parser.add_argument('sequence', type=inputs.positive, location='json') ...
频道
ChannelResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChannelResource: """频道""" def put(self, target): """修改频道""" <|body_0|> def delete(self, target): """删除频道""" <|body_1|> <|end_skeleton|> <|body_start_0|> json_parser = RequestParser() json_parser.add_argument('name', required=True, locati...
stack_v2_sparse_classes_75kplus_train_074662
5,465
no_license
[ { "docstring": "修改频道", "name": "put", "signature": "def put(self, target)" }, { "docstring": "删除频道", "name": "delete", "signature": "def delete(self, target)" } ]
2
stack_v2_sparse_classes_30k_train_046955
Implement the Python class `ChannelResource` described below. Class description: 频道 Method signatures and docstrings: - def put(self, target): 修改频道 - def delete(self, target): 删除频道
Implement the Python class `ChannelResource` described below. Class description: 频道 Method signatures and docstrings: - def put(self, target): 修改频道 - def delete(self, target): 删除频道 <|skeleton|> class ChannelResource: """频道""" def put(self, target): """修改频道""" <|body_0|> def delete(self,...
c9703a9c57a98babf8d1e41b227aada9ef4bfe15
<|skeleton|> class ChannelResource: """频道""" def put(self, target): """修改频道""" <|body_0|> def delete(self, target): """删除频道""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChannelResource: """频道""" def put(self, target): """修改频道""" json_parser = RequestParser() json_parser.add_argument('name', required=True, location='json') json_parser.add_argument('is_visible', type=inputs.int_range(0, 1), required=True, location='json') json_parse...
the_stack_v2_python_sparse
mis/resources/information/channel.py
Yaooooooooooooo/toutiao-backend
train
0
1d707fd88968151a86066f92d8b5699b574442aa
[ "name = validated_data.get('name')\ncodename = validated_data.get('codename')\ncontent_type_data = validated_data.get('content_type')\ncontent_type = ContentType.objects.get(app_label=content_type_data['app_label'], model=content_type_data['model'])\nreturn Permission.objects.create(name=name, content_type=content_...
<|body_start_0|> name = validated_data.get('name') codename = validated_data.get('codename') content_type_data = validated_data.get('content_type') content_type = ContentType.objects.get(app_label=content_type_data['app_label'], model=content_type_data['model']) return Permission...
A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update
PermissionSerializer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PermissionSerializer: """A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update""" def create(self, validated_data): """Create and save a permission into the database.""" <|body_0|> def update...
stack_v2_sparse_classes_75kplus_train_074663
8,394
permissive
[ { "docstring": "Create and save a permission into the database.", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Update a permission into the database.", "name": "update", "signature": "def update(self, instance, validated_data)" } ]
2
stack_v2_sparse_classes_30k_train_001947
Implement the Python class `PermissionSerializer` described below. Class description: A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update Method signatures and docstrings: - def create(self, validated_data): Create and save a permission...
Implement the Python class `PermissionSerializer` described below. Class description: A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update Method signatures and docstrings: - def create(self, validated_data): Create and save a permission...
56511ebac83a5dc1fb8768a98bc675e88530a447
<|skeleton|> class PermissionSerializer: """A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update""" def create(self, validated_data): """Create and save a permission into the database.""" <|body_0|> def update...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PermissionSerializer: """A serializer to handle our permission system. Heritates from serializers.HyperlinkedModelSerializer and overrides : - create - update""" def create(self, validated_data): """Create and save a permission into the database.""" name = validated_data.get('name') ...
the_stack_v2_python_sparse
usersmanagement/serializers.py
Open-CMMS/openCMMS_backend
train
4
6b5a715832ae65b524ac08fb04e52e62d9ab9e24
[ "super().__init__()\nself.h_dim = h_dim\nself.lQ = nn.Linear(e_dim, h_dim)\nself.lK = nn.Linear(e_dim, h_dim)\nself.lV = nn.Linear(e_dim, h_dim)", "if querys is not None:\n Q = self.lQ(querys)\nelse:\n Q = self.lQ(seq_inputs)\nK = self.lK(seq_inputs)\nV = self.lV(seq_inputs)\nQK = torch.matmul(Q, K.permute(...
<|body_start_0|> super().__init__() self.h_dim = h_dim self.lQ = nn.Linear(e_dim, h_dim) self.lK = nn.Linear(e_dim, h_dim) self.lV = nn.Linear(e_dim, h_dim) <|end_body_0|> <|body_start_1|> if querys is not None: Q = self.lQ(querys) else: Q...
OneHeadAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OneHeadAttention: def __init__(self, e_dim, h_dim): """:param e_dim: 输入向量维度 :param h_dim: 输出向量维度""" <|body_0|> def forward(self, seq_inputs, querys=None, mask=None): """:param seq_inputs: #[ batch, seq_lens, e_dim ] :param querys: #[ batch, seq_lens, e_dim ] :param m...
stack_v2_sparse_classes_75kplus_train_074664
10,000
no_license
[ { "docstring": ":param e_dim: 输入向量维度 :param h_dim: 输出向量维度", "name": "__init__", "signature": "def __init__(self, e_dim, h_dim)" }, { "docstring": ":param seq_inputs: #[ batch, seq_lens, e_dim ] :param querys: #[ batch, seq_lens, e_dim ] :param mask: #[ 1, seq_lens, seq_lens ] :return:", "nam...
2
stack_v2_sparse_classes_30k_train_017275
Implement the Python class `OneHeadAttention` described below. Class description: Implement the OneHeadAttention class. Method signatures and docstrings: - def __init__(self, e_dim, h_dim): :param e_dim: 输入向量维度 :param h_dim: 输出向量维度 - def forward(self, seq_inputs, querys=None, mask=None): :param seq_inputs: #[ batch, ...
Implement the Python class `OneHeadAttention` described below. Class description: Implement the OneHeadAttention class. Method signatures and docstrings: - def __init__(self, e_dim, h_dim): :param e_dim: 输入向量维度 :param h_dim: 输出向量维度 - def forward(self, seq_inputs, querys=None, mask=None): :param seq_inputs: #[ batch, ...
c7bef7c5ca6e755d0714a688e0c36f35146c8a10
<|skeleton|> class OneHeadAttention: def __init__(self, e_dim, h_dim): """:param e_dim: 输入向量维度 :param h_dim: 输出向量维度""" <|body_0|> def forward(self, seq_inputs, querys=None, mask=None): """:param seq_inputs: #[ batch, seq_lens, e_dim ] :param querys: #[ batch, seq_lens, e_dim ] :param m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OneHeadAttention: def __init__(self, e_dim, h_dim): """:param e_dim: 输入向量维度 :param h_dim: 输出向量维度""" super().__init__() self.h_dim = h_dim self.lQ = nn.Linear(e_dim, h_dim) self.lK = nn.Linear(e_dim, h_dim) self.lV = nn.Linear(e_dim, h_dim) def forward(self,...
the_stack_v2_python_sparse
chapter3/s49_transformer.py
chenrj23/recbyhand
train
0
c2120e99d8e48acc06345d196a2f6c2dc039a59c
[ "super().__init__()\nself._layers = nn.ModuleList()\nfor in_w, out_w in zip([M] + hidden_size[:-1], hidden_size):\n layer = nn.Sequential(nn.Linear(in_w, out_w), g)\n self._layers.append(layer)\nlayer = nn.Sequential(nn.Linear(hidden_size[-1], 1), nn.Sigmoid())\nself._layers.append(layer)", "d_theta = X\nfo...
<|body_start_0|> super().__init__() self._layers = nn.ModuleList() for in_w, out_w in zip([M] + hidden_size[:-1], hidden_size): layer = nn.Sequential(nn.Linear(in_w, out_w), g) self._layers.append(layer) layer = nn.Sequential(nn.Linear(hidden_size[-1], 1), nn.Sigm...
MalGAN discriminator (substitute detector). Simple feed forward network.
Discriminator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Discriminator: """MalGAN discriminator (substitute detector). Simple feed forward network.""" def __init__(self, M: int, hidden_size: List[int], g: nn.Module): """Discriminator Constructor Builds the discriminator block. :param M: Width of the malware feature vector :param hidden_siz...
stack_v2_sparse_classes_75kplus_train_074665
1,425
permissive
[ { "docstring": "Discriminator Constructor Builds the discriminator block. :param M: Width of the malware feature vector :param hidden_size: Width of the hidden layer(s). :param g: Activation function", "name": "__init__", "signature": "def __init__(self, M: int, hidden_size: List[int], g: nn.Module)" ...
2
stack_v2_sparse_classes_30k_train_003379
Implement the Python class `Discriminator` described below. Class description: MalGAN discriminator (substitute detector). Simple feed forward network. Method signatures and docstrings: - def __init__(self, M: int, hidden_size: List[int], g: nn.Module): Discriminator Constructor Builds the discriminator block. :param...
Implement the Python class `Discriminator` described below. Class description: MalGAN discriminator (substitute detector). Simple feed forward network. Method signatures and docstrings: - def __init__(self, M: int, hidden_size: List[int], g: nn.Module): Discriminator Constructor Builds the discriminator block. :param...
c36647d1b3ba86a9a4e6e1a0bda2a371d8875781
<|skeleton|> class Discriminator: """MalGAN discriminator (substitute detector). Simple feed forward network.""" def __init__(self, M: int, hidden_size: List[int], g: nn.Module): """Discriminator Constructor Builds the discriminator block. :param M: Width of the malware feature vector :param hidden_siz...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Discriminator: """MalGAN discriminator (substitute detector). Simple feed forward network.""" def __init__(self, M: int, hidden_size: List[int], g: nn.Module): """Discriminator Constructor Builds the discriminator block. :param M: Width of the malware feature vector :param hidden_size: Width of t...
the_stack_v2_python_sparse
malgan/discriminator.py
CyberForce/Pesidious
train
119
c8c853392ee573013a8b6c0d0da6c010fde2b69b
[ "if 'git_uri' not in self.user_params:\n raise ValueError(f'{self.__class__.__name__} instance has no source (no git_uri in user params)')\nreturn source.GitSource(provider='git', uri=self.user_params['git_uri'], provider_params={'git_commit': self.user_params.get('git_ref'), 'git_commit_depth': self.user_params...
<|body_start_0|> if 'git_uri' not in self.user_params: raise ValueError(f'{self.__class__.__name__} instance has no source (no git_uri in user params)') return source.GitSource(provider='git', uri=self.user_params['git_uri'], provider_params={'git_commit': self.user_params.get('git_ref'), 'g...
Task parameters (coming from CLI arguments).
TaskParams
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskParams: """Task parameters (coming from CLI arguments).""" def source(self) -> source.Source: """Source for the input files the task will operate on (e.g. a git repo).""" <|body_0|> def from_cli_args(cls, args: dict): """Create a TaskParams instance from CLI ...
stack_v2_sparse_classes_75kplus_train_074666
4,580
permissive
[ { "docstring": "Source for the input files the task will operate on (e.g. a git repo).", "name": "source", "signature": "def source(self) -> source.Source" }, { "docstring": "Create a TaskParams instance from CLI arguments.", "name": "from_cli_args", "signature": "def from_cli_args(cls, ...
2
stack_v2_sparse_classes_30k_train_014408
Implement the Python class `TaskParams` described below. Class description: Task parameters (coming from CLI arguments). Method signatures and docstrings: - def source(self) -> source.Source: Source for the input files the task will operate on (e.g. a git repo). - def from_cli_args(cls, args: dict): Create a TaskPara...
Implement the Python class `TaskParams` described below. Class description: Task parameters (coming from CLI arguments). Method signatures and docstrings: - def source(self) -> source.Source: Source for the input files the task will operate on (e.g. a git repo). - def from_cli_args(cls, args: dict): Create a TaskPara...
0ed6e07d848db7090332a18ef8ace3585dd314ac
<|skeleton|> class TaskParams: """Task parameters (coming from CLI arguments).""" def source(self) -> source.Source: """Source for the input files the task will operate on (e.g. a git repo).""" <|body_0|> def from_cli_args(cls, args: dict): """Create a TaskParams instance from CLI ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskParams: """Task parameters (coming from CLI arguments).""" def source(self) -> source.Source: """Source for the input files the task will operate on (e.g. a git repo).""" if 'git_uri' not in self.user_params: raise ValueError(f'{self.__class__.__name__} instance has no sou...
the_stack_v2_python_sparse
atomic_reactor/tasks/common.py
fr34k8/atomic-reactor
train
1
ef695b9614f0863793acb548a2cfa85e79a6c865
[ "Algorithm.__init__(self)\nself.name = 'Edge attribute filter'\nself.parent = 'Graph filtering'\nself.attribute = DropDown('Attribute', {'width', 'length'})\nself.drop_downs.append(self.attribute)\nself.attribute_threshold_value = FloatSlider('Attribute treshold', 0.0, 20.0, 0.1, 10.0)\nself.float_sliders.append(se...
<|body_start_0|> Algorithm.__init__(self) self.name = 'Edge attribute filter' self.parent = 'Graph filtering' self.attribute = DropDown('Attribute', {'width', 'length'}) self.drop_downs.append(self.attribute) self.attribute_threshold_value = FloatSlider('Attribute treshol...
Edge attribute filter algorithm implementation
AlgBody
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlgBody: """Edge attribute filter algorithm implementation""" def __init__(self): """Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attrib...
stack_v2_sparse_classes_75kplus_train_074667
3,328
permissive
[ { "docstring": "Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attribute_threshold_value* : A threshold value for the given attribute | *operator* : A logical python ...
2
stack_v2_sparse_classes_30k_train_022871
Implement the Python class `AlgBody` described below. Class description: Edge attribute filter algorithm implementation Method signatures and docstrings: - def __init__(self): Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute*...
Implement the Python class `AlgBody` described below. Class description: Edge attribute filter algorithm implementation Method signatures and docstrings: - def __init__(self): Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute*...
0dc9becc09da22af3edac90b81b1dd9b1f44fd5b
<|skeleton|> class AlgBody: """Edge attribute filter algorithm implementation""" def __init__(self): """Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attrib...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlgBody: """Edge attribute filter algorithm implementation""" def __init__(self): """Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attribute_threshold...
the_stack_v2_python_sparse
nefi2/model/algorithms/edge_attribute_filter.py
andreasfirczynski/NetworkExtractionFromImages
train
0
2419187dafbed75331e4d65d60f87d3c8d36386c
[ "QWidget.__init__(self, flags=Qt.Widget)\nself.te_1 = QTextEdit()\nself.te_2 = QTextEdit()\nself.te_3 = QTextEdit()\nself.split_1 = QSplitter()\nself.split_2 = QSplitter()\nself.vbox = QVBoxLayout()\nself.container_vbox = QVBoxLayout()\nself.init_widget()", "self.setWindowTitle('Hello World')\nself.split_1.addWid...
<|body_start_0|> QWidget.__init__(self, flags=Qt.Widget) self.te_1 = QTextEdit() self.te_2 = QTextEdit() self.te_3 = QTextEdit() self.split_1 = QSplitter() self.split_2 = QSplitter() self.vbox = QVBoxLayout() self.container_vbox = QVBoxLayout() sel...
만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.
Form
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Form: """만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.""" def __init__(self): """보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.""" <|body_0|> def init_widget(self): """현재 위젯의 모양등을 초기화""" ...
stack_v2_sparse_classes_75kplus_train_074668
1,815
no_license
[ { "docstring": "보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "현재 위젯의 모양등을 초기화", "name": "init_widget", "signature": "def init_widget(self)" } ]
2
stack_v2_sparse_classes_30k_train_032853
Implement the Python class `Form` described below. Class description: 만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성. Method signatures and docstrings: - def __init__(self): 보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다. - def init_widget(self): 현재 위젯의...
Implement the Python class `Form` described below. Class description: 만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성. Method signatures and docstrings: - def __init__(self): 보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다. - def init_widget(self): 현재 위젯의...
559ad5618eb99368b4da140cb78609bce2d5da71
<|skeleton|> class Form: """만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.""" def __init__(self): """보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.""" <|body_0|> def init_widget(self): """현재 위젯의 모양등을 초기화""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Form: """만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.""" def __init__(self): """보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.""" QWidget.__init__(self, flags=Qt.Widget) self.te_1 = QTextEdit() self.te_2 ...
the_stack_v2_python_sparse
Python/pyqt5/OpenTutorials_PyQt/QtFramework/QtWidgets/QSplitter/QSplitter_00_basic.py
ghdic/marinelifeirony
train
6
3da519b8b6f3d0773c0fb4307b146b6316b2b83a
[ "self.config = None\nself.desc = None\nself.sites = None", "errors = {}\nif user_input is not None:\n try:\n self.config = {CONF_HOST: user_input[CONF_HOST], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_PORT: user_input.get(CONF_PORT), CONF_VERIFY_SSL: user_in...
<|body_start_0|> self.config = None self.desc = None self.sites = None <|end_body_0|> <|body_start_1|> errors = {} if user_input is not None: try: self.config = {CONF_HOST: user_input[CONF_HOST], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD...
Handle a UniFi config flow.
UnifiFlowHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnifiFlowHandler: """Handle a UniFi config flow.""" def __init__(self): """Initialize the UniFi flow.""" <|body_0|> async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" <|body_1|> async def async_step_site(se...
stack_v2_sparse_classes_75kplus_train_074669
4,827
permissive
[ { "docstring": "Initialize the UniFi flow.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Handle a flow initialized by the user.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input=None)" }, { "docstring": "Select site...
4
null
Implement the Python class `UnifiFlowHandler` described below. Class description: Handle a UniFi config flow. Method signatures and docstrings: - def __init__(self): Initialize the UniFi flow. - async def async_step_user(self, user_input=None): Handle a flow initialized by the user. - async def async_step_site(self, ...
Implement the Python class `UnifiFlowHandler` described below. Class description: Handle a UniFi config flow. Method signatures and docstrings: - def __init__(self): Initialize the UniFi flow. - async def async_step_user(self, user_input=None): Handle a flow initialized by the user. - async def async_step_site(self, ...
ade847f243ab120d14b9e99c7f8e114c3bd27280
<|skeleton|> class UnifiFlowHandler: """Handle a UniFi config flow.""" def __init__(self): """Initialize the UniFi flow.""" <|body_0|> async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" <|body_1|> async def async_step_site(se...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UnifiFlowHandler: """Handle a UniFi config flow.""" def __init__(self): """Initialize the UniFi flow.""" self.config = None self.desc = None self.sites = None async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" ...
the_stack_v2_python_sparse
homeassistant/components/unifi/config_flow.py
koenvanderlinden/home-assistant
train
2
1f264addd8dce1ffefa0c251d36e0791e1ef2ba9
[ "self.acl = acl\nself.bucket_policy = bucket_policy\nself.efficient_mpu_enabled = efficient_mpu_enabled\nself.enable_obj_store_access = enable_obj_store_access\nself.init_cluster_id = init_cluster_id\nself.init_cluster_incarnation_id = init_cluster_incarnation_id\nself.lifecycle_config = lifecycle_config\nself.obje...
<|body_start_0|> self.acl = acl self.bucket_policy = bucket_policy self.efficient_mpu_enabled = efficient_mpu_enabled self.enable_obj_store_access = enable_obj_store_access self.init_cluster_id = init_cluster_id self.init_cluster_incarnation_id = init_cluster_incarnation_...
Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool representing whether this mpu structure is based on S3 MPU 2.0 enable_obj_store_access (bool): ...
S3BucketConfigProto
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class S3BucketConfigProto: """Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool representing whether this mpu structure is based...
stack_v2_sparse_classes_75kplus_train_074670
9,657
permissive
[ { "docstring": "Constructor for the S3BucketConfigProto class", "name": "__init__", "signature": "def __init__(self, acl=None, bucket_policy=None, efficient_mpu_enabled=None, enable_obj_store_access=None, init_cluster_id=None, init_cluster_incarnation_id=None, lifecycle_config=None, object_tags_added=No...
2
stack_v2_sparse_classes_30k_train_017038
Implement the Python class `S3BucketConfigProto` described below. Class description: Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool represent...
Implement the Python class `S3BucketConfigProto` described below. Class description: Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool represent...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class S3BucketConfigProto: """Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool representing whether this mpu structure is based...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class S3BucketConfigProto: """Implementation of the 'S3BucketConfigProto' model. TODO: type description here. Attributes: acl (ACLProto): ACL of the bucket. bucket_policy (BucketPolicy): Policy in effect for the bucket. efficient_mpu_enabled (bool): bool representing whether this mpu structure is based on S3 MPU 2....
the_stack_v2_python_sparse
cohesity_management_sdk/models/s3_bucket_config_proto.py
cohesity/management-sdk-python
train
24
c40e16655b08bf2e20ebb11a73c69fe676d3d908
[ "intensities = cls(intensities)\nintensities[Features.TARGET] = targets\nif distances:\n intensities[Features.DISTANCE] = distances\nif passes_threshold:\n intensities[Features.PASSES_THRESHOLDS] = passes_threshold\nif rounds_used:\n intensities['rounds_used'] = rounds_used\nreturn intensities", "df = se...
<|body_start_0|> intensities = cls(intensities) intensities[Features.TARGET] = targets if distances: intensities[Features.DISTANCE] = distances if passes_threshold: intensities[Features.PASSES_THRESHOLDS] = passes_threshold if rounds_used: inte...
DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of a set of features in each :code:`(round, channel)` tile in which the feature is identifi...
DecodedIntensityTable
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecodedIntensityTable: """DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of a set of features in each :code:`(round...
stack_v2_sparse_classes_75kplus_train_074671
7,761
permissive
[ { "docstring": "Assign target values to intensities. Parameters ---------- intensities : IntensityTable intensity_table to assign target values to targets : Tuple[str, np.ndarray] Target values to assign distances : Optional[Tuple[str, np.ndarray]] Corresponding array of distances from target for each feature p...
4
stack_v2_sparse_classes_30k_train_018964
Implement the Python class `DecodedIntensityTable` described below. Class description: DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of ...
Implement the Python class `DecodedIntensityTable` described below. Class description: DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of ...
853f56c7c02b15397adb921db5e3bde02fdadb63
<|skeleton|> class DecodedIntensityTable: """DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of a set of features in each :code:`(round...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DecodedIntensityTable: """DecodedIntensityTable is a container for spot or pixel features extracted from image data that have been decoded. It is the primary output from starfish :py:class:`Decode` methods. An IntensityTable records the numeric intensity of a set of features in each :code:`(round, channel)` t...
the_stack_v2_python_sparse
starfish/core/intensity_table/decoded_intensity_table.py
spacetx/starfish
train
211
dd28f16740bfda2e2604876bc1ecb820a9fe167b
[ "self.config = None\nself._com_ports_list = None\nself._default_com_port = None", "errors = {}\nif self._com_ports_list is None:\n result = await self.hass.async_add_executor_job(scan_comports)\n self._com_ports_list, self._default_com_port = result\n if self._default_com_port is None:\n return se...
<|body_start_0|> self.config = None self._com_ports_list = None self._default_com_port = None <|end_body_0|> <|body_start_1|> errors = {} if self._com_ports_list is None: result = await self.hass.async_add_executor_job(scan_comports) self._com_ports_list,...
Handle a config flow for Aurora ABB PowerOne.
AuroraABBConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuroraABBConfigFlow: """Handle a config flow for Aurora ABB PowerOne.""" def __init__(self): """Initialise the config flow.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle a flow initialised by the us...
stack_v2_sparse_classes_75kplus_train_074672
4,922
permissive
[ { "docstring": "Initialise the config flow.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Handle a flow initialised by the user.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult" ...
2
stack_v2_sparse_classes_30k_train_036342
Implement the Python class `AuroraABBConfigFlow` described below. Class description: Handle a config flow for Aurora ABB PowerOne. Method signatures and docstrings: - def __init__(self): Initialise the config flow. - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle a flow ...
Implement the Python class `AuroraABBConfigFlow` described below. Class description: Handle a config flow for Aurora ABB PowerOne. Method signatures and docstrings: - def __init__(self): Initialise the config flow. - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle a flow ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class AuroraABBConfigFlow: """Handle a config flow for Aurora ABB PowerOne.""" def __init__(self): """Initialise the config flow.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle a flow initialised by the us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuroraABBConfigFlow: """Handle a config flow for Aurora ABB PowerOne.""" def __init__(self): """Initialise the config flow.""" self.config = None self._com_ports_list = None self._default_com_port = None async def async_step_user(self, user_input: dict[str, Any] | Non...
the_stack_v2_python_sparse
homeassistant/components/aurora_abb_powerone/config_flow.py
home-assistant/core
train
35,501
e9a018622cf412ef3042d590934af774655a5060
[ "course_id = course_id_from_url(request.META.get('HTTP_REFERER'))\nif course_id:\n try:\n get_course_overview_with_access(request.user, 'load', course_id)\n return redirect(f'/courses/{str(course_id)}/wiki/{wiki_path}')\n except Http404:\n pass", "if not view_func.__module__.startswith(...
<|body_start_0|> course_id = course_id_from_url(request.META.get('HTTP_REFERER')) if course_id: try: get_course_overview_with_access(request.user, 'load', course_id) return redirect(f'/courses/{str(course_id)}/wiki/{wiki_path}') except Http404: ...
This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced with a wrapper function around the wiki views. This is currently difficult or impossibl...
WikiAccessMiddleware
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WikiAccessMiddleware: """This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced with a wrapper function around the wiki...
stack_v2_sparse_classes_75kplus_train_074673
5,446
permissive
[ { "docstring": "redirect to course wiki url if the referrer is from a course page", "name": "_redirect_from_referrer", "signature": "def _redirect_from_referrer(self, request, wiki_path)" }, { "docstring": "This function handles authentication logic for wiki urls and redirects from the \"root wi...
3
stack_v2_sparse_classes_30k_train_000371
Implement the Python class `WikiAccessMiddleware` described below. Class description: This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced ...
Implement the Python class `WikiAccessMiddleware` described below. Class description: This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced ...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class WikiAccessMiddleware: """This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced with a wrapper function around the wiki...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WikiAccessMiddleware: """This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. TODO: removing the "root wiki" would obviate the need for this middleware; it could be replaced with a wrapper function around the wiki views. This ...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/course_wiki/middleware.py
luque/better-ways-of-thinking-about-software
train
3
399094d90aed7a1109c9de4ae18e367dd0711324
[ "self.forms = []\ninstances = instances or []\nfor i, obj in enumerate(instances):\n if isinstance(obj, db.Key):\n obj = db.get(obj)\n form_kwargs = {'instance': obj, 'prefix': '%i' % i}\n if data:\n form_kwargs.update(dict(data=data))\n base_form = self.base_form(**form_kwargs)\n self....
<|body_start_0|> self.forms = [] instances = instances or [] for i, obj in enumerate(instances): if isinstance(obj, db.Key): obj = db.get(obj) form_kwargs = {'instance': obj, 'prefix': '%i' % i} if data: form_kwargs.update(dict(...
BaseFormSet
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseFormSet: def __init__(self, data=None, instances=None, extra_forms=2): """Testing Concerns: - deleting an item - adding an item - altering the key - altering the value""" <|body_0|> def is_valid(self): """App engine doesn't support the empty_permitted flag to mod...
stack_v2_sparse_classes_75kplus_train_074674
1,921
permissive
[ { "docstring": "Testing Concerns: - deleting an item - adding an item - altering the key - altering the value", "name": "__init__", "signature": "def __init__(self, data=None, instances=None, extra_forms=2)" }, { "docstring": "App engine doesn't support the empty_permitted flag to model forms, s...
2
stack_v2_sparse_classes_30k_train_019340
Implement the Python class `BaseFormSet` described below. Class description: Implement the BaseFormSet class. Method signatures and docstrings: - def __init__(self, data=None, instances=None, extra_forms=2): Testing Concerns: - deleting an item - adding an item - altering the key - altering the value - def is_valid(s...
Implement the Python class `BaseFormSet` described below. Class description: Implement the BaseFormSet class. Method signatures and docstrings: - def __init__(self, data=None, instances=None, extra_forms=2): Testing Concerns: - deleting an item - adding an item - altering the key - altering the value - def is_valid(s...
afdc352436f9ce623cfb108caf36cd8bc2590f06
<|skeleton|> class BaseFormSet: def __init__(self, data=None, instances=None, extra_forms=2): """Testing Concerns: - deleting an item - adding an item - altering the key - altering the value""" <|body_0|> def is_valid(self): """App engine doesn't support the empty_permitted flag to mod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseFormSet: def __init__(self, data=None, instances=None, extra_forms=2): """Testing Concerns: - deleting an item - adding an item - altering the key - altering the value""" self.forms = [] instances = instances or [] for i, obj in enumerate(instances): if isinstan...
the_stack_v2_python_sparse
permachart/charter/form_utils.py
justinabrahms/permachart
train
1
224b6a9b58d06e8efff273ed5952ca27e045022a
[ "for line in self:\n line.overdue_amount = 0\n if line.type == 'out_invoice':\n payments_obj = self.env['account.payment'].search([('partner_id', '=', line.partner_id.id), ('state', '=', 'posted'), ('bulk_payment_id.state', 'in', ['cheque_on_hand', 'deposited']), ('payment_type_name', '=', 'Cheque')])\...
<|body_start_0|> for line in self: line.overdue_amount = 0 if line.type == 'out_invoice': payments_obj = self.env['account.payment'].search([('partner_id', '=', line.partner_id.id), ('state', '=', 'posted'), ('bulk_payment_id.state', 'in', ['cheque_on_hand', 'deposited'])...
AccountInvoiceInherit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountInvoiceInherit: def _compute_overdue_amount(self): """Calculating Real outstanding by excluding all draft cheque payments""" <|body_0|> def _compute_stored_overdue_amount(self): """Calculating Real outstanding by excluding all draft cheque payments""" ...
stack_v2_sparse_classes_75kplus_train_074675
3,962
no_license
[ { "docstring": "Calculating Real outstanding by excluding all draft cheque payments", "name": "_compute_overdue_amount", "signature": "def _compute_overdue_amount(self)" }, { "docstring": "Calculating Real outstanding by excluding all draft cheque payments", "name": "_compute_stored_overdue_...
3
stack_v2_sparse_classes_30k_train_043064
Implement the Python class `AccountInvoiceInherit` described below. Class description: Implement the AccountInvoiceInherit class. Method signatures and docstrings: - def _compute_overdue_amount(self): Calculating Real outstanding by excluding all draft cheque payments - def _compute_stored_overdue_amount(self): Calcu...
Implement the Python class `AccountInvoiceInherit` described below. Class description: Implement the AccountInvoiceInherit class. Method signatures and docstrings: - def _compute_overdue_amount(self): Calculating Real outstanding by excluding all draft cheque payments - def _compute_stored_overdue_amount(self): Calcu...
b6b32366d966aa550af1de50fd4dd1f1e9daefd0
<|skeleton|> class AccountInvoiceInherit: def _compute_overdue_amount(self): """Calculating Real outstanding by excluding all draft cheque payments""" <|body_0|> def _compute_stored_overdue_amount(self): """Calculating Real outstanding by excluding all draft cheque payments""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccountInvoiceInherit: def _compute_overdue_amount(self): """Calculating Real outstanding by excluding all draft cheque payments""" for line in self: line.overdue_amount = 0 if line.type == 'out_invoice': payments_obj = self.env['account.payment'].search...
the_stack_v2_python_sparse
invoice_outstanding/models/account_invoice.py
EshangAllion/rts-payroll
train
2
f4122c5bd98381ffb9e1ad0e584219739daa490c
[ "super(GDriveUploader, self).__init__(folder_name)\nif not re.match('^[A-Za-z0-9._-]+$', self._path):\n raise UploaderException(UploaderException.INVALID_DIR_NAME, 'Invalid dir name {dirname}'.format(dirname=self._path))\nself._gdrive = GoogleDrive(gauth)\nself._folder = None", "query = \"mimeType = 'applicati...
<|body_start_0|> super(GDriveUploader, self).__init__(folder_name) if not re.match('^[A-Za-z0-9._-]+$', self._path): raise UploaderException(UploaderException.INVALID_DIR_NAME, 'Invalid dir name {dirname}'.format(dirname=self._path)) self._gdrive = GoogleDrive(gauth) self._fo...
Upload picked photo to Google Drive
GDriveUploader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GDriveUploader: """Upload picked photo to Google Drive""" def __init__(self, gauth, folder_name='photos-picker'): """Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Google Drive folder name""" <|body_0|> def initi...
stack_v2_sparse_classes_75kplus_train_074676
2,660
permissive
[ { "docstring": "Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Google Drive folder name", "name": "__init__", "signature": "def __init__(self, gauth, folder_name='photos-picker')" }, { "docstring": "Clear remote directory", "name": "...
3
stack_v2_sparse_classes_30k_train_030539
Implement the Python class `GDriveUploader` described below. Class description: Upload picked photo to Google Drive Method signatures and docstrings: - def __init__(self, gauth, folder_name='photos-picker'): Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Goog...
Implement the Python class `GDriveUploader` described below. Class description: Upload picked photo to Google Drive Method signatures and docstrings: - def __init__(self, gauth, folder_name='photos-picker'): Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Goog...
6790e0411bb46e3206ca778dbd83ddd1d4f90f21
<|skeleton|> class GDriveUploader: """Upload picked photo to Google Drive""" def __init__(self, gauth, folder_name='photos-picker'): """Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Google Drive folder name""" <|body_0|> def initi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GDriveUploader: """Upload picked photo to Google Drive""" def __init__(self, gauth, folder_name='photos-picker'): """Constructor :param pydrive.auth.GoogleAuth gauth: GoogleAth authentified instance :param str folder_name: Google Drive folder name""" super(GDriveUploader, self).__init__(f...
the_stack_v2_python_sparse
photospicker/uploader/uploaders/gdrive_uploader.py
l-vo/photos-picker
train
0
121ecbfeb94bfc8efbd3d2bd59e3a61b82c3fa5a
[ "self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.fromZone(zone)]\nself.glob = glob\nself.eq = 'matchGlob' if glob else '__eq__'", "reply = request.reply()\nqname = request.q.qname\nqtype = QTYPE[request.q.qtype]\nfor name, rtype, rr in self.zone:\n if getattr(qname, self.eq)(name) and (qtype == rtype...
<|body_start_0|> self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.fromZone(zone)] self.glob = glob self.eq = 'matchGlob' if glob else '__eq__' <|end_body_0|> <|body_start_1|> reply = request.reply() qname = request.q.qname qtype = QTYPE[request.q.qtype] ...
Simple fixed zone file resolver.
ZoneResolver
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZoneResolver: """Simple fixed zone file resolver.""" def __init__(self, zone, glob=False): """Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file""" <|body_0|> def resolve(self, request, ha...
stack_v2_sparse_classes_75kplus_train_074677
4,374
permissive
[ { "docstring": "Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file", "name": "__init__", "signature": "def __init__(self, zone, glob=False)" }, { "docstring": "Respond to DNS request - parameters are request packe...
2
stack_v2_sparse_classes_30k_train_028305
Implement the Python class `ZoneResolver` described below. Class description: Simple fixed zone file resolver. Method signatures and docstrings: - def __init__(self, zone, glob=False): Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file...
Implement the Python class `ZoneResolver` described below. Class description: Simple fixed zone file resolver. Method signatures and docstrings: - def __init__(self, zone, glob=False): Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file...
541f58da464296001109f9cfbb879256957b3819
<|skeleton|> class ZoneResolver: """Simple fixed zone file resolver.""" def __init__(self, zone, glob=False): """Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file""" <|body_0|> def resolve(self, request, ha...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ZoneResolver: """Simple fixed zone file resolver.""" def __init__(self, zone, glob=False): """Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file""" self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR....
the_stack_v2_python_sparse
code/default/lib/noarch/dnslib/zoneresolver.py
XX-net/XX-Net
train
40,250
0ba27183e05221117b702e01069a9691ddb96e7f
[ "from jina.logging.predefined import default_logger\n_meta_config = get_default_metas()\n_meta_config.update(data.get('metas', {}))\nif _meta_config:\n data['metas'] = _meta_config\ncls._init_from_yaml = True\nif dataclasses.is_dataclass(cls):\n obj = cls(**data.get('with', {}))\n cls.__bases__[0].__init__...
<|body_start_0|> from jina.logging.predefined import default_logger _meta_config = get_default_metas() _meta_config.update(data.get('metas', {})) if _meta_config: data['metas'] = _meta_config cls._init_from_yaml = True if dataclasses.is_dataclass(cls): ...
Legacy parser for executor.
ExecutorLegacyParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExecutorLegacyParser: """Legacy parser for executor.""" def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': """:param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml...
stack_v2_sparse_classes_75kplus_train_074678
4,515
permissive
[ { "docstring": ":param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml file loaded as python dict :param runtime_args: Optional runtime_args to be directly passed without being parsed into a yaml config :return: the Flow YAML parser given the syntax version nu...
3
stack_v2_sparse_classes_30k_train_027152
Implement the Python class `ExecutorLegacyParser` described below. Class description: Legacy parser for executor. Method signatures and docstrings: - def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': :param cls: target class type to parse into, must...
Implement the Python class `ExecutorLegacyParser` described below. Class description: Legacy parser for executor. Method signatures and docstrings: - def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': :param cls: target class type to parse into, must...
23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71
<|skeleton|> class ExecutorLegacyParser: """Legacy parser for executor.""" def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': """:param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExecutorLegacyParser: """Legacy parser for executor.""" def parse(self, cls: Type['BaseExecutor'], data: Dict, runtime_args: Optional[Dict[str, Any]]=None) -> 'BaseExecutor': """:param cls: target class type to parse into, must be a :class:`JAMLCompatible` type :param data: flow yaml file loaded ...
the_stack_v2_python_sparse
jina/jaml/parsers/executor/legacy.py
jina-ai/jina
train
20,687
0e7fd2cc98ffd4fd5a836539f6bb2aa7d1becde6
[ "self.client = APIClient()\nuser = Custom_User.objects.create(username='user12', first_name='tom', last_name='jerry')\nself.image_data = {'title': 'No Promises', 'artists': 'Cheat Codes', 'owner': user.id}\nself.response = self.client.post(reverse('create_image'), self.image_data, format='json')", "self.assertEqu...
<|body_start_0|> self.client = APIClient() user = Custom_User.objects.create(username='user12', first_name='tom', last_name='jerry') self.image_data = {'title': 'No Promises', 'artists': 'Cheat Codes', 'owner': user.id} self.response = self.client.post(reverse('create_image'), self.image...
Test suite for the api views.
ImageAPITestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageAPITestCase: """Test suite for the api views.""" def setUp(self): """Define the test client and other test variables.""" <|body_0|> def test_api_can_create_an_image(self): """POST: Test the api has image creation capability.""" <|body_1|> def te...
stack_v2_sparse_classes_75kplus_train_074679
25,406
no_license
[ { "docstring": "Define the test client and other test variables.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "POST: Test the api has image creation capability.", "name": "test_api_can_create_an_image", "signature": "def test_api_can_create_an_image(self)" }, {...
6
null
Implement the Python class `ImageAPITestCase` described below. Class description: Test suite for the api views. Method signatures and docstrings: - def setUp(self): Define the test client and other test variables. - def test_api_can_create_an_image(self): POST: Test the api has image creation capability. - def test_a...
Implement the Python class `ImageAPITestCase` described below. Class description: Test suite for the api views. Method signatures and docstrings: - def setUp(self): Define the test client and other test variables. - def test_api_can_create_an_image(self): POST: Test the api has image creation capability. - def test_a...
efac560c0ddfb315e8704d15090e8f4286a1029d
<|skeleton|> class ImageAPITestCase: """Test suite for the api views.""" def setUp(self): """Define the test client and other test variables.""" <|body_0|> def test_api_can_create_an_image(self): """POST: Test the api has image creation capability.""" <|body_1|> def te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImageAPITestCase: """Test suite for the api views.""" def setUp(self): """Define the test client and other test variables.""" self.client = APIClient() user = Custom_User.objects.create(username='user12', first_name='tom', last_name='jerry') self.image_data = {'title': 'No...
the_stack_v2_python_sparse
app/test_project/project2/tests.py
EtonMon/cs4501
train
0
338f462bcbc556c924424651bc2442bd106d676a
[ "if isinstance(first_arg, str) and isinstance(second_arg, str):\n if not os.path.isfile(first_arg):\n raise FileNotFoundError('HDF5 file expected: %r' % first_arg)\n with h5py.File(first_arg, 'r') as hdf:\n mass_axis = hdf['mass_axis'][...]\n if second_arg not in hdf['snr_values']:\n ...
<|body_start_0|> if isinstance(first_arg, str) and isinstance(second_arg, str): if not os.path.isfile(first_arg): raise FileNotFoundError('HDF5 file expected: %r' % first_arg) with h5py.File(first_arg, 'r') as hdf: mass_axis = hdf['mass_axis'][...] ...
Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode. The operation mode determines the interpolation method used and may be either...
Interpolator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interpolator: """Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode. The operation mode determines the int...
stack_v2_sparse_classes_75kplus_train_074680
12,331
permissive
[ { "docstring": "Initialize the interpolator by definig the used reference values and interpolation mode. The interpolator may be initialized by providing the mass axis and SNR grid, or via a path to a stored precomputed grid and a string specifying the noise spectrum to use. Parameters ---------- first_arg : ma...
3
stack_v2_sparse_classes_30k_train_008992
Implement the Python class `Interpolator` described below. Class description: Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode...
Implement the Python class `Interpolator` described below. Class description: Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode...
ceda4f1069a617bfd5f3ce61af06f24982cc3dfe
<|skeleton|> class Interpolator: """Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode. The operation mode determines the int...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Interpolator: """Interpolation class to estimate the values of arbitrary points from a given grid. The interpolator class is initialized with a mass axis defining the (symmetric) grid, a grid of values which are used as reference points, and a operation mode. The operation mode determines the interpolation me...
the_stack_v2_python_sparse
compas_python_utils/cosmic_integration/selection_effects.py
TeamCOMPAS/COMPAS
train
61
f39e3d7e06ae9fb2d224c90ca0dd0edc7083e70c
[ "if not data or not k in data:\n return 0\nf1 = data.index(k)\nmax_num = max(data)\ndiff = max_num - k\nif diff == 0:\n return len(data) - f1\nfor i in range(1, diff + 1):\n if k + i in data:\n f2 = data.index(k + i)\n return f2 - f1", "if not data:\n return -1\nnum = 0\nlength = len(dat...
<|body_start_0|> if not data or not k in data: return 0 f1 = data.index(k) max_num = max(data) diff = max_num - k if diff == 0: return len(data) - f1 for i in range(1, diff + 1): if k + i in data: f2 = data.index(k + i) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def GetNumberOfK(self, data, k): """Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引""" <|body_0|> def GetNumberOfK2(self, data, k): """二分法的思想 找到第一次出现: 如果中间数字等于k,则判断前一位是否为k 找到最后一次出现: 如果中间数字等于k,则判断后一位是否为k""" <|body_1|> def getfirst(self, data, length, k...
stack_v2_sparse_classes_75kplus_train_074681
2,550
no_license
[ { "docstring": "Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引", "name": "GetNumberOfK", "signature": "def GetNumberOfK(self, data, k)" }, { "docstring": "二分法的思想 找到第一次出现: 如果中间数字等于k,则判断前一位是否为k 找到最后一次出现: 如果中间数字等于k,则判断后一位是否为k", "name": "GetNumberOfK2", "signature": "def GetNumberOfK2(self, data, ...
4
stack_v2_sparse_classes_30k_train_026896
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def GetNumberOfK(self, data, k): Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引 - def GetNumberOfK2(self, data, k): 二分法的思想 找到第一次出现: 如果中间数字等于k,则判断前一位是否为k 找到最后一次出现: 如果中间数字等于k,则判断后一位是否为k ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def GetNumberOfK(self, data, k): Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引 - def GetNumberOfK2(self, data, k): 二分法的思想 找到第一次出现: 如果中间数字等于k,则判断前一位是否为k 找到最后一次出现: 如果中间数字等于k,则判断后一位是否为k ...
24dd0fcf44a84126d7c88e3d4622c26262e72863
<|skeleton|> class Solution: def GetNumberOfK(self, data, k): """Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引""" <|body_0|> def GetNumberOfK2(self, data, k): """二分法的思想 找到第一次出现: 如果中间数字等于k,则判断前一位是否为k 找到最后一次出现: 如果中间数字等于k,则判断后一位是否为k""" <|body_1|> def getfirst(self, data, length, k...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def GetNumberOfK(self, data, k): """Python特色解法 找到数字第一次出现的索引,和原数组中该数字后的一个数字索引""" if not data or not k in data: return 0 f1 = data.index(k) max_num = max(data) diff = max_num - k if diff == 0: return len(data) - f1 for i i...
the_stack_v2_python_sparse
55.在排序数组中查找数字.py
costume24/Sword-to-Offer
train
0
57c5a611a28dd856921f73fbb019ef1133184adc
[ "user = User.objects.create_user('username', 'myemail@test.com', 'password')\nself.client.login(username='username', password='password')\npage = self.client.get('/accounts/profile/', follow=True)\nself.assertEqual(page.status_code, 200)\nself.assertTemplateUsed(page, 'profile.html')", "page = self.client.get('/a...
<|body_start_0|> user = User.objects.create_user('username', 'myemail@test.com', 'password') self.client.login(username='username', password='password') page = self.client.get('/accounts/profile/', follow=True) self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page,...
test the profile views
TestAccountViewsProfile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAccountViewsProfile: """test the profile views""" def test_get_profile_page_when_someone_logged_in(self): """test profile view when someone is logged in""" <|body_0|> def test_profile_view_when_no_one_logged_in(self): """test profile view when no-one is logge...
stack_v2_sparse_classes_75kplus_train_074682
15,097
no_license
[ { "docstring": "test profile view when someone is logged in", "name": "test_get_profile_page_when_someone_logged_in", "signature": "def test_get_profile_page_when_someone_logged_in(self)" }, { "docstring": "test profile view when no-one is logged in", "name": "test_profile_view_when_no_one_l...
2
null
Implement the Python class `TestAccountViewsProfile` described below. Class description: test the profile views Method signatures and docstrings: - def test_get_profile_page_when_someone_logged_in(self): test profile view when someone is logged in - def test_profile_view_when_no_one_logged_in(self): test profile view...
Implement the Python class `TestAccountViewsProfile` described below. Class description: test the profile views Method signatures and docstrings: - def test_get_profile_page_when_someone_logged_in(self): test profile view when someone is logged in - def test_profile_view_when_no_one_logged_in(self): test profile view...
a80148cb642cb09dac57cff18483be14fed67dfd
<|skeleton|> class TestAccountViewsProfile: """test the profile views""" def test_get_profile_page_when_someone_logged_in(self): """test profile view when someone is logged in""" <|body_0|> def test_profile_view_when_no_one_logged_in(self): """test profile view when no-one is logge...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestAccountViewsProfile: """test the profile views""" def test_get_profile_page_when_someone_logged_in(self): """test profile view when someone is logged in""" user = User.objects.create_user('username', 'myemail@test.com', 'password') self.client.login(username='username', passwo...
the_stack_v2_python_sparse
accounts/tests_views.py
sarahbarron/Stream-3-Project
train
1
3996e26afa2e86ba50488322ec2955d34ba6f18c
[ "res = [[1]] if numRows else []\nfor i in range(1, numRows):\n res.append(self.getRow(i))\nreturn res", "arr = [1]\nfor i in range(rowIndex):\n arr.append(arr[i] * (rowIndex - i) / (i + 1))\nreturn arr" ]
<|body_start_0|> res = [[1]] if numRows else [] for i in range(1, numRows): res.append(self.getRow(i)) return res <|end_body_0|> <|body_start_1|> arr = [1] for i in range(rowIndex): arr.append(arr[i] * (rowIndex - i) / (i + 1)) return arr <|end_bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_0|> def getRow(self, rowIndex): """:type rowIndex: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [[1]] if numRows else [] ...
stack_v2_sparse_classes_75kplus_train_074683
1,631
no_license
[ { "docstring": ":type numRows: int :rtype: List[List[int]]", "name": "generate", "signature": "def generate(self, numRows)" }, { "docstring": ":type rowIndex: int :rtype: List[int]", "name": "getRow", "signature": "def getRow(self, rowIndex)" } ]
2
stack_v2_sparse_classes_30k_train_016505
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows): :type numRows: int :rtype: List[List[int]] - def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows): :type numRows: int :rtype: List[List[int]] - def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int] <|skeleton|> class Solution: def...
546cbce06fcd4bc34e16d42b5d5eb68fb25e16a9
<|skeleton|> class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_0|> def getRow(self, rowIndex): """:type rowIndex: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" res = [[1]] if numRows else [] for i in range(1, numRows): res.append(self.getRow(i)) return res def getRow(self, rowIndex): """:type rowIndex: int :rtype: List[int]...
the_stack_v2_python_sparse
leetcode/solution_118.py
eselyavka/python
train
0
f113b016e1e03002fb2e1b385a48a185a9c02a7a
[ "self.func = building_func\nfor key, value in kwargs.items():\n setattr(self, key, value)\nself.qml_Hs, self.labels, self.recycle_rule, self.model_params, self.n_states, self.n_hs, self.n_kappas, self.h_max, self.kappa_max = self.func(**kwargs)\nself.n_states = len(self.qml_Hs)", "try:\n _, _ = (self.true_e...
<|body_start_0|> self.func = building_func for key, value in kwargs.items(): setattr(self, key, value) self.qml_Hs, self.labels, self.recycle_rule, self.model_params, self.n_states, self.n_hs, self.n_kappas, self.h_max, self.kappa_max = self.func(**kwargs) self.n_states = len...
hamiltonian
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class hamiltonian: def __init__(self, building_func: Callable, **kwargs): """Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model **kwags : arguments Arguments of the building_func function""" <|body_0|> def add_true...
stack_v2_sparse_classes_75kplus_train_074684
3,748
permissive
[ { "docstring": "Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model **kwags : arguments Arguments of the building_func function", "name": "__init__", "signature": "def __init__(self, building_func: Callable, **kwargs)" }, { "docst...
4
stack_v2_sparse_classes_30k_train_031925
Implement the Python class `hamiltonian` described below. Class description: Implement the hamiltonian class. Method signatures and docstrings: - def __init__(self, building_func: Callable, **kwargs): Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model...
Implement the Python class `hamiltonian` described below. Class description: Implement the hamiltonian class. Method signatures and docstrings: - def __init__(self, building_func: Callable, **kwargs): Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model...
b14948ca1c91b1e38e2de3e0c98c64b488a7a228
<|skeleton|> class hamiltonian: def __init__(self, building_func: Callable, **kwargs): """Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model **kwags : arguments Arguments of the building_func function""" <|body_0|> def add_true...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class hamiltonian: def __init__(self, building_func: Callable, **kwargs): """Hamiltonian class Parameters ---------- building_func : function Function for preparing the hamiltonians of the model **kwags : arguments Arguments of the building_func function""" self.func = building_func for key,...
the_stack_v2_python_sparse
src/PhaseEstimation/hamiltonians.py
CERN-IT-INNOVATION/Quantum-Phase-Detection-ANNNI
train
4
0b4481d4fb376625a073844a3857a36b906621a1
[ "assert check_argument_types()\nsuper(StyleTokenLayer, self).__init__()\ngst_embs = torch.randn(gst_tokens, gst_token_dim // gst_heads)\nself.register_parameter('gst_embs', torch.nn.Parameter(gst_embs))\nself.mha = MultiHeadedAttention(q_dim=ref_embed_dim, k_dim=gst_token_dim // gst_heads, v_dim=gst_token_dim // gs...
<|body_start_0|> assert check_argument_types() super(StyleTokenLayer, self).__init__() gst_embs = torch.randn(gst_tokens, gst_token_dim // gst_heads) self.register_parameter('gst_embs', torch.nn.Parameter(gst_embs)) self.mha = MultiHeadedAttention(q_dim=ref_embed_dim, k_dim=gst_t...
Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org/abs/1803.09017 Args: ref_embe...
StyleTokenLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StyleTokenLayer: """Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: http...
stack_v2_sparse_classes_75kplus_train_074685
10,101
permissive
[ { "docstring": "Initilize style token layer module.", "name": "__init__", "signature": "def __init__(self, ref_embed_dim: int=128, gst_tokens: int=10, gst_token_dim: int=256, gst_heads: int=4, dropout_rate: float=0.0)" }, { "docstring": "Calculate forward propagation. Args: ref_embs (Tensor): Re...
2
stack_v2_sparse_classes_30k_train_043713
Implement the Python class `StyleTokenLayer` described below. Class description: Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfe...
Implement the Python class `StyleTokenLayer` described below. Class description: Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfe...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class StyleTokenLayer: """Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: http...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StyleTokenLayer: """Style token layer module. This module is style token layer introduced in `Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`. .. _`Style Tokens: Unsupervised Style Modeling, Control and Transfer in End-to-End Speech Synthesis`: https://arxiv.org...
the_stack_v2_python_sparse
espnet2/tts/gst/style_encoder.py
espnet/espnet
train
7,242
86951d6db83ab5f1900c3e52c12cae259b1c6310
[ "super(CriticSr, self).__init__()\nself.sr_net = sr_net\nself.fc1 = nn.Linear(sr_size, 400)\nself.fc2 = nn.Linear(400 + action_dim, 300)\nself.fc3 = nn.Linear(300, 1)\nfan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.fc1.weight)\nnn.init.uniform_(self.fc1.weight, -1 / math.sqrt(fan_in), 1 / math.sqrt(fan_in))...
<|body_start_0|> super(CriticSr, self).__init__() self.sr_net = sr_net self.fc1 = nn.Linear(sr_size, 400) self.fc2 = nn.Linear(400 + action_dim, 300) self.fc3 = nn.Linear(300, 1) fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.fc1.weight) nn.init.uniform_(s...
Represents a Critic in the Actor to Critic Model.
CriticSr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CriticSr: """Represents a Critic in the Actor to Critic Model.""" def __init__(self, sr_net, sr_size, action_dim): """Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs""" <|body_0|> def forward(self, obs_batch, a...
stack_v2_sparse_classes_75kplus_train_074686
13,450
no_license
[ { "docstring": "Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs", "name": "__init__", "signature": "def __init__(self, sr_net, sr_size, action_dim)" }, { "docstring": "Generate Q-values for the batch of states and actions pairs. Args: ...
2
stack_v2_sparse_classes_30k_train_006629
Implement the Python class `CriticSr` described below. Class description: Represents a Critic in the Actor to Critic Model. Method signatures and docstrings: - def __init__(self, sr_net, sr_size, action_dim): Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs ...
Implement the Python class `CriticSr` described below. Class description: Represents a Critic in the Actor to Critic Model. Method signatures and docstrings: - def __init__(self, sr_net, sr_size, action_dim): Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs ...
6dcb04e79f776fc780b843208e2c689578c94bb3
<|skeleton|> class CriticSr: """Represents a Critic in the Actor to Critic Model.""" def __init__(self, sr_net, sr_size, action_dim): """Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs""" <|body_0|> def forward(self, obs_batch, a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CriticSr: """Represents a Critic in the Actor to Critic Model.""" def __init__(self, sr_net, sr_size, action_dim): """Initialise layers. Args: state_dim (int) : Number of state inputs action_dim (int) : Number of action ouputs""" super(CriticSr, self).__init__() self.sr_net = sr_n...
the_stack_v2_python_sparse
retina_reinforcement_sim/src/model/models.py
lewisboyd/MsciProject
train
0
1a422cb34d04fe87d546b4c7c70f5a0d46a91771
[ "self._device = torch.device('cuda' if torch.cuda.is_available() and use_cuda_if_available else 'cpu')\nself._lod = lod\nself._lsd = 2 * self._lod\nself._enc_out_normalization = 'pre'\nself._initial_state_variance = 10.0\nself._learning_rate = 0.001\nEncoder._build_hidden_layers = self._build_enc_hidden_layers\nenc...
<|body_start_0|> self._device = torch.device('cuda' if torch.cuda.is_available() and use_cuda_if_available else 'cpu') self._lod = lod self._lsd = 2 * self._lod self._enc_out_normalization = 'pre' self._initial_state_variance = 10.0 self._learning_rate = 0.001 Enc...
LSTMBaseline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMBaseline: def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True): """TODO: Gradient Clipping? :param target_dim: :param lod: :param cell_config: :param use_cuda_if_available:""" <|body_0|> def forward(self, obs_batch: tor...
stack_v2_sparse_classes_75kplus_train_074687
2,538
permissive
[ { "docstring": "TODO: Gradient Clipping? :param target_dim: :param lod: :param cell_config: :param use_cuda_if_available:", "name": "__init__", "signature": "def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True)" }, { "docstring": ":param obs_ba...
2
stack_v2_sparse_classes_30k_train_002799
Implement the Python class `LSTMBaseline` described below. Class description: Implement the LSTMBaseline class. Method signatures and docstrings: - def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True): TODO: Gradient Clipping? :param target_dim: :param lod: :param c...
Implement the Python class `LSTMBaseline` described below. Class description: Implement the LSTMBaseline class. Method signatures and docstrings: - def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True): TODO: Gradient Clipping? :param target_dim: :param lod: :param c...
7a8ae18c17ff3f324f58a6d2ef8ee93265a6fa07
<|skeleton|> class LSTMBaseline: def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True): """TODO: Gradient Clipping? :param target_dim: :param lod: :param cell_config: :param use_cuda_if_available:""" <|body_0|> def forward(self, obs_batch: tor...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LSTMBaseline: def __init__(self, target_dim: int, lod: int, cell_config: ConfigDict, use_cuda_if_available: bool=True): """TODO: Gradient Clipping? :param target_dim: :param lod: :param cell_config: :param use_cuda_if_available:""" self._device = torch.device('cuda' if torch.cuda.is_available(...
the_stack_v2_python_sparse
rkn/LSTMBaseline.py
RyanLiangY/action-conditional-rkn
train
0
1b6ac686ffcae1ec157f3904d6ddf975298a264c
[ "super(RPN, self).__init__()\nstride = 1\npadding = 1\nbias = True\nself.num_anchors = len(ratios) * len(scales)\nself.RPN_conv = nn.Conv2d(input_depth, output_depth, size, stride, padding, bias=bias)\nself.ncls_out = self.num_anchors\nself.RPN_cls_score = nn.Conv2d(output_depth, self.ncls_out, 1, 1)\nself.RPN_cls_...
<|body_start_0|> super(RPN, self).__init__() stride = 1 padding = 1 bias = True self.num_anchors = len(ratios) * len(scales) self.RPN_conv = nn.Conv2d(input_depth, output_depth, size, stride, padding, bias=bias) self.ncls_out = self.num_anchors self.RPN_cl...
RPN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RPN: def __init__(self, input_depth, output_depth, ratios, scales, size=3): """Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)""" <|body_0|> def forward(self, feature_map): ...
stack_v2_sparse_classes_75kplus_train_074688
1,812
no_license
[ { "docstring": "Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)", "name": "__init__", "signature": "def __init__(self, input_depth, output_depth, ratios, scales, size=3)" }, { "docstring": "process the...
2
stack_v2_sparse_classes_30k_train_027801
Implement the Python class `RPN` described below. Class description: Implement the RPN class. Method signatures and docstrings: - def __init__(self, input_depth, output_depth, ratios, scales, size=3): Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: wi...
Implement the Python class `RPN` described below. Class description: Implement the RPN class. Method signatures and docstrings: - def __init__(self, input_depth, output_depth, ratios, scales, size=3): Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: wi...
225acd5dcde2ab225761ce83f5c9b42e33fdd27c
<|skeleton|> class RPN: def __init__(self, input_depth, output_depth, ratios, scales, size=3): """Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)""" <|body_0|> def forward(self, feature_map): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RPN: def __init__(self, input_depth, output_depth, ratios, scales, size=3): """Initialize a region Proposal network :param input_depth: number of filters coming out of the backbone :param size: window size of RPN (kernel)""" super(RPN, self).__init__() stride = 1 padding = 1 ...
the_stack_v2_python_sparse
model/rpn/rpn.py
UW-COSMOS/mmmask-rcnn
train
2
de5bdcf5a8363ba879073aee8e66ce7485141306
[ "prefix = nums[:]\nfor i in range(1, len(prefix)):\n prefix[i] += prefix[i - 1]\nself.prefix = prefix", "if i == 0:\n return self.prefix[j]\nelse:\n return self.prefix[j] - self.prefix[i - 1]" ]
<|body_start_0|> prefix = nums[:] for i in range(1, len(prefix)): prefix[i] += prefix[i - 1] self.prefix = prefix <|end_body_0|> <|body_start_1|> if i == 0: return self.prefix[j] else: return self.prefix[j] - self.prefix[i - 1] <|end_body_1|>
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> prefix = nums[:] for i in range(1, len(prefix)): ...
stack_v2_sparse_classes_75kplus_train_074689
586
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, i, j)" } ]
2
stack_v2_sparse_classes_30k_train_012015
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int <|skeleton|> class NumArray: def __init__(self, nums): ...
0e35e4cc87bd41144b8e34302aafe776fec1b356
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NumArray: def __init__(self, nums): """:type nums: List[int]""" prefix = nums[:] for i in range(1, len(prefix)): prefix[i] += prefix[i - 1] self.prefix = prefix def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" if i == 0: ...
the_stack_v2_python_sparse
LeetCode/303-range_sum_query_immutable.py
davll/practical-algorithms
train
0
03f780bbaa0af7aa1ebb67bc3f2c426296214706
[ "self.user_agent: Optional[str] = None\nself.forecast_type = 'compact'\nself.save_location = './data'\nself.base_url = 'https://api.met.no/weatherapi/locationforecast/2.0/'\nself.user_config_file: Optional[str] = None\nself.get_config()", "for file in self.files:\n if self.cwd.joinpath(file).is_file():\n ...
<|body_start_0|> self.user_agent: Optional[str] = None self.forecast_type = 'compact' self.save_location = './data' self.base_url = 'https://api.met.no/weatherapi/locationforecast/2.0/' self.user_config_file: Optional[str] = None self.get_config() <|end_body_0|> <|body_s...
Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from which the configuration was taken,...
Config
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from ...
stack_v2_sparse_classes_75kplus_train_074690
2,914
no_license
[ { "docstring": "Create Config object with the current user configuration. Uses default config if no configuration is supplied.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Generator of files to look for user configuration.", "name": "possible_user_config...
4
stack_v2_sparse_classes_30k_test_001794
Implement the Python class `Config` described below. Class description: Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Opt...
Implement the Python class `Config` described below. Class description: Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Opt...
49271f05d110e10035e5e017805abc9d2bd29387
<|skeleton|> class Config: """Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Config: """Retrieves and stores user configuration. Attributes: forecast_type (str): The forecast type to use user_agent (Optional[str]): A user agent string save_location (str): Location to save data to base_url (str): Url for requests user_config_file (Optional[str]): The user config file from which the con...
the_stack_v2_python_sparse
server/venv/Lib/site-packages/metno_locationforecast/config.py
WilliamMRS/CoT
train
0
79b78600bd5f5bba8c03838a163acbbbdca34590
[ "self.firstname = firstname\nself.lastname = lastname\nself.age = age\nself.sex = sex\nself.login_attempts = 0", "print(f'Name: {self.firstname.title()} {self.lastname.title()}')\nprint(f'Age: {self.age}')\nprint(f'Sex: {self.sex}')" ]
<|body_start_0|> self.firstname = firstname self.lastname = lastname self.age = age self.sex = sex self.login_attempts = 0 <|end_body_0|> <|body_start_1|> print(f'Name: {self.firstname.title()} {self.lastname.title()}') print(f'Age: {self.age}') print(f'S...
Basic characteristics of a user
User
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class User: """Basic characteristics of a user""" def __init__(self, firstname, lastname, age, sex): """Initialize a specific user""" <|body_0|> def user_description(self): """if called, provides basic info about the user""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_75kplus_train_074691
2,586
no_license
[ { "docstring": "Initialize a specific user", "name": "__init__", "signature": "def __init__(self, firstname, lastname, age, sex)" }, { "docstring": "if called, provides basic info about the user", "name": "user_description", "signature": "def user_description(self)" } ]
2
stack_v2_sparse_classes_30k_train_016011
Implement the Python class `User` described below. Class description: Basic characteristics of a user Method signatures and docstrings: - def __init__(self, firstname, lastname, age, sex): Initialize a specific user - def user_description(self): if called, provides basic info about the user
Implement the Python class `User` described below. Class description: Basic characteristics of a user Method signatures and docstrings: - def __init__(self, firstname, lastname, age, sex): Initialize a specific user - def user_description(self): if called, provides basic info about the user <|skeleton|> class User: ...
460ab20baccc199a453e0411210dca54ed01f5d8
<|skeleton|> class User: """Basic characteristics of a user""" def __init__(self, firstname, lastname, age, sex): """Initialize a specific user""" <|body_0|> def user_description(self): """if called, provides basic info about the user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class User: """Basic characteristics of a user""" def __init__(self, firstname, lastname, age, sex): """Initialize a specific user""" self.firstname = firstname self.lastname = lastname self.age = age self.sex = sex self.login_attempts = 0 def user_descripti...
the_stack_v2_python_sparse
classes2.py
Casper-V/Oefening
train
1
cdfbf5e8b614f4709b2b35703a562c839c88df4f
[ "logging.info('Validando os dados para criação do usuário na plataforma ALMA.')\nif 'user' not in data.keys():\n raise ParseError('Objeto user é obrigatório.')\nreturn data", "logging.info(f'Dados para criação do usuário na plataforma ALMA: {validated_data}')\nserializer = UserRegisterSerializer()\nuser_valida...
<|body_start_0|> logging.info('Validando os dados para criação do usuário na plataforma ALMA.') if 'user' not in data.keys(): raise ParseError('Objeto user é obrigatório.') return data <|end_body_0|> <|body_start_1|> logging.info(f'Dados para criação do usuário na plataforma...
O serializer para registrar um novo usuário
AlmaUserRegisterSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlmaUserRegisterSerializer: """O serializer para registrar um novo usuário""" def validate(self, data): """Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.""" <|body_0|> def create(self, validated_data): """Cria...
stack_v2_sparse_classes_75kplus_train_074692
3,343
no_license
[ { "docstring": "Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Cria e retorna um novo usuário", "name": "create", "signature": "def create(self, validate...
2
stack_v2_sparse_classes_30k_train_024878
Implement the Python class `AlmaUserRegisterSerializer` described below. Class description: O serializer para registrar um novo usuário Method signatures and docstrings: - def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde. - def create(self, ...
Implement the Python class `AlmaUserRegisterSerializer` described below. Class description: O serializer para registrar um novo usuário Method signatures and docstrings: - def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde. - def create(self, ...
3a8009b17518384c269dfee3c8fe44cbe2567cc0
<|skeleton|> class AlmaUserRegisterSerializer: """O serializer para registrar um novo usuário""" def validate(self, data): """Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.""" <|body_0|> def create(self, validated_data): """Cria...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlmaUserRegisterSerializer: """O serializer para registrar um novo usuário""" def validate(self, data): """Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.""" logging.info('Validando os dados para criação do usuário na plataforma ALMA.')...
the_stack_v2_python_sparse
project/alma/accounts/serializers.py
VWApplications/VWAlmaAPI
train
1
2903cc2bb853e9170eb33c9b9d040dadc0381b0a
[ "super().__init__()\nself.rel_pos_emb = torch.nn.Parameter(torch.randn(2 * seq_len - 1, int(dim_head)))\nself.rel_pos = calc_rel_pos(seq_len)", "content_lambda = torch.einsum('bnk,bnv->bkv', torch.softmax(k, dim=-1), v)\ncontent_output = torch.einsum('bnk,bkv->bnv', q, content_lambda)\nrel_pos_emb = self.rel_pos_...
<|body_start_0|> super().__init__() self.rel_pos_emb = torch.nn.Parameter(torch.randn(2 * seq_len - 1, int(dim_head))) self.rel_pos = calc_rel_pos(seq_len) <|end_body_0|> <|body_start_1|> content_lambda = torch.einsum('bnk,bnv->bkv', torch.softmax(k, dim=-1), v) content_output =...
LambdaLayer
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LambdaLayer: def __init__(self, seq_len: int, dim_head: int, *_, **__): """Attention approximation using Lambda layers, from "Lambda networks: modeling long-range interactions without attention.", Bello, I. (2021).""" <|body_0|> def forward(self, q: torch.Tensor, k: torch.Te...
stack_v2_sparse_classes_75kplus_train_074693
2,479
permissive
[ { "docstring": "Attention approximation using Lambda layers, from \"Lambda networks: modeling long-range interactions without attention.\", Bello, I. (2021).", "name": "__init__", "signature": "def __init__(self, seq_len: int, dim_head: int, *_, **__)" }, { "docstring": "..NOTE: We're reusing th...
2
stack_v2_sparse_classes_30k_train_036160
Implement the Python class `LambdaLayer` described below. Class description: Implement the LambdaLayer class. Method signatures and docstrings: - def __init__(self, seq_len: int, dim_head: int, *_, **__): Attention approximation using Lambda layers, from "Lambda networks: modeling long-range interactions without atte...
Implement the Python class `LambdaLayer` described below. Class description: Implement the LambdaLayer class. Method signatures and docstrings: - def __init__(self, seq_len: int, dim_head: int, *_, **__): Attention approximation using Lambda layers, from "Lambda networks: modeling long-range interactions without atte...
71bab94cb954e6e291ca93d3bce5dffadab4286d
<|skeleton|> class LambdaLayer: def __init__(self, seq_len: int, dim_head: int, *_, **__): """Attention approximation using Lambda layers, from "Lambda networks: modeling long-range interactions without attention.", Bello, I. (2021).""" <|body_0|> def forward(self, q: torch.Tensor, k: torch.Te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LambdaLayer: def __init__(self, seq_len: int, dim_head: int, *_, **__): """Attention approximation using Lambda layers, from "Lambda networks: modeling long-range interactions without attention.", Bello, I. (2021).""" super().__init__() self.rel_pos_emb = torch.nn.Parameter(torch.randn...
the_stack_v2_python_sparse
xformers/components/attention/lambda_layer.py
hercules261188/xformers
train
1
604ac42eb5b83b65e42c3706cc61fbde3b72256f
[ "question = 'What language did you first learn to speak?'\nself.my_survey = AnonymousSurvey(question)\n\"'создает экземпляр опроса; self позволяет использовать в любом месте класса\"\nself.responses = ['English', 'Spanish', 'Mandarin']\n\"'создает список ответов; self позволяет использовать в любом месте класса\"",...
<|body_start_0|> question = 'What language did you first learn to speak?' self.my_survey = AnonymousSurvey(question) "'создает экземпляр опроса; self позволяет использовать в любом месте класса" self.responses = ['English', 'Spanish', 'Mandarin'] "'создает список ответов; self по...
Тесты для класса AnonymousSurvey
TestAnonmyousSurvey
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAnonmyousSurvey: """Тесты для класса AnonymousSurvey""" def setUp(self): """'Создание опроса и набора ответов для всех тестовых методов.""" <|body_0|> def test_store_single_response(self): """Проверяет, что один ответ сохранен правильно. Больше НЕ СОЗДАЕМ ЭКЗ...
stack_v2_sparse_classes_75kplus_train_074694
5,407
permissive
[ { "docstring": "'Создание опроса и набора ответов для всех тестовых методов.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Проверяет, что один ответ сохранен правильно. Больше НЕ СОЗДАЕМ ЭКЗЕМПЛЯР опроса и ОТВЕТЫ т.е. не пишем question = \"What language did you first learn...
3
stack_v2_sparse_classes_30k_train_052184
Implement the Python class `TestAnonmyousSurvey` described below. Class description: Тесты для класса AnonymousSurvey Method signatures and docstrings: - def setUp(self): 'Создание опроса и набора ответов для всех тестовых методов. - def test_store_single_response(self): Проверяет, что один ответ сохранен правильно. ...
Implement the Python class `TestAnonmyousSurvey` described below. Class description: Тесты для класса AnonymousSurvey Method signatures and docstrings: - def setUp(self): 'Создание опроса и набора ответов для всех тестовых методов. - def test_store_single_response(self): Проверяет, что один ответ сохранен правильно. ...
af6a3d356f2ee7748e959c63768662fb16750c8d
<|skeleton|> class TestAnonmyousSurvey: """Тесты для класса AnonymousSurvey""" def setUp(self): """'Создание опроса и набора ответов для всех тестовых методов.""" <|body_0|> def test_store_single_response(self): """Проверяет, что один ответ сохранен правильно. Больше НЕ СОЗДАЕМ ЭКЗ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestAnonmyousSurvey: """Тесты для класса AnonymousSurvey""" def setUp(self): """'Создание опроса и набора ответов для всех тестовых методов.""" question = 'What language did you first learn to speak?' self.my_survey = AnonymousSurvey(question) "'создает экземпляр опроса; s...
the_stack_v2_python_sparse
test_2_survey.py
HeyArtem/python_lesson_10
train
0
f8f5abe5119d83aa6a2066384693226d96de6478
[ "logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('div.book-name').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_author = soup.select_one('div.author span.name').text.strip()\nlogger.info('Novel author: %s', self.novel...
<|body_start_0|> logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_title = soup.select_one('div.book-name').text.strip() logger.info('Novel title: %s', self.novel_title) self.novel_author = soup.select_one('div.author span.name').text.str...
NovelUpdatesCC
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NovelUpdatesCC: def read_novel_info(self): """Get novel title, autor, cover etc""" <|body_0|> def download_chapter_body(self, chapter): """Download body of a single chapter and return as clean html format.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_074695
3,146
permissive
[ { "docstring": "Get novel title, autor, cover etc", "name": "read_novel_info", "signature": "def read_novel_info(self)" }, { "docstring": "Download body of a single chapter and return as clean html format.", "name": "download_chapter_body", "signature": "def download_chapter_body(self, c...
2
stack_v2_sparse_classes_30k_train_007936
Implement the Python class `NovelUpdatesCC` described below. Class description: Implement the NovelUpdatesCC class. Method signatures and docstrings: - def read_novel_info(self): Get novel title, autor, cover etc - def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html fo...
Implement the Python class `NovelUpdatesCC` described below. Class description: Implement the NovelUpdatesCC class. Method signatures and docstrings: - def read_novel_info(self): Get novel title, autor, cover etc - def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html fo...
451e816ab03c8466be90f6f0b3eaa52d799140ce
<|skeleton|> class NovelUpdatesCC: def read_novel_info(self): """Get novel title, autor, cover etc""" <|body_0|> def download_chapter_body(self, chapter): """Download body of a single chapter and return as clean html format.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NovelUpdatesCC: def read_novel_info(self): """Get novel title, autor, cover etc""" logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_title = soup.select_one('div.book-name').text.strip() logger.info('Novel title: %s', self.novel...
the_stack_v2_python_sparse
lncrawl/sources/novelupdatescc.py
NNTin/lightnovel-crawler
train
2
631de2942d6f0b78ea75799a7cdf87ae27958f39
[ "super().__init__()\nif not callable(raysampler):\n raise ValueError('\"raysampler\" has to be a \"Callable\" object.')\nif not callable(raymarcher):\n raise ValueError('\"raymarcher\" has to be a \"Callable\" object.')\nself.raysampler = raysampler\nself.raymarcher = raymarcher", "if not callable(volumetri...
<|body_start_0|> super().__init__() if not callable(raysampler): raise ValueError('"raysampler" has to be a "Callable" object.') if not callable(raymarcher): raise ValueError('"raymarcher" has to be a "Callable" object.') self.raysampler = raysampler self....
A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input the rendering cameras as well as the `volumetric_function` `Callable`, which defines ...
ImplicitRenderer
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImplicitRenderer: """A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input the rendering cameras as well as the `vol...
stack_v2_sparse_classes_75kplus_train_074696
17,111
permissive
[ { "docstring": "Args: raysampler: A `Callable` that takes as input scene cameras (an instance of `CamerasBase`) and returns a RayBundle or HeterogeneousRayBundle, that describes the rays emitted from the cameras. raymarcher: A `Callable` that receives the response of the `volumetric_function` (an input to `self...
2
stack_v2_sparse_classes_30k_train_047012
Implement the Python class `ImplicitRenderer` described below. Class description: A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input th...
Implement the Python class `ImplicitRenderer` described below. Class description: A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input th...
a3d99cab6bf5eb69be8d5eb48895da6edd859565
<|skeleton|> class ImplicitRenderer: """A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input the rendering cameras as well as the `vol...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImplicitRenderer: """A class for rendering a batch of implicit surfaces. The class should be initialized with a raysampler and raymarcher class which both have to be a `Callable`. VOLUMETRIC_FUNCTION The `forward` function of the renderer accepts as input the rendering cameras as well as the `volumetric_funct...
the_stack_v2_python_sparse
pytorch3d/renderer/implicit/renderer.py
facebookresearch/pytorch3d
train
7,964
76bf9535afdc2396debb9e9d413902b39a7d5771
[ "child_indices = heap._indices_of_children(index)\nvalid_child_indices = [i for i in child_indices if i < len(heap._data)]\nif not valid_child_indices:\n return\nparent_value = heap._data[index]\nfor i in valid_child_indices:\n child_value = heap._data[i]\n if child_value.priority < parent_value.priority:\...
<|body_start_0|> child_indices = heap._indices_of_children(index) valid_child_indices = [i for i in child_indices if i < len(heap._data)] if not valid_child_indices: return parent_value = heap._data[index] for i in valid_child_indices: child_value = heap._...
HeapAssertions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeapAssertions: def assertHeap(self, heap, operation, index=0): """AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the assertHeap is being run.""" <|body_0|> def assertIndices(self, heap): """AssertIndice...
stack_v2_sparse_classes_75kplus_train_074697
27,238
no_license
[ { "docstring": "AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the assertHeap is being run.", "name": "assertHeap", "signature": "def assertHeap(self, heap, operation, index=0)" }, { "docstring": "AssertIndices checks that the index...
2
null
Implement the Python class `HeapAssertions` described below. Class description: Implement the HeapAssertions class. Method signatures and docstrings: - def assertHeap(self, heap, operation, index=0): AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the ass...
Implement the Python class `HeapAssertions` described below. Class description: Implement the HeapAssertions class. Method signatures and docstrings: - def assertHeap(self, heap, operation, index=0): AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the ass...
d4db02f001fee61e7d86e50027b0d34a64c998bf
<|skeleton|> class HeapAssertions: def assertHeap(self, heap, operation, index=0): """AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the assertHeap is being run.""" <|body_0|> def assertIndices(self, heap): """AssertIndice...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HeapAssertions: def assertHeap(self, heap, operation, index=0): """AssertHeap is an O(n) check that the heap is valid. Operation is a string indicating the operation after which the assertHeap is being run.""" child_indices = heap._indices_of_children(index) valid_child_indices = [i fo...
the_stack_v2_python_sparse
3. Heaps/student_files/test_car_queue.py
JonathanMichaelEdwards/COSC-122--Projects
train
0
b6e462fae276bc2cfbb8d86c9b3165dff01b1cdf
[ "test = 'abacabaca'\nd = Ling(test)\nself.assertEqual(d.s, 'abacabaca')\nself.assertEqual(Ling(test).calculate(), '3\\naca\\nba\\nca')\ntest = 'abaca'\nself.assertEqual(Ling(test).calculate(), '0')\ntest = 'fffffaafgfg'", "import random\nimport timeit\ntest = str(nmax) + ' ' + str(nmax) + '\\n'\nnumnums = [str(i)...
<|body_start_0|> test = 'abacabaca' d = Ling(test) self.assertEqual(d.s, 'abacabaca') self.assertEqual(Ling(test).calculate(), '3\naca\nba\nca') test = 'abaca' self.assertEqual(Ling(test).calculate(), '0') test = 'fffffaafgfg' <|end_body_0|> <|body_start_1|> ...
unitTests
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class unitTests: def test_single_test(self): """Ling class testing""" <|body_0|> def time_limit_test(self, nmax): """Timelimit testing""" <|body_1|> <|end_skeleton|> <|body_start_0|> test = 'abacabaca' d = Ling(test) self.assertEqual(d.s, ...
stack_v2_sparse_classes_75kplus_train_074698
3,411
permissive
[ { "docstring": "Ling class testing", "name": "test_single_test", "signature": "def test_single_test(self)" }, { "docstring": "Timelimit testing", "name": "time_limit_test", "signature": "def time_limit_test(self, nmax)" } ]
2
stack_v2_sparse_classes_30k_train_048147
Implement the Python class `unitTests` described below. Class description: Implement the unitTests class. Method signatures and docstrings: - def test_single_test(self): Ling class testing - def time_limit_test(self, nmax): Timelimit testing
Implement the Python class `unitTests` described below. Class description: Implement the unitTests class. Method signatures and docstrings: - def test_single_test(self): Ling class testing - def time_limit_test(self, nmax): Timelimit testing <|skeleton|> class unitTests: def test_single_test(self): """L...
ae02ea872ca91ef98630cc172a844b82cc56f621
<|skeleton|> class unitTests: def test_single_test(self): """Ling class testing""" <|body_0|> def time_limit_test(self, nmax): """Timelimit testing""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class unitTests: def test_single_test(self): """Ling class testing""" test = 'abacabaca' d = Ling(test) self.assertEqual(d.s, 'abacabaca') self.assertEqual(Ling(test).calculate(), '3\naca\nba\nca') test = 'abaca' self.assertEqual(Ling(test).calculate(), '0') ...
the_stack_v2_python_sparse
codeforces/667C_ling.py
snsokolov/contests
train
1
fd0a0ae0adc031f7afdb3cdb3a810ee944521902
[ "if not mode in ['grid', 'muni', 'simu']:\n raise ValueError('Only \"grid\" and \"muni\" mode are allowed')\nself.GHI, self.WS, self.WD = (GHI, WS, WD)\nself.D_freq, self.h_freq = (D_freq, h_freq)\nself.mode = mode\nself.hours = hours\nif type(GHI) == pd.core.frame.DataFrame:\n self._install(GHI)\nelif type(...
<|body_start_0|> if not mode in ['grid', 'muni', 'simu']: raise ValueError('Only "grid" and "muni" mode are allowed') self.GHI, self.WS, self.WD = (GHI, WS, WD) self.D_freq, self.h_freq = (D_freq, h_freq) self.mode = mode self.hours = hours if type(GHI) == pd...
Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in same format as GHI Input can be only one information, e.g. only GHI or even n...
forecast
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class forecast: """Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in same format as GHI Input can be only one ...
stack_v2_sparse_classes_75kplus_train_074699
35,934
no_license
[ { "docstring": "Initialises forecast and check which information is given. Also calls the install method (see forecast.install). Modes: \"grid\" and \"muni\" grid mode accepts forcast for given grid numbers muni mode accepts forecasts for given muni numbers simu mode accepts forecast initialised in simulation m...
3
stack_v2_sparse_classes_30k_train_013022
Implement the Python class `forecast` described below. Class description: Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in sa...
Implement the Python class `forecast` described below. Class description: Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in sa...
51aaf5123c2780dda89b2ae8d0a1e1b71768b2ed
<|skeleton|> class forecast: """Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in same format as GHI Input can be only one ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class forecast: """Structure to handle weather forecasts containing global irridiance, windspeed and wind direction. Input: GHI: Global irridicance as pandas dataframe preferably with timeseries as index WS: Windspeed in same format as GHI WD: Wind direction in same format as GHI Input can be only one information, ...
the_stack_v2_python_sparse
Libraries/import_forecast.py
JonasVilladsen/P6_software
train
0