blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8082efdaded4d052c7c26a00fd641de50471a8f1 | [
"self.validate_parameters(transaction_id=transaction_id)\n_query_builder = Configuration.get_base_uri()\n_query_builder += '/merchant/signature/{transactionId}'\n_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'transactionId': transaction_id})\n_query_url = APIHelper.clean_url(_query... | <|body_start_0|>
self.validate_parameters(transaction_id=transaction_id)
_query_builder = Configuration.get_base_uri()
_query_builder += '/merchant/signature/{transactionId}'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'transactionId': transaction_id})... | A Controller to access Endpoints in the idfy_rest_client API. | SignatureController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignatureController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def signature_get(self, transaction_id):
"""Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: transaction_id (uuid|string): TODO: type description here. Ex... | stack_v2_sparse_classes_36k_train_034600 | 5,684 | permissive | [
{
"docstring": "Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: transaction_id (uuid|string): TODO: type description here. Example: Returns: MerchantSignTransaction: Response from the API. OK Raises: APIException: When an error occurs while fetching the data from the re... | 3 | null | Implement the Python class `SignatureController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def signature_get(self, transaction_id): Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: tran... | Implement the Python class `SignatureController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def signature_get(self, transaction_id): Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: tran... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class SignatureController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def signature_get(self, transaction_id):
"""Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: transaction_id (uuid|string): TODO: type description here. Ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignatureController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def signature_get(self, transaction_id):
"""Does a GET request to /merchant/signature/{transactionId}. Get a single transaction Args: transaction_id (uuid|string): TODO: type description here. Example: Return... | the_stack_v2_python_sparse | idfy_rest_client/controllers/signature_controller.py | dealflowteam/Idfy | train | 0 |
f81a52f0e774127e9a2a60be939c1259ccc86158 | [
"if s == '':\n return True\nif t == '':\n return False\nlt = len(t)\nls = len(s)\ni_t = 0\ni_s = 0\nwhile i_t < lt:\n if t[i_t] == s[i_s]:\n i_s += 1\n if i_s == ls:\n return True\n i_t += 1\nreturn False",
"idx = 0\nbeg = 0\nwhile idx < len(s):\n if beg >= len(t):\n return ... | <|body_start_0|>
if s == '':
return True
if t == '':
return False
lt = len(t)
ls = len(s)
i_t = 0
i_s = 0
while i_t < lt:
if t[i_t] == s[i_s]:
i_s += 1
if i_s == ls:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool 379ms"""
<|body_0|>
def isSubsequence_1(self, s, t):
""":type s: str :type t: str :rtype: bool 45ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
... | stack_v2_sparse_classes_36k_train_034601 | 1,880 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool 379ms",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool 45ms",
"name": "isSubsequence_1",
"signature": "def isSubsequence_1(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool 379ms
- def isSubsequence_1(self, s, t): :type s: str :type t: str :rtype: bool 45ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool 379ms
- def isSubsequence_1(self, s, t): :type s: str :type t: str :rtype: bool 45ms
<|skeleton|>
class Sol... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool 379ms"""
<|body_0|>
def isSubsequence_1(self, s, t):
""":type s: str :type t: str :rtype: bool 45ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool 379ms"""
if s == '':
return True
if t == '':
return False
lt = len(t)
ls = len(s)
i_t = 0
i_s = 0
while i_t < lt:
if t[i_t] == ... | the_stack_v2_python_sparse | IsSubsequence_MID_392.py | 953250587/leetcode-python | train | 2 | |
d1732df6973e57ea107066174899d57752e42292 | [
"self.data = ''\n\ndef dfs(node):\n if node:\n self.data += '%s ' % node.val\n dfs(node.left)\n dfs(node.right)\n else:\n self.data += '# '\ndfs(root)\nreturn self.data",
"def dfs():\n val = next(data)\n if val == '#':\n return None\n node = TreeNode(int(val))\n ... | <|body_start_0|>
self.data = ''
def dfs(node):
if node:
self.data += '%s ' % node.val
dfs(node.left)
dfs(node.right)
else:
self.data += '# '
dfs(root)
return self.data
<|end_body_0|>
<|body_start_1|... | Codec | [
"Unlicense"
] | 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_36k_train_034602 | 1,568 | permissive | [
{
"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_016223 | 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:... | 2a03499ed0b403d79f6c8451c9a839991b23e188 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
self.data = ''
def dfs(node):
if node:
self.data += '%s ' % node.val
dfs(node.left)
dfs(node.right)
else:... | the_stack_v2_python_sparse | leetcode/297_serialize_deserialize_binary_tree.py | leetcode-notes/daily-algorithms-practice | train | 0 | |
a6169279466f3ef82482f9c3a52e0e3b6f28f523 | [
"cg_model = self.DATA.CG_MODEL.strip()\nscp_array = numpy.array([float(self.DATA.CG_SCECN_X), float(self.DATA.CG_SCECN_Y), float(self.DATA.CG_SCECN_Z)], dtype='float64')\nif cg_model == 'ECEF':\n return scp_array\nelif cg_model == 'WGS84':\n return geodetic_to_ecf(scp_array)\nelse:\n raise ValueError('Got ... | <|body_start_0|>
cg_model = self.DATA.CG_MODEL.strip()
scp_array = numpy.array([float(self.DATA.CG_SCECN_X), float(self.DATA.CG_SCECN_Y), float(self.DATA.CG_SCECN_Z)], dtype='float64')
if cg_model == 'ECEF':
return scp_array
elif cg_model == 'WGS84':
return geodet... | CMETAA | [
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CMETAA:
def get_scp(self):
"""Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray"""
<|body_0|>
def get_arp(self):
"""Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns ------- numpy.ndarray"""
<|body_1|>
def get_ima... | stack_v2_sparse_classes_36k_train_034603 | 11,683 | permissive | [
{
"docstring": "Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray",
"name": "get_scp",
"signature": "def get_scp(self)"
},
{
"docstring": "Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns ------- numpy.ndarray",
"name": "get_arp",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_021108 | Implement the Python class `CMETAA` described below.
Class description:
Implement the CMETAA class.
Method signatures and docstrings:
- def get_scp(self): Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray
- def get_arp(self): Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns -... | Implement the Python class `CMETAA` described below.
Class description:
Implement the CMETAA class.
Method signatures and docstrings:
- def get_scp(self): Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray
- def get_arp(self): Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns -... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class CMETAA:
def get_scp(self):
"""Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray"""
<|body_0|>
def get_arp(self):
"""Gets the Aperture Position, at SCP Time, in ECF coordinates. Returns ------- numpy.ndarray"""
<|body_1|>
def get_ima... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CMETAA:
def get_scp(self):
"""Gets the SCP location in ECF coordinates. Returns ------- numpy.ndarray"""
cg_model = self.DATA.CG_MODEL.strip()
scp_array = numpy.array([float(self.DATA.CG_SCECN_X), float(self.DATA.CG_SCECN_Y), float(self.DATA.CG_SCECN_Z)], dtype='float64')
if cg... | the_stack_v2_python_sparse | sarpy/io/general/nitf_elements/tres/unclass/CMETAA.py | ngageoint/sarpy | train | 192 | |
e77a820a86d3222217a9fbe36cc494e583f4c6c5 | [
"try:\n date = ElectionDay.objects.get(date=self.kwargs['date'])\nexcept:\n raise APIException('No elections on {}.'.format(self.kwargs['date']))\ndivision_ids = []\nfor election in date.elections.all():\n if election.division.level == STATE_LEVEL and election.race.special:\n division_ids.append(ele... | <|body_start_0|>
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
division_ids = []
for election in date.elections.all():
if election.division.level == STATE_LEV... | SpecialMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_034604 | 5,447 | no_license | [
{
"docstring": "Returns a queryset of all states holding a special election on a date.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Adds ``election_day`` to serializer context.",
"name": "get_serializer_context",
"signature": "def get_serializer_cont... | 2 | stack_v2_sparse_classes_30k_train_009584 | Implement the Python class `SpecialMixin` described below.
Class description:
Implement the SpecialMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all states holding a special election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer con... | Implement the Python class `SpecialMixin` described below.
Class description:
Implement the SpecialMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all states holding a special election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer con... | 9137a0c59e044d081d6c34f0e9e97b789e69bdbf | <|skeleton|>
class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecialMixin:
def get_queryset(self):
"""Returns a queryset of all states holding a special election on a date."""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
... | the_stack_v2_python_sparse | theshow/viewsets.py | The-Politico/politico-elections | train | 0 | |
14ee4c15847b4a84087dda703f0040f94a844ab9 | [
"transformed_input = []\ntokenized_string = nltk.word_tokenize(input_string)\npos_tagged_tokens = nltk.pos_tag(tokenized_string)\nwordnet_lemmatizer = WordNetLemmatizer()\nfor pos_tagged_token in pos_tagged_tokens:\n word, part_of_speech = pos_tagged_token\n if str(part_of_speech).startswith('N'):\n tr... | <|body_start_0|>
transformed_input = []
tokenized_string = nltk.word_tokenize(input_string)
pos_tagged_tokens = nltk.pos_tag(tokenized_string)
wordnet_lemmatizer = WordNetLemmatizer()
for pos_tagged_token in pos_tagged_tokens:
word, part_of_speech = pos_tagged_token
... | This class implements lemmatization and is based on an abstract method. | LemmatizationFilePreprocessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LemmatizationFilePreprocessing:
"""This class implements lemmatization and is based on an abstract method."""
def string_transformation(input_string):
"""This method returns a string array with the words of the document. It needs to be used for query preprocessing as well."""
... | stack_v2_sparse_classes_36k_train_034605 | 6,719 | no_license | [
{
"docstring": "This method returns a string array with the words of the document. It needs to be used for query preprocessing as well.",
"name": "string_transformation",
"signature": "def string_transformation(input_string)"
},
{
"docstring": "This method reads the 20 newsgroup corpus, processe... | 3 | stack_v2_sparse_classes_30k_train_016362 | Implement the Python class `LemmatizationFilePreprocessing` described below.
Class description:
This class implements lemmatization and is based on an abstract method.
Method signatures and docstrings:
- def string_transformation(input_string): This method returns a string array with the words of the document. It nee... | Implement the Python class `LemmatizationFilePreprocessing` described below.
Class description:
This class implements lemmatization and is based on an abstract method.
Method signatures and docstrings:
- def string_transformation(input_string): This method returns a string array with the words of the document. It nee... | 3192cdb4b969e461d389d2cff2063a33d79fa9e2 | <|skeleton|>
class LemmatizationFilePreprocessing:
"""This class implements lemmatization and is based on an abstract method."""
def string_transformation(input_string):
"""This method returns a string array with the words of the document. It needs to be used for query preprocessing as well."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LemmatizationFilePreprocessing:
"""This class implements lemmatization and is based on an abstract method."""
def string_transformation(input_string):
"""This method returns a string array with the words of the document. It needs to be used for query preprocessing as well."""
transformed_... | the_stack_v2_python_sparse | src/preprocessing/LemmatizationFilePreprocessing.py | IR-WS-TeamProject/LatentSemanticIndexing | train | 1 |
39b2110306ffbf176b3fc00fee4e37696b58f44c | [
"xs, ys = data\ntest_stat = abs(thinkstats2.Corr(xs, ys))\nreturn test_stat",
"xs, ys = self.data\nxs = np.random.permutation(xs)\nreturn (xs, ys)"
] | <|body_start_0|>
xs, ys = data
test_stat = abs(thinkstats2.Corr(xs, ys))
return test_stat
<|end_body_0|>
<|body_start_1|>
xs, ys = self.data
xs = np.random.permutation(xs)
return (xs, ys)
<|end_body_1|>
| Tests correlations by permutation. | CorrelationPermute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrelationPermute:
"""Tests correlations by permutation."""
def TestStatistic(self, data):
"""Computes the test statistic. data: tuple of xs and ys"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
<|bo... | stack_v2_sparse_classes_36k_train_034606 | 10,162 | permissive | [
{
"docstring": "Computes the test statistic. data: tuple of xs and ys",
"name": "TestStatistic",
"signature": "def TestStatistic(self, data)"
},
{
"docstring": "Run the model of the null hypothesis. returns: simulated data",
"name": "RunModel",
"signature": "def RunModel(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008696 | Implement the Python class `CorrelationPermute` described below.
Class description:
Tests correlations by permutation.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: tuple of xs and ys
- def RunModel(self): Run the model of the null hypothesis. returns: simulated... | Implement the Python class `CorrelationPermute` described below.
Class description:
Tests correlations by permutation.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: tuple of xs and ys
- def RunModel(self): Run the model of the null hypothesis. returns: simulated... | 30a85d5137db95e01461ad21519bc1bdf294044b | <|skeleton|>
class CorrelationPermute:
"""Tests correlations by permutation."""
def TestStatistic(self, data):
"""Computes the test statistic. data: tuple of xs and ys"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorrelationPermute:
"""Tests correlations by permutation."""
def TestStatistic(self, data):
"""Computes the test statistic. data: tuple of xs and ys"""
xs, ys = data
test_stat = abs(thinkstats2.Corr(xs, ys))
return test_stat
def RunModel(self):
"""Run the mode... | the_stack_v2_python_sparse | CompStats/hypothesis.py | sunny2309/scipy_conf_notebooks | train | 2 |
a501fe707294cdffe52cbd564341a1d99aec5fa3 | [
"self.calculator = ExpressionCalculator(unit_system='SI')\nself.unit_system = UnitSystem(system_name='SI')\nself.expressions = [{'expression': '3*{a}+15*{b}', 'operands': [{'name': 'a', 'value': 0.1, 'unit': 'kg'}, {'name': 'b', 'value': 15, 'unit': 'g'}]}, {'expression': '3*{a}+15*{b}+1000*{c}', 'operands': [{'nam... | <|body_start_0|>
self.calculator = ExpressionCalculator(unit_system='SI')
self.unit_system = UnitSystem(system_name='SI')
self.expressions = [{'expression': '3*{a}+15*{b}', 'operands': [{'name': 'a', 'value': 0.1, 'unit': 'kg'}, {'name': 'b', 'value': 15, 'unit': 'g'}]}, {'expression': '3*{a}+15... | Test expression calculator API | ExpressionCalculatorAPITest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpressionCalculatorAPITest:
"""Test expression calculator API"""
def setUp(self) -> None:
"""Setup environment"""
<|body_0|>
def test_convert_request(self):
"""Test calculate API"""
<|body_1|>
def test_convert_to_unit_request(self):
"""Test ... | stack_v2_sparse_classes_36k_train_034607 | 22,594 | permissive | [
{
"docstring": "Setup environment",
"name": "setUp",
"signature": "def setUp(self) -> None"
},
{
"docstring": "Test calculate API",
"name": "test_convert_request",
"signature": "def test_convert_request(self)"
},
{
"docstring": "Test calculate API",
"name": "test_convert_to_u... | 5 | stack_v2_sparse_classes_30k_train_008315 | Implement the Python class `ExpressionCalculatorAPITest` described below.
Class description:
Test expression calculator API
Method signatures and docstrings:
- def setUp(self) -> None: Setup environment
- def test_convert_request(self): Test calculate API
- def test_convert_to_unit_request(self): Test calculate API
-... | Implement the Python class `ExpressionCalculatorAPITest` described below.
Class description:
Test expression calculator API
Method signatures and docstrings:
- def setUp(self) -> None: Setup environment
- def test_convert_request(self): Test calculate API
- def test_convert_to_unit_request(self): Test calculate API
-... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class ExpressionCalculatorAPITest:
"""Test expression calculator API"""
def setUp(self) -> None:
"""Setup environment"""
<|body_0|>
def test_convert_request(self):
"""Test calculate API"""
<|body_1|>
def test_convert_to_unit_request(self):
"""Test ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpressionCalculatorAPITest:
"""Test expression calculator API"""
def setUp(self) -> None:
"""Setup environment"""
self.calculator = ExpressionCalculator(unit_system='SI')
self.unit_system = UnitSystem(system_name='SI')
self.expressions = [{'expression': '3*{a}+15*{b}', 'o... | the_stack_v2_python_sparse | src/geocurrency/calculations/tests.py | fmeurou/geocurrency | train | 5 |
4b38f94efbe0c27cce8244184bdc6dc1210504bd | [
"s = ''\nfor i in strs:\n s += str(len(i)) + '#' + i\nreturn s",
"i, str = (0, [])\nwhile i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\nreturn str"
] | <|body_start_0|>
s = ''
for i in strs:
s += str(len(i)) + '#' + i
return s
<|end_body_0|>
<|body_start_1|>
i, str = (0, [])
while i < len(s):
sharp = s.find('#', i)
l = int(s[i:sharp])
str.append(s[sharp + 1:sharp + l + 1])
... | codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decode a sing string to a list of strings :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_034608 | 605 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decode a sing string to a list of strings :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def deco... | 2 | stack_v2_sparse_classes_30k_train_018174 | Implement the Python class `codec` described below.
Class description:
Implement the codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decode a sing string to a list of strings :type s: str :r... | Implement the Python class `codec` described below.
Class description:
Implement the codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decode a sing string to a list of strings :type s: str :r... | a6d22777d3d2e14dcd0d77832f2be1c7de9ef195 | <|skeleton|>
class codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decode a sing string to a list of strings :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
s = ''
for i in strs:
s += str(len(i)) + '#' + i
return s
def decode(self, s):
"""Decode a sing string to a list of strings :type s: str... | the_stack_v2_python_sparse | 271. Encode and Decode Strings/AC_Answer.py | nikoGao/Leetcode | train | 0 | |
47a5c96c3e3fe6dc201df57cc09a87fe7c37fa0f | [
"super().__init__(embedding_fn)\nself.softmax_temperature = softmax_temperature\nself.seed = seed",
"del time, state\nif not isinstance(outputs, tf.Tensor):\n raise TypeError('Expected outputs to be a single Tensor, got: %s' % type(outputs))\nif self.softmax_temperature is None:\n logits = outputs\nelse:\n ... | <|body_start_0|>
super().__init__(embedding_fn)
self.softmax_temperature = softmax_temperature
self.seed = seed
<|end_body_0|>
<|body_start_1|>
del time, state
if not isinstance(outputs, tf.Tensor):
raise TypeError('Expected outputs to be a single Tensor, got: %s' % ... | An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input. | SampleEmbeddingSampler | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleEmbeddingSampler:
"""An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding_fn: Optional[Callable]=None, softm... | stack_v2_sparse_classes_36k_train_034609 | 32,255 | permissive | [
{
"docstring": "Initializer. Args: embedding_fn: (Optional) A callable that takes a vector tensor of `ids` (argmax ids). The returned tensor will be passed to the decoder input. softmax_temperature: (Optional) `float32` scalar, value to divide the logits by before computing the softmax. Larger values (above 1.0... | 2 | stack_v2_sparse_classes_30k_train_003885 | Implement the Python class `SampleEmbeddingSampler` described below.
Class description:
An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input.
Method signatures and docstring... | Implement the Python class `SampleEmbeddingSampler` described below.
Class description:
An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input.
Method signatures and docstring... | 5dd5f65827c37e9b9b616b79ed93da856b57ffe5 | <|skeleton|>
class SampleEmbeddingSampler:
"""An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding_fn: Optional[Callable]=None, softm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleEmbeddingSampler:
"""An inference sampler that randomly samples from the output distribution. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding_fn: Optional[Callable]=None, softmax_temperatur... | the_stack_v2_python_sparse | tensorflow_addons/seq2seq/sampler.py | tensorflow/addons | train | 1,779 |
6c730519f7cf08b6ef51b7980d8f2b4dba5cdfbd | [
"self.orderbook = OrderBook(limit=10)\nself.output_file = output_file\nself.ws = websocket.WebSocketApp('wss://api.gemini.com/v1/marketdata/{}'.format(symbol), on_message=lambda ws, message: self.on_message(message))\nself.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})",
"data = json.loads(message)\nfor even... | <|body_start_0|>
self.orderbook = OrderBook(limit=10)
self.output_file = output_file
self.ws = websocket.WebSocketApp('wss://api.gemini.com/v1/marketdata/{}'.format(symbol), on_message=lambda ws, message: self.on_message(message))
self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})
... | Crawler | Crawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crawler:
"""Crawler"""
def __init__(self, symbol, output_file):
"""init :param symbol: :param output_file:"""
<|body_0|>
def on_message(self, message):
"""on_message :param message: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.o... | stack_v2_sparse_classes_36k_train_034610 | 4,868 | permissive | [
{
"docstring": "init :param symbol: :param output_file:",
"name": "__init__",
"signature": "def __init__(self, symbol, output_file)"
},
{
"docstring": "on_message :param message: :return:",
"name": "on_message",
"signature": "def on_message(self, message)"
}
] | 2 | null | Implement the Python class `Crawler` described below.
Class description:
Crawler
Method signatures and docstrings:
- def __init__(self, symbol, output_file): init :param symbol: :param output_file:
- def on_message(self, message): on_message :param message: :return: | Implement the Python class `Crawler` described below.
Class description:
Crawler
Method signatures and docstrings:
- def __init__(self, symbol, output_file): init :param symbol: :param output_file:
- def on_message(self, message): on_message :param message: :return:
<|skeleton|>
class Crawler:
"""Crawler"""
... | 74628fcfcfed439ee8dc5498d138b4d019f1ea58 | <|skeleton|>
class Crawler:
"""Crawler"""
def __init__(self, symbol, output_file):
"""init :param symbol: :param output_file:"""
<|body_0|>
def on_message(self, message):
"""on_message :param message: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Crawler:
"""Crawler"""
def __init__(self, symbol, output_file):
"""init :param symbol: :param output_file:"""
self.orderbook = OrderBook(limit=10)
self.output_file = output_file
self.ws = websocket.WebSocketApp('wss://api.gemini.com/v1/marketdata/{}'.format(symbol), on_mes... | the_stack_v2_python_sparse | python_core/qt_crawler.py | ftconan/python3 | train | 1 |
72bce0fbfbfe6a597a62ad0a6bf2a9a10882fd1e | [
"_log.debug(r_body)\nif method == 'GET':\n return self.get_operations(path)\nif method == 'POST':\n return self.post_operations(path, r_body)",
"_log.debug('GET received on user dispatcher')\nif len(path) == 1:\n _log.debug('path length')\n db_users_list = db.get_users()\n _log.debug(db_users_list)... | <|body_start_0|>
_log.debug(r_body)
if method == 'GET':
return self.get_operations(path)
if method == 'POST':
return self.post_operations(path, r_body)
<|end_body_0|>
<|body_start_1|>
_log.debug('GET received on user dispatcher')
if len(path) == 1:
... | Customer Dispatcher for Users | UserDispatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDispatcher:
"""Customer Dispatcher for Users"""
def dispatch(self, path: list, method, r_body=None):
"""dispatch takes in a path and request body and returns status code and response body as tuple"""
<|body_0|>
def get_operations(self, path: list):
"""GET ope... | stack_v2_sparse_classes_36k_train_034611 | 2,019 | no_license | [
{
"docstring": "dispatch takes in a path and request body and returns status code and response body as tuple",
"name": "dispatch",
"signature": "def dispatch(self, path: list, method, r_body=None)"
},
{
"docstring": "GET operations for user",
"name": "get_operations",
"signature": "def g... | 3 | stack_v2_sparse_classes_30k_train_008885 | Implement the Python class `UserDispatcher` described below.
Class description:
Customer Dispatcher for Users
Method signatures and docstrings:
- def dispatch(self, path: list, method, r_body=None): dispatch takes in a path and request body and returns status code and response body as tuple
- def get_operations(self,... | Implement the Python class `UserDispatcher` described below.
Class description:
Customer Dispatcher for Users
Method signatures and docstrings:
- def dispatch(self, path: list, method, r_body=None): dispatch takes in a path and request body and returns status code and response body as tuple
- def get_operations(self,... | 386582cbd30f6bd3e32b6b2dadcfb1413f5a1820 | <|skeleton|>
class UserDispatcher:
"""Customer Dispatcher for Users"""
def dispatch(self, path: list, method, r_body=None):
"""dispatch takes in a path and request body and returns status code and response body as tuple"""
<|body_0|>
def get_operations(self, path: list):
"""GET ope... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDispatcher:
"""Customer Dispatcher for Users"""
def dispatch(self, path: list, method, r_body=None):
"""dispatch takes in a path and request body and returns status code and response body as tuple"""
_log.debug(r_body)
if method == 'GET':
return self.get_operations... | the_stack_v2_python_sparse | projects/project1/users/handler.py | ettynan/Revature | train | 0 |
9791d4b1c0458cfe8247b76f095615a135a4692e | [
"if n == 0 or n == 1:\n return 1\nreturn self.fib(n - 1) + self.fib(n - 2)",
"if n == 0:\n return 1\nreturn self.fact(n - 1) * n"
] | <|body_start_0|>
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
<|end_body_0|>
<|body_start_1|>
if n == 0:
return 1
return self.fact(n - 1) * n
<|end_body_1|>
| MyMath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
<|body_0|>
def fact(self, n):
"""Returns n!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
<... | stack_v2_sparse_classes_36k_train_034612 | 2,510 | no_license | [
{
"docstring": "Returns the nth # of Fibonacci's",
"name": "fib",
"signature": "def fib(self, n)"
},
{
"docstring": "Returns n!",
"name": "fact",
"signature": "def fact(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006240 | Implement the Python class `MyMath` described below.
Class description:
Implement the MyMath class.
Method signatures and docstrings:
- def fib(self, n): Returns the nth # of Fibonacci's
- def fact(self, n): Returns n! | Implement the Python class `MyMath` described below.
Class description:
Implement the MyMath class.
Method signatures and docstrings:
- def fib(self, n): Returns the nth # of Fibonacci's
- def fact(self, n): Returns n!
<|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
... | de912b450a0ff6bb84024cdf653a0ee2f6086be1 | <|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
<|body_0|>
def fact(self, n):
"""Returns n!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
def fact(self, n):
"""Returns n!"""
if n == 0:
return 1
return self.fact(n - 1) * n
| the_stack_v2_python_sparse | cazzola.py | giuscri/problem-solving-workout | train | 1 | |
99471dc8d8095ae4c2b829f35bee4b4dd6dc7bf4 | [
"self._file_path = file_path\nself._virtual_image = virtual_image\nself._ndb_path = '/dev/nbd' + str(Nbd_LoadDiskImage.nbd_port % 16)\nNbd_LoadDiskImage.nbd_port = (Nbd_LoadDiskImage.nbd_port + 1) % 16",
"SyncFileSystem()\ntime.sleep(2)\ntry:\n kpartx_cmd = ['kpartx', '-d', '-v', '-s', self._file_path]\n Ru... | <|body_start_0|>
self._file_path = file_path
self._virtual_image = virtual_image
self._ndb_path = '/dev/nbd' + str(Nbd_LoadDiskImage.nbd_port % 16)
Nbd_LoadDiskImage.nbd_port = (Nbd_LoadDiskImage.nbd_port + 1) % 16
<|end_body_0|>
<|body_start_1|>
SyncFileSystem()
time.sl... | Loads raw disk image using kpartx. | Nbd_LoadDiskImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nbd_LoadDiskImage:
"""Loads raw disk image using kpartx."""
def __init__(self, file_path, virtual_image=True):
"""Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a boolean specifying whether the file is virtual image (not ... | stack_v2_sparse_classes_36k_train_034613 | 8,532 | no_license | [
{
"docstring": "Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a boolean specifying whether the file is virtual image (not raw file) supported by qemu-img Returns: A list of devices for every partition found in an image.",
"name": "__init__",
... | 3 | null | Implement the Python class `Nbd_LoadDiskImage` described below.
Class description:
Loads raw disk image using kpartx.
Method signatures and docstrings:
- def __init__(self, file_path, virtual_image=True): Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a b... | Implement the Python class `Nbd_LoadDiskImage` described below.
Class description:
Loads raw disk image using kpartx.
Method signatures and docstrings:
- def __init__(self, file_path, virtual_image=True): Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a b... | e01a7e11931a61ae91b9cadbc961d703f8c77925 | <|skeleton|>
class Nbd_LoadDiskImage:
"""Loads raw disk image using kpartx."""
def __init__(self, file_path, virtual_image=True):
"""Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a boolean specifying whether the file is virtual image (not ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nbd_LoadDiskImage:
"""Loads raw disk image using kpartx."""
def __init__(self, file_path, virtual_image=True):
"""Initializes LoadDiskImage object. Args: file_path: a path to a file containing raw disk image. virtual_image: a boolean specifying whether the file is virtual image (not raw file) sup... | the_stack_v2_python_sparse | Migrate/Linux_GC/NbdBundle_utils.py | migrate2iaas/cloudscraper-engine | train | 1 |
a41128d417feb72bb19c6c798ee4e96440512106 | [
"try:\n object_id = resolve(request.path).args[0]\n roster = Roster.objects.get(pk=object_id)\n if db_field.name == 'captain':\n kwargs['queryset'] = Registrant.objects.filter(pass_type__in=['MVP', 'Skater'], con=roster.con)\nexcept:\n pass\nreturn super(RosterAdmin, self).formfield_for_foreignke... | <|body_start_0|>
try:
object_id = resolve(request.path).args[0]
roster = Roster.objects.get(pk=object_id)
if db_field.name == 'captain':
kwargs['queryset'] = Registrant.objects.filter(pass_type__in=['MVP', 'Skater'], con=roster.con)
except:
... | RosterAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RosterAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""... | stack_v2_sparse_classes_36k_train_034614 | 11,791 | permissive | [
{
"docstring": "If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "If roster exists, limits participant que... | 3 | stack_v2_sparse_classes_30k_train_017520 | Implement the Python class `RosterAdmin` described below.
Class description:
Implement the RosterAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster.
- d... | Implement the Python class `RosterAdmin` described below.
Class description:
Implement the RosterAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster.
- d... | 22200345b309a89991873be8e5b76bd71c644c29 | <|skeleton|>
class RosterAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RosterAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""If roster exists, limits captain queryset to registrants with Skater or MVP pass of same con as Roster."""
try:
object_id = resolve(request.path).args[0]
roster = Roster.objects.get(pk=obje... | the_stack_v2_python_sparse | scheduler/admin.py | mdaizovi/rcreg_project | train | 1 | |
a3030ea039e7a9a04d2835a27e76f01b312dbb94 | [
"query = session.query(GoldenHitCandidate.hit_id)\nassert query.count() > 0, 'No candidate golden hits'\nquery = query.order_by(GoldenHitCandidate.created_at.desc()).limit(n_lookback)\nquery = query.from_self()\nquery = query.outerjoin(GoldenHit, GoldenHitCandidate.hit_id == GoldenHit.hit_id)\nquery = query.group_b... | <|body_start_0|>
query = session.query(GoldenHitCandidate.hit_id)
assert query.count() > 0, 'No candidate golden hits'
query = query.order_by(GoldenHitCandidate.created_at.desc()).limit(n_lookback)
query = query.from_self()
query = query.outerjoin(GoldenHit, GoldenHitCandidate.hi... | Manager in charge of golden hits. | GoldenHitManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those ... | stack_v2_sparse_classes_36k_train_034615 | 2,356 | no_license | [
{
"docstring": "Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those that have been submitted as golden the least number of times. Args: n_hits: Number of golden hits submissions. n_look... | 2 | stack_v2_sparse_classes_30k_train_018961 | Implement the Python class `GoldenHitManager` described below.
Class description:
Manager in charge of golden hits.
Method signatures and docstrings:
- def submit_golden_hits(n_hits, n_lookback): Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, c... | Implement the Python class `GoldenHitManager` described below.
Class description:
Manager in charge of golden hits.
Method signatures and docstrings:
- def submit_golden_hits(n_hits, n_lookback): Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, c... | 2f9c33c4e1a26b3e9e699210ac974047936f49e1 | <|skeleton|>
class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoldenHitManager:
"""Manager in charge of golden hits."""
def submit_golden_hits(n_hits, n_lookback):
"""Submit golden hits. Fetches the N_LOOKBACK hits most recently selected for golden submission and submits N_HITS of them, cycling through them as necessary, and prioritizing those that have bee... | the_stack_v2_python_sparse | affine/model/mturk/golden_hit_manager.py | winkash/image-classification | train | 0 |
d40ddc1f4e0524c01f019316c920a21d30a59937 | [
"super().__init__()\nself.login_url = login_url\nself.cj = cj\nself.pw_mgr = pw_mgr\nself.save_cookies = save_cookies\ntry:\n self.cj.load(ignore_discard=True)\nexcept IOError:\n pass",
"if res.code == 200 and res.geturl().startswith(self.login_url + '?'):\n self.cj.extract_cookies(res, req)\n data = ... | <|body_start_0|>
super().__init__()
self.login_url = login_url
self.cj = cj
self.pw_mgr = pw_mgr
self.save_cookies = save_cookies
try:
self.cj.load(ignore_discard=True)
except IOError:
pass
<|end_body_0|>
<|body_start_1|>
if res.co... | urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and # logins. opener = urllib.request.build_opener( urllib.request.HTTPCookieProcess... | CosignHandler | [
"MIT",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CosignHandler:
"""urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and # logins. opener = urllib.request.build... | stack_v2_sparse_classes_36k_train_034616 | 5,961 | permissive | [
{
"docstring": "Construct new CosignHandler. Args: login_url: URL of cosign login page. Used to figure out if we have been redirected to the login page after a failed authentication, and as the URL to POST to to log in. cj: An http.cookiejar.CookieJar or equivalent. You'll need something that implements the Fil... | 2 | stack_v2_sparse_classes_30k_train_019178 | Implement the Python class `CosignHandler` described below.
Class description:
urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and ... | Implement the Python class `CosignHandler` described below.
Class description:
urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and ... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class CosignHandler:
"""urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and # logins. opener = urllib.request.build... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CosignHandler:
"""urllib.request style handler for Cosign protected URLs. See http://weblogin.org SYNOPSIS: # Cosign relies on cookies. cj = http.cookiejar.MozillaCookieJar('cookies.txt') # We need an opener that handles cookies and any cosign redirects and # logins. opener = urllib.request.build_opener( urll... | the_stack_v2_python_sparse | recipes/Python/578217_Cosign_Handler/recipe-578217.py | betty29/code-1 | train | 0 |
165b8dbfc145c82ca13b6dd98a2cdada86658d9c | [
"to_child = _Pipe()\nfrom_child = _Pipe()\nexec_term = get_term_command()\nif os.fork() == 0:\n try:\n try:\n to_child.writeable.close()\n from_child.readable.close()\n to_parent = from_child.writeable\n from_parent = to_child.readable\n fcntl.fcntl(t... | <|body_start_0|>
to_child = _Pipe()
from_child = _Pipe()
exec_term = get_term_command()
if os.fork() == 0:
try:
try:
to_child.writeable.close()
from_child.readable.close()
to_parent = from_child.write... | SuProxyMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuProxyMaker:
def __init__(self, message):
"""Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted for the root password."""
<|body_0|>
def get_root(self):
"""Raises UserAbort if ... | stack_v2_sparse_classes_36k_train_034617 | 2,849 | no_license | [
{
"docstring": "Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted for the root password.",
"name": "__init__",
"signature": "def __init__(self, message)"
},
{
"docstring": "Raises UserAbort if the user can... | 2 | stack_v2_sparse_classes_30k_train_021210 | Implement the Python class `SuProxyMaker` described below.
Class description:
Implement the SuProxyMaker class.
Method signatures and docstrings:
- def __init__(self, message): Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted ... | Implement the Python class `SuProxyMaker` described below.
Class description:
Implement the SuProxyMaker class.
Method signatures and docstrings:
- def __init__(self, message): Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted ... | aa49e5f2230353d53f6d79e5824859f027d81b03 | <|skeleton|>
class SuProxyMaker:
def __init__(self, message):
"""Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted for the root password."""
<|body_0|>
def get_root(self):
"""Raises UserAbort if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuProxyMaker:
def __init__(self, message):
"""Displays a box prompting the user for a password. Creates a new master_proxy.MasterObject and starts the child process. The user is prompted for the root password."""
to_child = _Pipe()
from_child = _Pipe()
exec_term = get_term_comm... | the_stack_v2_python_sparse | config/includes.chroot/usr/local/lib/ROX-Lib2/python/rox/su.py | machinebacon/livarp | train | 2 | |
5b63c1cb7b69510c4b09b8a9989104dc059425f2 | [
"bad = np.zeros(len(self.times), dtype=bool)\nfor pcad_mode, max_delta_val in self.max_delta_vals.items():\n mask = self.states_at_times['pcad_mode'] == pcad_mode\n bad |= (np.abs(self.tlm_vals - self.state_vals) > max_delta_val) & mask\nreturn bad",
"super().add_exclude_intervals()\nself.exclude_ofp_interv... | <|body_start_0|>
bad = np.zeros(len(self.times), dtype=bool)
for pcad_mode, max_delta_val in self.max_delta_vals.items():
mask = self.states_at_times['pcad_mode'] == pcad_mode
bad |= (np.abs(self.tlm_vals - self.state_vals) > max_delta_val) & mask
return bad
<|end_body_0|... | ValidatePitchRollBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
<|body_0|>
def add_exclude... | stack_v2_sparse_classes_36k_train_034618 | 27,851 | permissive | [
{
"docstring": "Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings.",
"name": "get_violations_mask",
"signature": "def get_violations_mask(self)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_011034 | Implement the Python class `ValidatePitchRollBase` described below.
Class description:
Implement the ValidatePitchRollBase class.
Method signatures and docstrings:
- def get_violations_mask(self): Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Ta... | Implement the Python class `ValidatePitchRollBase` described below.
Class description:
Implement the ValidatePitchRollBase class.
Method signatures and docstrings:
- def get_violations_mask(self): Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Ta... | eb58686d91b6668af55ae51959a1f8f6eccb7d7d | <|skeleton|>
class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
<|body_0|>
def add_exclude... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidatePitchRollBase:
def get_violations_mask(self):
"""Get the violations mask for the pitch validation class This is the main method for each validation class. It returns a Table with the columns ``start`` and ``stop`` which are date strings."""
bad = np.zeros(len(self.times), dtype=bool)
... | the_stack_v2_python_sparse | kadi/commands/validate.py | sot/kadi | train | 3 | |
9ed3a748839efd3332f60186124b32c57035f82d | [
"user = context.get('user', None)\nviewing_user = context.get('viewing_user', None)\nif not viewing_user or not user.is_authenticated():\n return ''\nkeyid = self.gpg_key_id.get_value(viewing_user.username)\nsend_private_link = '<a href=\"\" title=\"%s;%s\" class=\"private_message\">%s</a>' % (viewing_user.usern... | <|body_start_0|>
user = context.get('user', None)
viewing_user = context.get('viewing_user', None)
if not viewing_user or not user.is_authenticated():
return ''
keyid = self.gpg_key_id.get_value(viewing_user.username)
send_private_link = '<a href="" title="%s;%s" clas... | With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Khtml/Konqueror. Each user can access their private timeline with a link added by this plu... | PrivateTimelinePlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrivateTimelinePlugin:
"""With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Khtml/Konqueror. Each user can access the... | stack_v2_sparse_classes_36k_train_034619 | 3,475 | no_license | [
{
"docstring": "Shows a button to 'Send Private Message to <username>' in the headbar, next to \"(un)follow\" button",
"name": "headbar",
"signature": "def headbar(self, context)"
},
{
"docstring": "Shows a link to 'Send Private Message' in the sidebar when browsing a profile",
"name": "side... | 3 | stack_v2_sparse_classes_30k_train_018421 | Implement the Python class `PrivateTimelinePlugin` described below.
Class description:
With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Kh... | Implement the Python class `PrivateTimelinePlugin` described below.
Class description:
With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Kh... | a9eb05514e8788d7c290f88eae383c0f4d9179ad | <|skeleton|>
class PrivateTimelinePlugin:
"""With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Khtml/Konqueror. Each user can access the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrivateTimelinePlugin:
"""With this plugin users can send a private and encrypted message to somebody, which will be shown only in the private timeline of that user. The message will be encrypted with GPG using a HTML extension currently only available in Khtml/Konqueror. Each user can access their private ti... | the_stack_v2_python_sparse | contrib/privatetimeline/PrivateTimelinePlugin.py | lilac/totem | train | 0 |
b1058e0e388171501c29fa6c189b7551ddde4d86 | [
"try:\n data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()\n login_cookies = loggin_wx()\n cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)\n cookies = {'SERVERID': '%s' % cookie, 'SESSION': '%s' % wx_session}\n test_id = 0\n s = requests.session()\n res = send_requests(s, d... | <|body_start_0|>
try:
data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()
login_cookies = loggin_wx()
cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)
cookies = {'SERVERID': '%s' % cookie, 'SESSION': '%s' % wx_session}
test_id = 0
... | member_openChildCard | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
<|body_0|>
def test_openChildCard_2(self):
"""开通附属卡,主卡人ID错误"""
<|body_1|>
def test_openChildCard_3(self):
"""开通附属卡,主卡ID错误"""
<|body_2|>
def test_openChildCar... | stack_v2_sparse_classes_36k_train_034620 | 4,831 | permissive | [
{
"docstring": "开通附属卡,附属卡已存在的情况",
"name": "test_openChildCard_1",
"signature": "def test_openChildCard_1(self)"
},
{
"docstring": "开通附属卡,主卡人ID错误",
"name": "test_openChildCard_2",
"signature": "def test_openChildCard_2(self)"
},
{
"docstring": "开通附属卡,主卡ID错误",
"name": "test_ope... | 5 | stack_v2_sparse_classes_30k_test_000097 | Implement the Python class `member_openChildCard` described below.
Class description:
Implement the member_openChildCard class.
Method signatures and docstrings:
- def test_openChildCard_1(self): 开通附属卡,附属卡已存在的情况
- def test_openChildCard_2(self): 开通附属卡,主卡人ID错误
- def test_openChildCard_3(self): 开通附属卡,主卡ID错误
- def test_... | Implement the Python class `member_openChildCard` described below.
Class description:
Implement the member_openChildCard class.
Method signatures and docstrings:
- def test_openChildCard_1(self): 开通附属卡,附属卡已存在的情况
- def test_openChildCard_2(self): 开通附属卡,主卡人ID错误
- def test_openChildCard_3(self): 开通附属卡,主卡ID错误
- def test_... | 472f3f6d9bd407f1c4ed30a5557ec141e2434188 | <|skeleton|>
class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
<|body_0|>
def test_openChildCard_2(self):
"""开通附属卡,主卡人ID错误"""
<|body_1|>
def test_openChildCard_3(self):
"""开通附属卡,主卡ID错误"""
<|body_2|>
def test_openChildCar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
try:
data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()
login_cookies = loggin_wx()
cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)
cookies = {'SERVE... | the_stack_v2_python_sparse | case/Test_Environment/Member/member_openChildCard.py | Four-sun/Requests_Load | train | 0 | |
441f89298b13bb0c31797197fa30fb941cb26afa | [
"assert colors1() == ('white', 'white', 'white', 'white')\nassert colors1('red', 'blue', 'yellow', 'chartreuse') == ('red', 'blue', 'yellow', 'chartreuse')\nassert colors1(link_color='red', back_color='blue') == ('white', 'blue', 'red', 'white')\nassert colors1('purple', link_color='red', back_color='blue') == ('pu... | <|body_start_0|>
assert colors1() == ('white', 'white', 'white', 'white')
assert colors1('red', 'blue', 'yellow', 'chartreuse') == ('red', 'blue', 'yellow', 'chartreuse')
assert colors1(link_color='red', back_color='blue') == ('white', 'blue', 'red', 'white')
assert colors1('purple', lin... | Class to test args_kwargs_lab | ArgsKwargsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgsKwargsTest:
"""Class to test args_kwargs_lab"""
def test_colors1(self):
"""Test assertions for colors1 function"""
<|body_0|>
def test_colors2(self):
"""Test assertions for colors2 function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ass... | stack_v2_sparse_classes_36k_train_034621 | 1,798 | no_license | [
{
"docstring": "Test assertions for colors1 function",
"name": "test_colors1",
"signature": "def test_colors1(self)"
},
{
"docstring": "Test assertions for colors2 function",
"name": "test_colors2",
"signature": "def test_colors2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003890 | Implement the Python class `ArgsKwargsTest` described below.
Class description:
Class to test args_kwargs_lab
Method signatures and docstrings:
- def test_colors1(self): Test assertions for colors1 function
- def test_colors2(self): Test assertions for colors2 function | Implement the Python class `ArgsKwargsTest` described below.
Class description:
Class to test args_kwargs_lab
Method signatures and docstrings:
- def test_colors1(self): Test assertions for colors1 function
- def test_colors2(self): Test assertions for colors2 function
<|skeleton|>
class ArgsKwargsTest:
"""Class... | 661903cd9dc49b294fb9a0c905133a4c3f9d8d0f | <|skeleton|>
class ArgsKwargsTest:
"""Class to test args_kwargs_lab"""
def test_colors1(self):
"""Test assertions for colors1 function"""
<|body_0|>
def test_colors2(self):
"""Test assertions for colors2 function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgsKwargsTest:
"""Class to test args_kwargs_lab"""
def test_colors1(self):
"""Test assertions for colors1 function"""
assert colors1() == ('white', 'white', 'white', 'white')
assert colors1('red', 'blue', 'yellow', 'chartreuse') == ('red', 'blue', 'yellow', 'chartreuse')
... | the_stack_v2_python_sparse | students/douglas_klos/session6/lab/test_args_kwargs_lab.py | pauleclifton/GP_Python210B_Winter_2019 | train | 0 |
4c8cbfd58685863273a020ecf104507eeec67607 | [
"s_set = set(s)\nt_set = set(t)\nif s_set != t_set:\n return False\nif all((s.count(letter) == t.count(letter) for letter in s_set)):\n return True\nelse:\n return False",
"res = []\np_set = set(p)\nstart = 0\nend = 0\nlen_p = len(p)\nwhile start <= len(s) - len_p and end < len(s):\n while start <= le... | <|body_start_0|>
s_set = set(s)
t_set = set(t)
if s_set != t_set:
return False
if all((s.count(letter) == t.count(letter) for letter in s_set)):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
res = []
p_set = se... | Thoughts: Time Exceed, try to use update dict method | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
"""Thoughts: Time Exceed, try to use update dict method"""
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_034622 | 3,719 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram",
"signature": "def isAnagram(self, s, t)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013562 | Implement the Python class `Solution_1` described below.
Class description:
Thoughts: Time Exceed, try to use update dict method
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution_1` described below.
Class description:
Thoughts: Time Exceed, try to use update dict method
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Solution_1:
"""Thoughts: Time Exceed, try to use update dict method"""
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_1:
"""Thoughts: Time Exceed, try to use update dict method"""
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
s_set = set(s)
t_set = set(t)
if s_set != t_set:
return False
if all((s.count(letter) == t.count(letter) for l... | the_stack_v2_python_sparse | Python/FindAllAnagramsinaString.py | here0009/LeetCode | train | 1 |
5d1fe599a6391946e8f3101eeb4c563d60cd4106 | [
"response = self.client.get('/api/rankings/55')\nself.assertEqual(response.status_code, 400, msg=f'{BColors.FAIL}\\t[-]\\tResponse was not 400 for too large numbers!{BColors.ENDC}')\nprint(f'{BColors.OKGREEN}\\t[+]\\tPass returning the correct response code for too many players.{BColors.ENDC}')\nresponse2 = self.cl... | <|body_start_0|>
response = self.client.get('/api/rankings/55')
self.assertEqual(response.status_code, 400, msg=f'{BColors.FAIL}\t[-]\tResponse was not 400 for too large numbers!{BColors.ENDC}')
print(f'{BColors.OKGREEN}\t[+]\tPass returning the correct response code for too many players.{BColor... | Tests the API call for getting top n ranking players | Rankings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rankings:
"""Tests the API call for getting top n ranking players"""
def test_invalid_api_request(self):
"""Invalid API request. Too many or too few players requested"""
<|body_0|>
def test_top_n(self):
"""Test getting top n players"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_034623 | 2,885 | permissive | [
{
"docstring": "Invalid API request. Too many or too few players requested",
"name": "test_invalid_api_request",
"signature": "def test_invalid_api_request(self)"
},
{
"docstring": "Test getting top n players",
"name": "test_top_n",
"signature": "def test_top_n(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013541 | Implement the Python class `Rankings` described below.
Class description:
Tests the API call for getting top n ranking players
Method signatures and docstrings:
- def test_invalid_api_request(self): Invalid API request. Too many or too few players requested
- def test_top_n(self): Test getting top n players | Implement the Python class `Rankings` described below.
Class description:
Tests the API call for getting top n ranking players
Method signatures and docstrings:
- def test_invalid_api_request(self): Invalid API request. Too many or too few players requested
- def test_top_n(self): Test getting top n players
<|skelet... | a47c849ea97763eff1005273a58aa3d8ab663ff2 | <|skeleton|>
class Rankings:
"""Tests the API call for getting top n ranking players"""
def test_invalid_api_request(self):
"""Invalid API request. Too many or too few players requested"""
<|body_0|>
def test_top_n(self):
"""Test getting top n players"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rankings:
"""Tests the API call for getting top n ranking players"""
def test_invalid_api_request(self):
"""Invalid API request. Too many or too few players requested"""
response = self.client.get('/api/rankings/55')
self.assertEqual(response.status_code, 400, msg=f'{BColors.FAIL}... | the_stack_v2_python_sparse | home_page/api/tests_api.py | Plongesam/data-structures-game | train | 2 |
a7f1074a294d42958601036409aa0328bb961ce4 | [
"self._queue = Queue()\nself._sock_lock = threading.Lock()\nself._sock = sock\nself._req_buffer = bytearray(1000000)\nself._req_mv = memoryview(self._req_buffer)\nself._refs = {}\nself._ref_count = 1\nself._MAX_TO_PROCESS = 100",
"packer = msgpack.Packer()\nunpacker = msgpack.Unpacker()\nwith self._sock_lock:\n ... | <|body_start_0|>
self._queue = Queue()
self._sock_lock = threading.Lock()
self._sock = sock
self._req_buffer = bytearray(1000000)
self._req_mv = memoryview(self._req_buffer)
self._refs = {}
self._ref_count = 1
self._MAX_TO_PROCESS = 100
<|end_body_0|>
<|b... | FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages down this one socket. Calls to req place message tuples on a shared queue, and ther... | ClientChannel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientChannel:
"""FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages down this one socket. Calls to req place m... | stack_v2_sparse_classes_36k_train_034624 | 3,343 | permissive | [
{
"docstring": "Sets up message tuple queue to remote.",
"name": "__init__",
"signature": "def __init__(self, sock)"
},
{
"docstring": "Sends data to the other side and waits for a response. If no response within timeout period (or connection failure) then raises an error.",
"name": "req",
... | 2 | stack_v2_sparse_classes_30k_train_009124 | Implement the Python class `ClientChannel` described below.
Class description:
FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages dow... | Implement the Python class `ClientChannel` described below.
Class description:
FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages dow... | 91923ed10bee4b2f084b156b31d4e4700bf2326c | <|skeleton|>
class ClientChannel:
"""FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages down this one socket. Calls to req place m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientChannel:
"""FIXME, fix all the docs Channels are connections to another participant. They maintain a message queue and push only one at a time. A couple implementation notes: - We maintain a single connection to the remote end and push all messages down this one socket. Calls to req place message tuples... | the_stack_v2_python_sparse | experiments/messaging/custom/mbus.py | bobquest33/wade | train | 0 |
793831c3424c39ec0f1623462f6b72c8dfb37027 | [
"product = Product.query.get(id)\nif product:\n return product\napi.abort(404)",
"args = parser.parse_args()\nCart.add_to_currentuser_cart(args['quantity'], args['variant_id'])\nres = {'cart_lines': len(current_user.cart.lines)}\nreturn (res, 201)"
] | <|body_start_0|>
product = Product.query.get(id)
if product:
return product
api.abort(404)
<|end_body_0|>
<|body_start_1|>
args = parser.parse_args()
Cart.add_to_currentuser_cart(args['quantity'], args['variant_id'])
res = {'cart_lines': len(current_user.cart... | ProductDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductDetail:
def get(self, id):
"""Fetch a product"""
<|body_0|>
def post(self, id):
"""post product to current user cart"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
product = Product.query.get(id)
if product:
return produc... | stack_v2_sparse_classes_36k_train_034625 | 2,921 | permissive | [
{
"docstring": "Fetch a product",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "post product to current user cart",
"name": "post",
"signature": "def post(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010877 | Implement the Python class `ProductDetail` described below.
Class description:
Implement the ProductDetail class.
Method signatures and docstrings:
- def get(self, id): Fetch a product
- def post(self, id): post product to current user cart | Implement the Python class `ProductDetail` described below.
Class description:
Implement the ProductDetail class.
Method signatures and docstrings:
- def get(self, id): Fetch a product
- def post(self, id): post product to current user cart
<|skeleton|>
class ProductDetail:
def get(self, id):
"""Fetch a... | 0e5f60b1ef6986e01e8ffc172a3ea0f42ab828e7 | <|skeleton|>
class ProductDetail:
def get(self, id):
"""Fetch a product"""
<|body_0|>
def post(self, id):
"""post product to current user cart"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductDetail:
def get(self, id):
"""Fetch a product"""
product = Product.query.get(id)
if product:
return product
api.abort(404)
def post(self, id):
"""post product to current user cart"""
args = parser.parse_args()
Cart.add_to_currentu... | the_stack_v2_python_sparse | flaskshop/api/product.py | UnknownFX02/flask-shop | train | 0 | |
73518cb01ee0bc33dcf8578a349d5b6411a1ba4c | [
"try:\n return {**self.META_FIELD_FALLBACK_CONF, **self.TEASER_FIELD_FALLBACK_CONF}\nexcept AttributeError:\n return self.TEASER_FIELD_FALLBACK_CONF",
"from allink_core.apps.config.utils import get_fallback\nteaser_context = {'teaser_title': get_fallback(self, 'teaser_title'), 'teaser_technical_title': get_... | <|body_start_0|>
try:
return {**self.META_FIELD_FALLBACK_CONF, **self.TEASER_FIELD_FALLBACK_CONF}
except AttributeError:
return self.TEASER_FIELD_FALLBACK_CONF
<|end_body_0|>
<|body_start_1|>
from allink_core.apps.config.utils import get_fallback
teaser_context =... | Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ... | AllinkTeaserMixin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllinkTeaserMixin:
"""Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ..."""
def field_fallback_conf(self):
"""the get_fall... | stack_v2_sparse_classes_36k_train_034626 | 11,084 | permissive | [
{
"docstring": "the get_fallback function is interested in both META_FIELD_FALLBACK_CONF and TEASER_FIELD_FALLBACK_CONF but it is not guaranteed, that AllinkMetaTagMixin and AllinkTeaserMixin are used together.",
"name": "field_fallback_conf",
"signature": "def field_fallback_conf(self)"
},
{
"d... | 2 | null | Implement the Python class `AllinkTeaserMixin` described below.
Class description:
Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ...
Method signatures and ... | Implement the Python class `AllinkTeaserMixin` described below.
Class description:
Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ...
Method signatures and ... | 710ad306ebf681dadcbb58a5d36321025a33c2dc | <|skeleton|>
class AllinkTeaserMixin:
"""Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ..."""
def field_fallback_conf(self):
"""the get_fall... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllinkTeaserMixin:
"""Mixin for all relevant teaser fields. Defines the fallback hierarchy. Used in combination with: AllinkTeaserFieldsModel, AllinkTeaserTranslatedFieldsModel override TEASER_FIELD_FALLBACK_CONF on per app basis: ..."""
def field_fallback_conf(self):
"""the get_fallback function... | the_stack_v2_python_sparse | allink_core/core/models/mixins.py | allink/allink-core | train | 7 |
a850a8fa466cfcb539b0eabc41059e6a6cbc9a51 | [
"name = http.request.params.get('name', None)\nmodel = http.request.env['metro_park_base.location']\nreturn model.get_location_by_name(name)",
"placeholder = functools.partial(get_resource_path, 'metro_park_base', 'static', 'img')\nresponse = http.send_file(placeholder('logo.png'))\nreturn response",
"alias = h... | <|body_start_0|>
name = http.request.params.get('name', None)
model = http.request.env['metro_park_base.location']
return model.get_location_by_name(name)
<|end_body_0|>
<|body_start_1|>
placeholder = functools.partial(get_resource_path, 'metro_park_base', 'static', 'img')
respo... | 基础接口 | MetroParkBaseController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
<|body_0|>
def company_logo(self, dbname=None, **kw):
"""更改默认logo :param dbname: :param kw: :return:"""
<|body_1|>
def get_rail_state(... | stack_v2_sparse_classes_36k_train_034627 | 6,610 | no_license | [
{
"docstring": "根据名称取得位置信息 :param kw: :return:",
"name": "get_location_info_by_name",
"signature": "def get_location_info_by_name(self, **kw)"
},
{
"docstring": "更改默认logo :param dbname: :param kw: :return:",
"name": "company_logo",
"signature": "def company_logo(self, dbname=None, **kw)"... | 3 | stack_v2_sparse_classes_30k_test_000084 | Implement the Python class `MetroParkBaseController` described below.
Class description:
基础接口
Method signatures and docstrings:
- def get_location_info_by_name(self, **kw): 根据名称取得位置信息 :param kw: :return:
- def company_logo(self, dbname=None, **kw): 更改默认logo :param dbname: :param kw: :return:
- def get_rail_state(self... | Implement the Python class `MetroParkBaseController` described below.
Class description:
基础接口
Method signatures and docstrings:
- def get_location_info_by_name(self, **kw): 根据名称取得位置信息 :param kw: :return:
- def company_logo(self, dbname=None, **kw): 更改默认logo :param dbname: :param kw: :return:
- def get_rail_state(self... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
<|body_0|>
def company_logo(self, dbname=None, **kw):
"""更改默认logo :param dbname: :param kw: :return:"""
<|body_1|>
def get_rail_state(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetroParkBaseController:
"""基础接口"""
def get_location_info_by_name(self, **kw):
"""根据名称取得位置信息 :param kw: :return:"""
name = http.request.params.get('name', None)
model = http.request.env['metro_park_base.location']
return model.get_location_by_name(name)
def company_lo... | the_stack_v2_python_sparse | mdias_addons/metro_park_base/controllers/controllers.py | rezaghanimi/main_mdias | train | 0 |
9aede653279a734d7662845cc19b49d512579e44 | [
"if not p and (not q):\n return True\nif not p or not q:\n return False\nstack = []\nstack.append(p)\nstack.append(q)\nwhile stack:\n cur_p = stack.pop(0)\n cur_q = stack.pop(0)\n if cur_p.val != cur_q.val:\n return False\n if cur_p.left and cur_q.left:\n stack.append(cur_p.left)\n ... | <|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return False
stack = []
stack.append(p)
stack.append(q)
while stack:
cur_p = stack.pop(0)
cur_q = stack.pop(0)
if cur_p.val != cur_q.val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool 迭代"""
<|body_0|>
def isSameTree1(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p and ... | stack_v2_sparse_classes_36k_train_034628 | 1,804 | no_license | [
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool 迭代",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree1",
"signature": "def isSameTree1(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013754 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool 迭代
- def isSameTree1(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool 迭代
- def isSameTree1(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
clas... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool 迭代"""
<|body_0|>
def isSameTree1(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool 迭代"""
if not p and (not q):
return True
if not p or not q:
return False
stack = []
stack.append(p)
stack.append(q)
while stack:
... | the_stack_v2_python_sparse | 100.相同的树.py | yangyuxiang1996/leetcode | train | 0 | |
dd811b1b26d95c3097d589c43773a4b0fbb54725 | [
"if letter.islower():\n if letter == 'z':\n letter = 'A'\n else:\n letter = chr(ord(letter) + 1).upper()\nelif letter == 'Z':\n letter = 'a'\nelse:\n letter = chr(ord(letter) + 1).lower()\nreturn letter",
"if letter.islower():\n if letter == 'a':\n letter = 'Z'\n else:\n ... | <|body_start_0|>
if letter.islower():
if letter == 'z':
letter = 'A'
else:
letter = chr(ord(letter) + 1).upper()
elif letter == 'Z':
letter = 'a'
else:
letter = chr(ord(letter) + 1).lower()
return letter
<|en... | Encrytion_decryption | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
<|body_0|>
def letter_decryption(self, letter):
"""对字母的解密方法"""
<|body_1|>
def digit_encryption(self, num):
"""对数字的加密方法"""
<|body_2|>
def digit_decryption(self, n... | stack_v2_sparse_classes_36k_train_034629 | 1,285 | no_license | [
{
"docstring": "对字母的加密",
"name": "letter_encryption",
"signature": "def letter_encryption(self, letter)"
},
{
"docstring": "对字母的解密方法",
"name": "letter_decryption",
"signature": "def letter_decryption(self, letter)"
},
{
"docstring": "对数字的加密方法",
"name": "digit_encryption",
... | 4 | stack_v2_sparse_classes_30k_train_015528 | Implement the Python class `Encrytion_decryption` described below.
Class description:
Implement the Encrytion_decryption class.
Method signatures and docstrings:
- def letter_encryption(self, letter): 对字母的加密
- def letter_decryption(self, letter): 对字母的解密方法
- def digit_encryption(self, num): 对数字的加密方法
- def digit_decryp... | Implement the Python class `Encrytion_decryption` described below.
Class description:
Implement the Encrytion_decryption class.
Method signatures and docstrings:
- def letter_encryption(self, letter): 对字母的加密
- def letter_decryption(self, letter): 对字母的解密方法
- def digit_encryption(self, num): 对数字的加密方法
- def digit_decryp... | 1d37ef796e2f01b29a8b9a3924b0db5dd8f312cc | <|skeleton|>
class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
<|body_0|>
def letter_decryption(self, letter):
"""对字母的解密方法"""
<|body_1|>
def digit_encryption(self, num):
"""对数字的加密方法"""
<|body_2|>
def digit_decryption(self, n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
if letter.islower():
if letter == 'z':
letter = 'A'
else:
letter = chr(ord(letter) + 1).upper()
elif letter == 'Z':
letter = 'a'
else:
... | the_stack_v2_python_sparse | huaweiTest/encryption_decryption.py | moguoyi/httpApi | train | 0 | |
c728956950319ebd3aa62d0f3c84d3def910f833 | [
"self.netName = net_name\nself.net = net\nself.criterion = criterion\nself.optimizer = optimizer\nself.environmentExtractor = environment_extractor\nself.sensor = sensor\nself.shortTermMemory = short_term_memory\nself.replayMemory = replay_memory\nself.explorationPolicy = exploration_policy\nself.rewardProcessor = ... | <|body_start_0|>
self.netName = net_name
self.net = net
self.criterion = criterion
self.optimizer = optimizer
self.environmentExtractor = environment_extractor
self.sensor = sensor
self.shortTermMemory = short_term_memory
self.replayMemory = replay_memory
... | Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memory -> [replay_memory] [replay_memory] -> minibatch -> [minibatch_preparation] ... | AgentProxy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentProxy:
"""Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memory -> [replay_memory] [replay_memory] ->... | stack_v2_sparse_classes_36k_train_034630 | 5,979 | no_license | [
{
"docstring": "Setup of the proxy :param net_name: name of the network - needed for load and save :param net: model which should act as the agents brain :param criterion: loss function which is used during training :param optimizer: optimizer which is used during training :param environment_extractor: extracts... | 5 | stack_v2_sparse_classes_30k_train_007693 | Implement the Python class `AgentProxy` described below.
Class description:
Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memor... | Implement the Python class `AgentProxy` described below.
Class description:
Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memor... | 5db378c85efb030fabcd0a3fde4c33a127007260 | <|skeleton|>
class AgentProxy:
"""Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memory -> [replay_memory] [replay_memory] ->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentProxy:
"""Proxy for the bomberman agent This class contains the complete workflow of the agent. Act (implemented in __call__): raw environment -> [sensor] -> perception -> [policy] -> [net] -> action Update (implemented in update, __create_memory) memory -> [replay_memory] [replay_memory] -> minibatch ->... | the_stack_v2_python_sparse | agent_code/dqn_agent/proxies.py | Ctoffer/Bomberman_RL | train | 0 |
a8a935143bcdc065a0695e5bd358af99cbd5d8cd | [
"if not exactly_one(destination_table_definition, destination_sql):\n raise ETLInputError('One of dest table or dest sql needed')\nif script_arguments is None:\n script_arguments = list()\nif sql_tail_for_source is None:\n sql_tail_for_source = ''\ndest_sql, primary_key_index = self.convert_destination_to_... | <|body_start_0|>
if not exactly_one(destination_table_definition, destination_sql):
raise ETLInputError('One of dest table or dest sql needed')
if script_arguments is None:
script_arguments = list()
if sql_tail_for_source is None:
sql_tail_for_source = ''
... | ColumnCheckStep class that checks if the rows of a table has been populated with the correct values | ColumnCheckStep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnCheckStep:
"""ColumnCheckStep class that checks if the rows of a table has been populated with the correct values"""
def __init__(self, id, source_sql, source_host, destination_table_definition=None, script=None, destination_sql=None, sql_tail_for_source=None, sample_size=100, toleranc... | stack_v2_sparse_classes_36k_train_034631 | 5,778 | permissive | [
{
"docstring": "Constructor for the ColumnCheckStep class Args: destination_table_definition(file): table definition for the destination table **kwargs(optional): Keyword arguments directly passed to base class",
"name": "__init__",
"signature": "def __init__(self, id, source_sql, source_host, destinati... | 3 | null | Implement the Python class `ColumnCheckStep` described below.
Class description:
ColumnCheckStep class that checks if the rows of a table has been populated with the correct values
Method signatures and docstrings:
- def __init__(self, id, source_sql, source_host, destination_table_definition=None, script=None, desti... | Implement the Python class `ColumnCheckStep` described below.
Class description:
ColumnCheckStep class that checks if the rows of a table has been populated with the correct values
Method signatures and docstrings:
- def __init__(self, id, source_sql, source_host, destination_table_definition=None, script=None, desti... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class ColumnCheckStep:
"""ColumnCheckStep class that checks if the rows of a table has been populated with the correct values"""
def __init__(self, id, source_sql, source_host, destination_table_definition=None, script=None, destination_sql=None, sql_tail_for_source=None, sample_size=100, toleranc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColumnCheckStep:
"""ColumnCheckStep class that checks if the rows of a table has been populated with the correct values"""
def __init__(self, id, source_sql, source_host, destination_table_definition=None, script=None, destination_sql=None, sql_tail_for_source=None, sample_size=100, tolerance=1.0, script... | the_stack_v2_python_sparse | dataduct/steps/column_check.py | EverFi/dataduct | train | 3 |
157c7f970e89f84e3c0c56f4802293b1f009727f | [
"self.logger = logging\nself.root_dir = dh.get_root_dir()\nself.log_dir = None\nself.log_file_path = self.set_logger()\nself.set_logger_handler(filename=self.log_file_path)",
"calling_test = os.environ.get('PYTEST_CURRENT_TEST')\ntarget = re.findall('\\\\[(.*?)\\\\]', calling_test) or ['']\ntarget = target[0]\nfi... | <|body_start_0|>
self.logger = logging
self.root_dir = dh.get_root_dir()
self.log_dir = None
self.log_file_path = self.set_logger()
self.set_logger_handler(filename=self.log_file_path)
<|end_body_0|>
<|body_start_1|>
calling_test = os.environ.get('PYTEST_CURRENT_TEST')
... | This is a wrapper around the logging module. | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
"""This is a wrapper around the logging module."""
def __init__(self):
"""This is the constructor for Logging."""
<|body_0|>
def set_logger(self, by_time=False):
"""This sets up the logging directories and file paths. Args: by_time (bool): Whether to keep... | stack_v2_sparse_classes_36k_train_034632 | 2,240 | permissive | [
{
"docstring": "This is the constructor for Logging.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This sets up the logging directories and file paths. Args: by_time (bool): Whether to keep all successive runs by time. Returns: log_file_path: The path of the log file... | 3 | stack_v2_sparse_classes_30k_train_005700 | Implement the Python class `Logger` described below.
Class description:
This is a wrapper around the logging module.
Method signatures and docstrings:
- def __init__(self): This is the constructor for Logging.
- def set_logger(self, by_time=False): This sets up the logging directories and file paths. Args: by_time (b... | Implement the Python class `Logger` described below.
Class description:
This is a wrapper around the logging module.
Method signatures and docstrings:
- def __init__(self): This is the constructor for Logging.
- def set_logger(self, by_time=False): This sets up the logging directories and file paths. Args: by_time (b... | 815f606de1b7f43890a0313dcd0581273acd3952 | <|skeleton|>
class Logger:
"""This is a wrapper around the logging module."""
def __init__(self):
"""This is the constructor for Logging."""
<|body_0|>
def set_logger(self, by_time=False):
"""This sets up the logging directories and file paths. Args: by_time (bool): Whether to keep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logger:
"""This is a wrapper around the logging module."""
def __init__(self):
"""This is the constructor for Logging."""
self.logger = logging
self.root_dir = dh.get_root_dir()
self.log_dir = None
self.log_file_path = self.set_logger()
self.set_logger_hand... | the_stack_v2_python_sparse | uiautomationtools/logging/logger.py | webclinic017/ui-automation-tools-mbt | train | 0 |
d2de77d23387930ecf99adda4c4c1deb2b7d47da | [
"super(AuditLog, self).__init__()\nself._listeners = []\nself._logger = logging.getLogger('lostservice.logger.auditlog.AuditLog')",
"self._logger.info('recording event')\nself._logger.debug(event)\nfor listener in self._listeners:\n listener.record_event(event)",
"self._logger.info('registering listener')\ns... | <|body_start_0|>
super(AuditLog, self).__init__()
self._listeners = []
self._logger = logging.getLogger('lostservice.logger.auditlog.AuditLog')
<|end_body_0|>
<|body_start_1|>
self._logger.info('recording event')
self._logger.debug(event)
for listener in self._listeners:... | Class for handling audit logger. | AuditLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditLog:
"""Class for handling audit logger."""
def __init__(self):
"""Constructor."""
<|body_0|>
def record_event(self, event):
"""Records the given event with all registered listeners. :param event: The event to record. :type event: :py:class:`lostservice.logg... | stack_v2_sparse_classes_36k_train_034633 | 2,089 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Records the given event with all registered listeners. :param event: The event to record. :type event: :py:class:`lostservice.logging.auditlog.AuditableEvent`",
"name": "record_event",
... | 3 | stack_v2_sparse_classes_30k_val_001155 | Implement the Python class `AuditLog` described below.
Class description:
Class for handling audit logger.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def record_event(self, event): Records the given event with all registered listeners. :param event: The event to record. :type event: :py:cl... | Implement the Python class `AuditLog` described below.
Class description:
Class for handling audit logger.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def record_event(self, event): Records the given event with all registered listeners. :param event: The event to record. :type event: :py:cl... | 5a41d09a922f0b239893c99ae9a9626f020bf3f9 | <|skeleton|>
class AuditLog:
"""Class for handling audit logger."""
def __init__(self):
"""Constructor."""
<|body_0|>
def record_event(self, event):
"""Records the given event with all registered listeners. :param event: The event to record. :type event: :py:class:`lostservice.logg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditLog:
"""Class for handling audit logger."""
def __init__(self):
"""Constructor."""
super(AuditLog, self).__init__()
self._listeners = []
self._logger = logging.getLogger('lostservice.logger.auditlog.AuditLog')
def record_event(self, event):
"""Records the... | the_stack_v2_python_sparse | lostservice/logger/auditlog.py | ravinash496/lostservice | train | 1 |
d0622ec9a9fb891ae2c9a0a875e3f0e5666725ed | [
"self.video_vis = video_vis\nself.task_queue = task_queue\nself.result_queue = result_queue\nsuper().__init__()",
"while True:\n task = self.task_queue.get()\n if isinstance(task, _StopToken):\n break\n frames = draw_predictions(task, self.video_vis)\n task.frames = np.array(frames)\n self.r... | <|body_start_0|>
self.video_vis = video_vis
self.task_queue = task_queue
self.result_queue = result_queue
super().__init__()
<|end_body_0|>
<|body_start_1|>
while True:
task = self.task_queue.get()
if isinstance(task, _StopToken):
break
... | _VisWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _VisWorker:
def __init__(self, video_vis, task_queue, result_queue):
"""Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a ... | stack_v2_sparse_classes_36k_train_034634 | 9,808 | permissive | [
{
"docstring": "Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue for visualized results.",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_017223 | Implement the Python class `_VisWorker` described below.
Class description:
Implement the _VisWorker class.
Method signatures and docstrings:
- def __init__(self, video_vis, task_queue, result_queue): Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. tas... | Implement the Python class `_VisWorker` described below.
Class description:
Implement the _VisWorker class.
Method signatures and docstrings:
- def __init__(self, video_vis, task_queue, result_queue): Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. tas... | 6092dad7be32bb1d6b71fe1bade258dc8b492fe3 | <|skeleton|>
class _VisWorker:
def __init__(self, video_vis, task_queue, result_queue):
"""Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _VisWorker:
def __init__(self, video_vis, task_queue, result_queue):
"""Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue f... | the_stack_v2_python_sparse | slowfast/visualization/async_predictor.py | facebookresearch/SlowFast | train | 6,221 | |
7761259dab72aad87d471ba08bf6310965a2fbd9 | [
"context = super(HelpDetailView, self).get_context_data(**kwargs)\nobj = self.get_object()\nqueryset = self.get_queryset().filter(db_help_category=obj.db_help_category).order_by(Lower('db_key'))\ncontext['topic_list'] = queryset\nobjs = list(queryset)\nfor i, x in enumerate(objs):\n if obj is x:\n break\n... | <|body_start_0|>
context = super(HelpDetailView, self).get_context_data(**kwargs)
obj = self.get_object()
queryset = self.get_queryset().filter(db_help_category=obj.db_help_category).order_by(Lower('db_key'))
context['topic_list'] = queryset
objs = list(queryset)
for i, x... | Returns the detail page for a given help entry. | HelpDetailView | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpDetailView:
"""Returns the detail page for a given help entry."""
def get_context_data(self, **kwargs):
"""Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: context (dict): Django context object"""
<|body_0|... | stack_v2_sparse_classes_36k_train_034635 | 35,922 | permissive | [
{
"docstring": "Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: context (dict): Django context object",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Override of Django hook th... | 2 | null | Implement the Python class `HelpDetailView` described below.
Class description:
Returns the detail page for a given help entry.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: c... | Implement the Python class `HelpDetailView` described below.
Class description:
Returns the detail page for a given help entry.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: c... | 5e97df013399e1a401d0a7ec184c4b9eb3100edd | <|skeleton|>
class HelpDetailView:
"""Returns the detail page for a given help entry."""
def get_context_data(self, **kwargs):
"""Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: context (dict): Django context object"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelpDetailView:
"""Returns the detail page for a given help entry."""
def get_context_data(self, **kwargs):
"""Adds navigational data to the template to let browsers go to the next or previous entry in the help list. Returns: context (dict): Django context object"""
context = super(HelpDe... | the_stack_v2_python_sparse | evennia-engine/evennia/evennia/web/website/views.py | rajammanabrolu/WorldGeneration | train | 69 |
44d160bd335180af752386c8ffa6662bacf81c5c | [
"self._dbg = debug\nself._log = get_logger(self.__class__.__name__, self._dbg)\nself._port = port\nself._wav_mode = wav_mode\nself._wavdir = wavdir\nself._svr = WsServer(wav_mode=self._wav_mode, port=self._port, wavdir=self._wavdir, debug=self._dbg)",
"self._log.debug('start')\nself._svr.main()\nself._log.debug('... | <|body_start_0|>
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._port = port
self._wav_mode = wav_mode
self._wavdir = wavdir
self._svr = WsServer(wav_mode=self._wav_mode, port=self._port, wavdir=self._wavdir, debug=self._dbg)
<|end_body_... | Music Box Websocket Server App | WsServerApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WsServerApp:
"""Music Box Websocket Server App"""
def __init__(self, port, wav_mode, wavdir, debug=False):
"""Constructor Parameters ---------- port: int wav_mode: int wavdir: str"""
<|body_0|>
def main(self):
"""main"""
<|body_1|>
def end(self):
... | stack_v2_sparse_classes_36k_train_034636 | 25,197 | no_license | [
{
"docstring": "Constructor Parameters ---------- port: int wav_mode: int wavdir: str",
"name": "__init__",
"signature": "def __init__(self, port, wav_mode, wavdir, debug=False)"
},
{
"docstring": "main",
"name": "main",
"signature": "def main(self)"
},
{
"docstring": "end: Call ... | 3 | stack_v2_sparse_classes_30k_train_002112 | Implement the Python class `WsServerApp` described below.
Class description:
Music Box Websocket Server App
Method signatures and docstrings:
- def __init__(self, port, wav_mode, wavdir, debug=False): Constructor Parameters ---------- port: int wav_mode: int wavdir: str
- def main(self): main
- def end(self): end: Ca... | Implement the Python class `WsServerApp` described below.
Class description:
Music Box Websocket Server App
Method signatures and docstrings:
- def __init__(self, port, wav_mode, wavdir, debug=False): Constructor Parameters ---------- port: int wav_mode: int wavdir: str
- def main(self): main
- def end(self): end: Ca... | b8264118d19c7f6c6be9b11f18c890c598eb1295 | <|skeleton|>
class WsServerApp:
"""Music Box Websocket Server App"""
def __init__(self, port, wav_mode, wavdir, debug=False):
"""Constructor Parameters ---------- port: int wav_mode: int wavdir: str"""
<|body_0|>
def main(self):
"""main"""
<|body_1|>
def end(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WsServerApp:
"""Music Box Websocket Server App"""
def __init__(self, port, wav_mode, wavdir, debug=False):
"""Constructor Parameters ---------- port: int wav_mode: int wavdir: str"""
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._port = ... | the_stack_v2_python_sparse | musicbox/__main__.py | ytani01/MusicBox | train | 1 |
5716b5f02e9f550df441f371313598e695e5933e | [
"if request.user.is_authenticated:\n stops = UserStop.objects.filter(station_user=request.user)\n stops = list(stops)\n stop_list = [stop.stop for stop in stops]\n json_file = {'user_stop_list': stop_list, 'res': 1}\n return JsonResponse(json_file)\nelse:\n return JsonResponse({'res': 0, 'error_ms... | <|body_start_0|>
if request.user.is_authenticated:
stops = UserStop.objects.filter(station_user=request.user)
stops = list(stops)
stop_list = [stop.stop for stop in stops]
json_file = {'user_stop_list': stop_list, 'res': 1}
return JsonResponse(json_fil... | store the favorite stops of user | FavoriteStopView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteStopView:
"""store the favorite stops of user"""
def get(self, request):
"""return the user's favortie stop list"""
<|body_0|>
def post(self, request):
"""add new stop information"""
<|body_1|>
def delete(self, request):
"""remove the... | stack_v2_sparse_classes_36k_train_034637 | 28,206 | no_license | [
{
"docstring": "return the user's favortie stop list",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "add new stop information",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "remove the stop from the favorite list",
"name":... | 3 | stack_v2_sparse_classes_30k_train_019510 | Implement the Python class `FavoriteStopView` described below.
Class description:
store the favorite stops of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie stop list
- def post(self, request): add new stop information
- def delete(self, request): remove the stop from the ... | Implement the Python class `FavoriteStopView` described below.
Class description:
store the favorite stops of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie stop list
- def post(self, request): add new stop information
- def delete(self, request): remove the stop from the ... | 5efeebedd4695ef9d904beb707a1538ba049b187 | <|skeleton|>
class FavoriteStopView:
"""store the favorite stops of user"""
def get(self, request):
"""return the user's favortie stop list"""
<|body_0|>
def post(self, request):
"""add new stop information"""
<|body_1|>
def delete(self, request):
"""remove the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FavoriteStopView:
"""store the favorite stops of user"""
def get(self, request):
"""return the user's favortie stop list"""
if request.user.is_authenticated:
stops = UserStop.objects.filter(station_user=request.user)
stops = list(stops)
stop_list = [sto... | the_stack_v2_python_sparse | dbbus/apps/user/views.py | mofiebiger/DublinBus | train | 1 |
1bf36e0a628b420712ed774573a5788398be10fb | [
"self.dir = dir\nself.tstRatio = tstRatio\nself.batch_size = batch_size\nsplit_test_train_data(dir, tstRatio)\ntrnTransform = data_transforms['train']\nself.trainSet = DroneDataset(train=True, transform=trnTransform)\ntstTransform = data_transforms['val']\nself.testSet = DroneDataset(train=False, transform=tstTrans... | <|body_start_0|>
self.dir = dir
self.tstRatio = tstRatio
self.batch_size = batch_size
split_test_train_data(dir, tstRatio)
trnTransform = data_transforms['train']
self.trainSet = DroneDataset(train=True, transform=trnTransform)
tstTransform = data_transforms['val'... | A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders | LoadDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadDataset:
"""A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders"""
def __init__(s... | stack_v2_sparse_classes_36k_train_034638 | 9,192 | permissive | [
{
"docstring": "Initialize the class object. Dataset class ojbect",
"name": "__init__",
"signature": "def __init__(self, dir, tstRatio, batch_size)"
},
{
"docstring": "Show five sample images for verification of dataloaders. Get item internal fuction",
"name": "show_batch",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_016222 | Implement the Python class `LoadDataset` described below.
Class description:
A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verificatio... | Implement the Python class `LoadDataset` described below.
Class description:
A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verificatio... | 7c551e3894979cc425dd51baeddbfa5a51b7878d | <|skeleton|>
class LoadDataset:
"""A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders"""
def __init__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadDataset:
"""A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders"""
def __init__(self, dir, tst... | the_stack_v2_python_sparse | Modules/data_loader.py | EVA4-RS-Group/Phase2 | train | 0 |
904435b8f270fdb7b191e6039da47ce9da99be0f | [
"super().__init__(features_to_sample, **kwargs)\nself.amount = amount\nself.sample_size = tuple(sample_size)\nself.replace = replace",
"feature_type, feature_name = self.features_parser.get_features(eopatch)[0]\nheight, width = eopatch.get_spatial_dimension(feature_type, cast(str, feature_name))\nheight -= self.s... | <|body_start_0|>
super().__init__(features_to_sample, **kwargs)
self.amount = amount
self.sample_size = tuple(sample_size)
self.replace = replace
<|end_body_0|>
<|body_start_1|>
feature_type, feature_name = self.features_parser.get_features(eopatch)[0]
height, width = eo... | A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purposes that require fine-tuning use `FractionSamplingTask` instead. | BlockSamplingTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockSamplingTask:
"""A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purposes that require fine-tuning use `Frac... | stack_v2_sparse_classes_36k_train_034639 | 17,895 | permissive | [
{
"docstring": ":param features_to_sample: Features that will be spatially sampled according to given sampling parameters. :param amount: The number of points to sample if integer valued and the fraction of all points if `float` :param sample_size: A tuple describing a size of sampled blocks. The size is define... | 3 | stack_v2_sparse_classes_30k_train_006711 | Implement the Python class `BlockSamplingTask` described below.
Class description:
A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purp... | Implement the Python class `BlockSamplingTask` described below.
Class description:
A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purp... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class BlockSamplingTask:
"""A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purposes that require fine-tuning use `Frac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockSamplingTask:
"""A task to randomly sample pixels or blocks of any size. The task has no option to add data validity masks, because when sampling a fixed amount of objects it can cause uneven distribution density across different eopatches. For any purposes that require fine-tuning use `FractionSamplingT... | the_stack_v2_python_sparse | ml_tools/eolearn/ml_tools/sampling.py | sentinel-hub/eo-learn | train | 1,072 |
c24a333d4228d3898e8d0ab20b12c8120265dd08 | [
"result = 1\nfor a in args:\n result = result * a\nreturn result",
"if name == 'product':\n return cls(cls.product).get\nelse:\n raise NotImplementedError"
] | <|body_start_0|>
result = 1
for a in args:
result = result * a
return result
<|end_body_0|>
<|body_start_1|>
if name == 'product':
return cls(cls.product).get
else:
raise NotImplementedError
<|end_body_1|>
| Fuzzy norms (conjunctions). | SNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
<|body_0|>
def method(cls, name):
"""Returns callable operator of chosen name. Arguments: name Name of the operator: {'prod... | stack_v2_sparse_classes_36k_train_034640 | 7,372 | no_license | [
{
"docstring": "Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.",
"name": "product",
"signature": "def product(*args)"
},
{
"docstring": "Returns callable operator of chosen name. Arguments: name Name of the operator: {'product'}",
"name": "method",
"signature": ... | 2 | null | Implement the Python class `SNorm` described below.
Class description:
Fuzzy norms (conjunctions).
Method signatures and docstrings:
- def product(*args): Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.
- def method(cls, name): Returns callable operator of chosen name. Arguments: name Name of... | Implement the Python class `SNorm` described below.
Class description:
Fuzzy norms (conjunctions).
Method signatures and docstrings:
- def product(*args): Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.
- def method(cls, name): Returns callable operator of chosen name. Arguments: name Name of... | 1c2c3abe50bd9125b105ffd13eef513839f3f9d8 | <|skeleton|>
class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
<|body_0|>
def method(cls, name):
"""Returns callable operator of chosen name. Arguments: name Name of the operator: {'prod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
result = 1
for a in args:
result = result * a
return result
def method(cls, name):
"""Returns callable opera... | the_stack_v2_python_sparse | monitor/fuzzy.py | martinbenes1996/bc | train | 0 |
0c21b6384b213aa1857f1fc126afe7dc6d635180 | [
"if site_meters is ElecMeter:\n self._check_meter(site_meters)\n if not site_meters.metadata['site_meter']:\n raise RuntimeError('Only site meters can be disaggregated')\nelse:\n for meter in site_meters.all_elecmeters():\n self._check_meter(meter)\n if not ('site_meter' in meter.metad... | <|body_start_0|>
if site_meters is ElecMeter:
self._check_meter(site_meters)
if not site_meters.metadata['site_meter']:
raise RuntimeError('Only site meters can be disaggregated')
else:
for meter in site_meters.all_elecmeters():
self._c... | This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats. | Processing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processing:
"""This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats."""
def _pre_disaggregation_checks(self, sit... | stack_v2_sparse_classes_36k_train_034641 | 2,789 | permissive | [
{
"docstring": "This is the basic check, which is called before disaggregation is performed. It takes care. site_meters: A Group of site meters or a single site-meter",
"name": "_pre_disaggregation_checks",
"signature": "def _pre_disaggregation_checks(self, site_meters, load_kwargs)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_014322 | Implement the Python class `Processing` described below.
Class description:
This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats.
Method s... | Implement the Python class `Processing` described below.
Class description:
This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats.
Method s... | e9b06bcb43a40010ccc40a534a7067ee520fb3a7 | <|skeleton|>
class Processing:
"""This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats."""
def _pre_disaggregation_checks(self, sit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Processing:
"""This is the baseclass for all predictors which process ElecMeters. At the moment disaggregator, clustering and forecasting inherits from this class. Do not confuse it with the node system which is only used for calculating the stats."""
def _pre_disaggregation_checks(self, site_meters, loa... | the_stack_v2_python_sparse | nilmtk/processing.py | BaluJr/energytk | train | 3 |
3bddc36bce399237db71338bbb379ee36e954c76 | [
"self.access_token = 'Bearer ' + access_token\nself.organization_id = organization_id\nself.project_id = project_id\nself.app_id = app_id\nself.service_url = service_url\nself.app_name = ''\nself.paths = paths",
"import requests\nfrom django.conf import settings\nfrom .interface_exception_handler import handle_in... | <|body_start_0|>
self.access_token = 'Bearer ' + access_token
self.organization_id = organization_id
self.project_id = project_id
self.app_id = app_id
self.service_url = service_url
self.app_name = ''
self.paths = paths
<|end_body_0|>
<|body_start_1|>
imp... | SwaggerSpec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwaggerSpec:
def __init__(self, access_token, organization_id, project_id, app_id, service_url, paths):
""":param access_token: :param organization_id: :param project_id: :param app_id: :param service_url: :param paths: Initialize the Swaager spec service with configuration details"""
... | stack_v2_sparse_classes_36k_train_034642 | 4,432 | no_license | [
{
"docstring": ":param access_token: :param organization_id: :param project_id: :param app_id: :param service_url: :param paths: Initialize the Swaager spec service with configuration details",
"name": "__init__",
"signature": "def __init__(self, access_token, organization_id, project_id, app_id, servic... | 4 | null | Implement the Python class `SwaggerSpec` described below.
Class description:
Implement the SwaggerSpec class.
Method signatures and docstrings:
- def __init__(self, access_token, organization_id, project_id, app_id, service_url, paths): :param access_token: :param organization_id: :param project_id: :param app_id: :p... | Implement the Python class `SwaggerSpec` described below.
Class description:
Implement the SwaggerSpec class.
Method signatures and docstrings:
- def __init__(self, access_token, organization_id, project_id, app_id, service_url, paths): :param access_token: :param organization_id: :param project_id: :param app_id: :p... | 7c892873c1221a816a62cdba0fb9ad491cfba261 | <|skeleton|>
class SwaggerSpec:
def __init__(self, access_token, organization_id, project_id, app_id, service_url, paths):
""":param access_token: :param organization_id: :param project_id: :param app_id: :param service_url: :param paths: Initialize the Swaager spec service with configuration details"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwaggerSpec:
def __init__(self, access_token, organization_id, project_id, app_id, service_url, paths):
""":param access_token: :param organization_id: :param project_id: :param app_id: :param service_url: :param paths: Initialize the Swaager spec service with configuration details"""
self.acc... | the_stack_v2_python_sparse | lib/python3.8/site-packages/django_swagger_utils/swagger_gui/swagger_spec.py | ushatirumalasetty/venv | train | 0 | |
85595bfaf85f7fa65e8737348abe471bc5559a59 | [
"self._vgg = tf.keras.applications.VGG19(include_top=False, weights=weights)\nself._vgg.trainable = False\nself._layers = layers\nself._weights = layer_weights\noutput_names = layers\noutputs = [self._vgg.get_layer(name).output for name in output_names]\nself._model = tf.keras.Model([self._vgg.input], outputs)",
... | <|body_start_0|>
self._vgg = tf.keras.applications.VGG19(include_top=False, weights=weights)
self._vgg.trainable = False
self._layers = layers
self._weights = layer_weights
output_names = layers
outputs = [self._vgg.get_layer(name).output for name in output_names]
... | A VGG losss class. | VGGLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_034643 | 1,984 | permissive | [
{
"docstring": "Initializes the VGG network.",
"name": "__init__",
"signature": "def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0))"
},
{
"docstring": "Computes... | 2 | stack_v2_sparse_classes_30k_train_002726 | Implement the Python class `VGGLoss` described below.
Class description:
A VGG losss class.
Method signatures and docstrings:
- def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)): In... | Implement the Python class `VGGLoss` described below.
Class description:
A VGG losss class.
Method signatures and docstrings:
- def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)): In... | a9a6643968a7b6b29cab3b53b73ab80d14fb32b7 | <|skeleton|>
class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
self._vgg = tf.keras.application... | the_stack_v2_python_sparse | losses/vgg_loss.py | czero69/lsr | train | 0 |
1841e5b1f2ee649282d8c28df7c313fe398ff490 | [
"super(SaleShippingRates, self).__init__(*args, **kwargs)\nself.endpoint = 'sale/shipping-rates'\nself.seller_id = None\nself.shipping_rate_id = None\nself._headers = {'Accept': 'application/vnd.allegro.public.v1+json', 'Content-type': 'application/vnd.allegro.public.v1+json'}",
"self.shipping_rate_id = shipping_... | <|body_start_0|>
super(SaleShippingRates, self).__init__(*args, **kwargs)
self.endpoint = 'sale/shipping-rates'
self.seller_id = None
self.shipping_rate_id = None
self._headers = {'Accept': 'application/vnd.allegro.public.v1+json', 'Content-type': 'application/vnd.allegro.public.... | Manage shipping rates (cenniki dostaw) | SaleShippingRates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleShippingRates:
"""Manage shipping rates (cenniki dostaw)"""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def get(self, shipping_rate_id):
"""Get information about specific shipping rate :param shipping_rate_id: The unique id (... | stack_v2_sparse_classes_36k_train_034644 | 1,884 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get information about specific shipping rate :param shipping_rate_id: The unique id (UUID) for the shipping rate. :type shipping_rate_id: :py:class:`str` :return: T... | 3 | stack_v2_sparse_classes_30k_test_001148 | Implement the Python class `SaleShippingRates` described below.
Class description:
Manage shipping rates (cenniki dostaw)
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def get(self, shipping_rate_id): Get information about specific shipping rate :param shipping_rat... | Implement the Python class `SaleShippingRates` described below.
Class description:
Manage shipping rates (cenniki dostaw)
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def get(self, shipping_rate_id): Get information about specific shipping rate :param shipping_rat... | 112b0f2570fcf3840645dd62f6f7150956e56f9c | <|skeleton|>
class SaleShippingRates:
"""Manage shipping rates (cenniki dostaw)"""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def get(self, shipping_rate_id):
"""Get information about specific shipping rate :param shipping_rate_id: The unique id (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaleShippingRates:
"""Manage shipping rates (cenniki dostaw)"""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(SaleShippingRates, self).__init__(*args, **kwargs)
self.endpoint = 'sale/shipping-rates'
self.seller_id = None
self.shipping_rat... | the_stack_v2_python_sparse | allegroapi/entities/saleshippingrates.py | krystianmagdziarz/python-allegro | train | 0 |
d3c65211b08fbfd445bb2306bbde230d4b74429a | [
"super(ESIM, self).__init__()\nself.vocab_size = vocab_size\nself.embedding_dim = embedding_dim\nself.hidden_size = hidden_size\nself.num_classes = num_classes\nself.dropout = dropout\nself.device = device\nself._word_embedding = nn.Embedding(self.vocab_size, self.embedding_dim, padding_idx=padding_idx, _weight=emb... | <|body_start_0|>
super(ESIM, self).__init__()
self.vocab_size = vocab_size
self.embedding_dim = embedding_dim
self.hidden_size = hidden_size
self.num_classes = num_classes
self.dropout = dropout
self.device = device
self._word_embedding = nn.Embedding(self... | Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al. | ESIM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESIM:
"""Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al."""
def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dropout=0.5, num_classes=3, device='cpu'):
"""Args: vocab_size:... | stack_v2_sparse_classes_36k_train_034645 | 30,263 | no_license | [
{
"docstring": "Args: vocab_size: The size of the vocabulary of embeddings in the model. embedding_dim: The dimension of the word embeddings. hidden_size: The size of all the hidden layers in the network. embeddings: A tensor of size (vocab_size, embedding_dim) containing pretrained word embeddings. If None, wo... | 2 | stack_v2_sparse_classes_30k_train_017556 | Implement the Python class `ESIM` described below.
Class description:
Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dro... | Implement the Python class `ESIM` described below.
Class description:
Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dro... | e52909f401279351d1589cb8b755d30b38ae0091 | <|skeleton|>
class ESIM:
"""Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al."""
def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dropout=0.5, num_classes=3, device='cpu'):
"""Args: vocab_size:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESIM:
"""Implementation of the ESIM model presented in the paper "Enhanced LSTM for Natural Language Inference" by Chen et al."""
def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dropout=0.5, num_classes=3, device='cpu'):
"""Args: vocab_size: The size of ... | the_stack_v2_python_sparse | code/model.py | FairyFali/macer-certified-word-sub-2.0 | train | 0 |
a01bd5e586e163aaf648285611e850cf15ed60dd | [
"self.pygm = pygm\nself.screen = self.pygm.screen\nself.blitimg = self.pygm.blitimg\nself.blittxt = self.pygm.blittxt\nself.mic = mic\nself.profile = profile\nself.modules = self.get_modules()\nself._logger = logging.getLogger(__name__)\nself.background = self.pygm.background",
"logger = logging.getLogger(__name_... | <|body_start_0|>
self.pygm = pygm
self.screen = self.pygm.screen
self.blitimg = self.pygm.blitimg
self.blittxt = self.pygm.blittxt
self.mic = mic
self.profile = profile
self.modules = self.get_modules()
self._logger = logging.getLogger(__name__)
se... | Brain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brain:
def __init__(self, mic, profile, pygm):
"""Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will cease execution on the first module that accepts a given input. Arguments: mic -- u... | stack_v2_sparse_classes_36k_train_034646 | 5,648 | permissive | [
{
"docstring": "Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will cease execution on the first module that accepts a given input. Arguments: mic -- used to interact with the user (for both input and output) ... | 3 | stack_v2_sparse_classes_30k_train_007484 | Implement the Python class `Brain` described below.
Class description:
Implement the Brain class.
Method signatures and docstrings:
- def __init__(self, mic, profile, pygm): Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the ... | Implement the Python class `Brain` described below.
Class description:
Implement the Brain class.
Method signatures and docstrings:
- def __init__(self, mic, profile, pygm): Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the ... | 12a65146e36462de94e7a05b7df8736fa615a1eb | <|skeleton|>
class Brain:
def __init__(self, mic, profile, pygm):
"""Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will cease execution on the first module that accepts a given input. Arguments: mic -- u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Brain:
def __init__(self, mic, profile, pygm):
"""Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will cease execution on the first module that accepts a given input. Arguments: mic -- used to interac... | the_stack_v2_python_sparse | client/brain.py | DarthToker/jasper-client-TokerWare- | train | 1 | |
356ba88132c2fc2b58dec39dbdc55394b0829333 | [
"self.channel = implementations.insecure_channel(host, int(port))\nself.stub = prediction_service_pb2.beta_create_PredictionService_stub(self.channel)\nself.model_name = model_name\nself.max_detection_size = max_detection_size\nself.max_classification_size = max_classification_size",
"assert isinstance(image, Ima... | <|body_start_0|>
self.channel = implementations.insecure_channel(host, int(port))
self.stub = prediction_service_pb2.beta_create_PredictionService_stub(self.channel)
self.model_name = model_name
self.max_detection_size = max_detection_size
self.max_classification_size = max_class... | ColaDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColaDetector:
def __init__(self, host, port, model_name, max_detection_size=None, max_classification_size=None):
""":param host: str, serving model's host ip or dns :param port: integer, serving model's port :param model_name: str, model name :param max_detection_size: integer, the max s... | stack_v2_sparse_classes_36k_train_034647 | 7,148 | no_license | [
{
"docstring": ":param host: str, serving model's host ip or dns :param port: integer, serving model's port :param model_name: str, model name :param max_detection_size: integer, the max size for detection :param max_classification_size: integer, the max size for classification",
"name": "__init__",
"si... | 4 | stack_v2_sparse_classes_30k_train_007419 | Implement the Python class `ColaDetector` described below.
Class description:
Implement the ColaDetector class.
Method signatures and docstrings:
- def __init__(self, host, port, model_name, max_detection_size=None, max_classification_size=None): :param host: str, serving model's host ip or dns :param port: integer, ... | Implement the Python class `ColaDetector` described below.
Class description:
Implement the ColaDetector class.
Method signatures and docstrings:
- def __init__(self, host, port, model_name, max_detection_size=None, max_classification_size=None): :param host: str, serving model's host ip or dns :param port: integer, ... | d44baf68d19edaa8f6e83767b1f28a2049460417 | <|skeleton|>
class ColaDetector:
def __init__(self, host, port, model_name, max_detection_size=None, max_classification_size=None):
""":param host: str, serving model's host ip or dns :param port: integer, serving model's port :param model_name: str, model name :param max_detection_size: integer, the max s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColaDetector:
def __init__(self, host, port, model_name, max_detection_size=None, max_classification_size=None):
""":param host: str, serving model's host ip or dns :param port: integer, serving model's port :param model_name: str, model name :param max_detection_size: integer, the max size for detect... | the_stack_v2_python_sparse | detection_classification_api/detection_api.py | PangYunsheng8/object-detection | train | 0 | |
c840900e6bc2bb24d67cc7def9717d3803e1f098 | [
"self.derivatives: BaseParameterDerivatives = derivatives\nself.N_axis: int = 0\nfor param_str in params:\n if not hasattr(self, param_str):\n setattr(self, param_str, self._make_param_function(param_str))\nsuper().__init__(params=params)",
"def param_function(ext: SumGradSquared, module: Module, g_inp:... | <|body_start_0|>
self.derivatives: BaseParameterDerivatives = derivatives
self.N_axis: int = 0
for param_str in params:
if not hasattr(self, param_str):
setattr(self, param_str, self._make_param_function(param_str))
super().__init__(params=params)
<|end_body_0... | Base class for extensions calculating sum_grad_squared. | SGSBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGSBase:
"""Base class for extensions calculating sum_grad_squared."""
def __init__(self, derivatives: BaseParameterDerivatives, params: List[str]=None):
"""Initialization. For each parameter a function is initialized that is named like the parameter Args: derivatives: calculates the... | stack_v2_sparse_classes_36k_train_034648 | 2,429 | permissive | [
{
"docstring": "Initialization. For each parameter a function is initialized that is named like the parameter Args: derivatives: calculates the derivatives wrt parameters params: list of parameter names",
"name": "__init__",
"signature": "def __init__(self, derivatives: BaseParameterDerivatives, params:... | 2 | null | Implement the Python class `SGSBase` described below.
Class description:
Base class for extensions calculating sum_grad_squared.
Method signatures and docstrings:
- def __init__(self, derivatives: BaseParameterDerivatives, params: List[str]=None): Initialization. For each parameter a function is initialized that is n... | Implement the Python class `SGSBase` described below.
Class description:
Base class for extensions calculating sum_grad_squared.
Method signatures and docstrings:
- def __init__(self, derivatives: BaseParameterDerivatives, params: List[str]=None): Initialization. For each parameter a function is initialized that is n... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class SGSBase:
"""Base class for extensions calculating sum_grad_squared."""
def __init__(self, derivatives: BaseParameterDerivatives, params: List[str]=None):
"""Initialization. For each parameter a function is initialized that is named like the parameter Args: derivatives: calculates the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SGSBase:
"""Base class for extensions calculating sum_grad_squared."""
def __init__(self, derivatives: BaseParameterDerivatives, params: List[str]=None):
"""Initialization. For each parameter a function is initialized that is named like the parameter Args: derivatives: calculates the derivatives ... | the_stack_v2_python_sparse | backpack/extensions/firstorder/sum_grad_squared/sgs_base.py | f-dangel/backpack | train | 505 |
363137e6b197be30c161e8ae7364d43301ec5bc3 | [
"if not t1:\n return t2\nif not t2:\n return t1\nv_queue = [(t1, t2)]\nt1.val += t2.val\nwhile len(v_queue) >= 1:\n for _ in range(len(v_queue)):\n current_v1, current_v2 = v_queue.pop(0)\n if not current_v1 and (not current_v2):\n continue\n if current_v2.left:\n ... | <|body_start_0|>
if not t1:
return t2
if not t2:
return t1
v_queue = [(t1, t2)]
t1.val += t2.val
while len(v_queue) >= 1:
for _ in range(len(v_queue)):
current_v1, current_v2 = v_queue.pop(0)
if not current_v1 an... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
"""迭代方法"""
<|body_0|>
def mergeTrees2(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
"""递归方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not t1:
return t2
... | stack_v2_sparse_classes_36k_train_034649 | 1,840 | no_license | [
{
"docstring": "迭代方法",
"name": "mergeTrees",
"signature": "def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode"
},
{
"docstring": "递归方法",
"name": "mergeTrees2",
"signature": "def mergeTrees2(self, t1: TreeNode, t2: TreeNode) -> TreeNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 迭代方法
- def mergeTrees2(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 递归方法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 迭代方法
- def mergeTrees2(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 递归方法
<|skeleton|>
class Solution:
def me... | 97cc61fefe0bedf5161687aab92fb09b0df990e2 | <|skeleton|>
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
"""迭代方法"""
<|body_0|>
def mergeTrees2(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
"""递归方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
"""迭代方法"""
if not t1:
return t2
if not t2:
return t1
v_queue = [(t1, t2)]
t1.val += t2.val
while len(v_queue) >= 1:
for _ in range(len(v_queue)):
... | the_stack_v2_python_sparse | code/tree/merge_tree.py | JiaXingBinggan/For_work | train | 0 | |
2e258889c29782b7dbd7b0aa4ec7eed3a1fce237 | [
"mergeUnits = {}\nnewMergeUnit = {}\nfor mergeableFile in mergeableFiles:\n newMergeFile = {}\n for key in mergeableFile:\n newMergeFile[key] = mergeableFile[key]\n if newMergeFile['pnn'] not in mergeUnits:\n mergeUnits[newMergeFile['pnn']] = {}\n if newMergeFile['file_run'] not in mergeUn... | <|body_start_0|>
mergeUnits = {}
newMergeUnit = {}
for mergeableFile in mergeableFiles:
newMergeFile = {}
for key in mergeableFile:
newMergeFile[key] = mergeableFile[key]
if newMergeFile['pnn'] not in mergeUnits:
mergeUnits[newM... | _WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order. | WMBSMergeBySize | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WMBSMergeBySize:
"""_WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order."""
def defineMergeUnits(self, mergeableFiles):
"""_defineMergeUnits_ Split al... | stack_v2_sparse_classes_36k_train_034650 | 9,282 | permissive | [
{
"docstring": "_defineMergeUnits_ Split all the mergeable files into merge units. A merge unit is a group of files that must be merged together. For example, the files that result from event based splitting jobs need to be merged back together. This method will return a list of merge units. A merge unit is a d... | 4 | null | Implement the Python class `WMBSMergeBySize` described below.
Class description:
_WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order.
Method signatures and docstrings:
- def defineMerg... | Implement the Python class `WMBSMergeBySize` described below.
Class description:
_WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order.
Method signatures and docstrings:
- def defineMerg... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class WMBSMergeBySize:
"""_WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order."""
def defineMergeUnits(self, mergeableFiles):
"""_defineMergeUnits_ Split al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WMBSMergeBySize:
"""_WMBSMergeBySize_ Generic merging for WMBS. This will correctly handle merging files that have been split up honoring the original file boundaries merging the files in the correct order."""
def defineMergeUnits(self, mergeableFiles):
"""_defineMergeUnits_ Split all the mergeab... | the_stack_v2_python_sparse | src/python/WMCore/JobSplitting/WMBSMergeBySize.py | vkuznet/WMCore | train | 0 |
ae2731ff9243fa123c16594196d772984035c132 | [
"if exposure_time is not None:\n if isinstance(exposure_time, int) or isinstance(exposure_time, float):\n if exposure_time <= 10 ** (-10):\n exposure_time = 10 ** (-10)\n else:\n exposure_time[exposure_time <= 10 ** (-10)] = 10 ** (-10)\nself._exp_map = exposure_time\nself._background... | <|body_start_0|>
if exposure_time is not None:
if isinstance(exposure_time, int) or isinstance(exposure_time, float):
if exposure_time <= 10 ** (-10):
exposure_time = 10 ** (-10)
else:
exposure_time[exposure_time <= 10 ** (-10)] = 10 **... | class that deals with noise properties of imaging data | ImageNoise | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNoise:
"""class that deals with noise properties of imaging data"""
def __init__(self, image_data, exposure_time=None, background_rms=None, noise_map=None, gradient_boost_factor=None, verbose=True, flux_scaling=1):
""":param image_data: numpy array, pixel data values :param expo... | stack_v2_sparse_classes_36k_train_034651 | 5,966 | permissive | [
{
"docstring": ":param image_data: numpy array, pixel data values :param exposure_time: int or array of size the data; exposure time (common for all pixels or individually for each individual pixel) :param background_rms: root-mean-square value of Gaussian background noise :param noise_map: int or array of size... | 5 | stack_v2_sparse_classes_30k_train_011023 | Implement the Python class `ImageNoise` described below.
Class description:
class that deals with noise properties of imaging data
Method signatures and docstrings:
- def __init__(self, image_data, exposure_time=None, background_rms=None, noise_map=None, gradient_boost_factor=None, verbose=True, flux_scaling=1): :par... | Implement the Python class `ImageNoise` described below.
Class description:
class that deals with noise properties of imaging data
Method signatures and docstrings:
- def __init__(self, image_data, exposure_time=None, background_rms=None, noise_map=None, gradient_boost_factor=None, verbose=True, flux_scaling=1): :par... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class ImageNoise:
"""class that deals with noise properties of imaging data"""
def __init__(self, image_data, exposure_time=None, background_rms=None, noise_map=None, gradient_boost_factor=None, verbose=True, flux_scaling=1):
""":param image_data: numpy array, pixel data values :param expo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageNoise:
"""class that deals with noise properties of imaging data"""
def __init__(self, image_data, exposure_time=None, background_rms=None, noise_map=None, gradient_boost_factor=None, verbose=True, flux_scaling=1):
""":param image_data: numpy array, pixel data values :param exposure_time: in... | the_stack_v2_python_sparse | lenstronomy/Data/image_noise.py | lenstronomy/lenstronomy | train | 41 |
3c44016df7badbd9f28932a29b14369687079c32 | [
"super(CondBatchNorm, self).__init__(x_dim, eps, momentum, affine=False)\nself.eps = eps\nself.shift_conv = nn.Sequential(nn.Conv2d(z_dim, x_dim, kernel_size=1, padding=0, bias=True))\nself.scale_conv = nn.Sequential(nn.Conv2d(z_dim, x_dim, kernel_size=1, padding=0, bias=True))",
"shift = self.shift_conv.forward(... | <|body_start_0|>
super(CondBatchNorm, self).__init__(x_dim, eps, momentum, affine=False)
self.eps = eps
self.shift_conv = nn.Sequential(nn.Conv2d(z_dim, x_dim, kernel_size=1, padding=0, bias=True))
self.scale_conv = nn.Sequential(nn.Conv2d(z_dim, x_dim, kernel_size=1, padding=0, bias=Tru... | Conditional batch norm. | CondBatchNorm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CondBatchNorm:
"""Conditional batch norm."""
def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1):
"""Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents"""
<|body_0|>
def forward(self, input, noise):
"""Forward method.""... | stack_v2_sparse_classes_36k_train_034652 | 34,675 | permissive | [
{
"docstring": "Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents",
"name": "__init__",
"signature": "def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1)"
},
{
"docstring": "Forward method.",
"name": "forward",
"signature": "def forward(self, ... | 2 | stack_v2_sparse_classes_30k_train_018918 | Implement the Python class `CondBatchNorm` described below.
Class description:
Conditional batch norm.
Method signatures and docstrings:
- def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1): Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents
- def forward(self, input, nois... | Implement the Python class `CondBatchNorm` described below.
Class description:
Conditional batch norm.
Method signatures and docstrings:
- def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1): Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents
- def forward(self, input, nois... | e1e4a8d9a2ab51c2108a4d167bc37fab101f0c2c | <|skeleton|>
class CondBatchNorm:
"""Conditional batch norm."""
def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1):
"""Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents"""
<|body_0|>
def forward(self, input, noise):
"""Forward method.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CondBatchNorm:
"""Conditional batch norm."""
def __init__(self, x_dim, z_dim, eps=1e-05, momentum=0.1):
"""Constructor. - `x_dim`: dimensionality of x input - `z_dim`: dimensionality of z latents"""
super(CondBatchNorm, self).__init__(x_dim, eps, momentum, affine=False)
self.eps =... | the_stack_v2_python_sparse | diffrend/torch/GAN/twin_networks.py | sainatarajan/pix2shape | train | 0 |
d912062c54f0c1e8822b288e4fb9c3d4bc4748a2 | [
"value = self.display_iso(date_val)\nyear = self._slash_year(date_val[2], date_val[3])\nif self.format == 0:\n return self.display_iso(date_val)\nelif self.format == 1:\n if date_val[0] == 0:\n if date_val[1] == 0:\n value = year\n else:\n value = '%s m. %s' % (year, self.l... | <|body_start_0|>
value = self.display_iso(date_val)
year = self._slash_year(date_val[2], date_val[3])
if self.format == 0:
return self.display_iso(date_val)
elif self.format == 1:
if date_val[0] == 0:
if date_val[1] == 0:
value ... | Lithuanian language date display class. | DateDisplayLT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateDisplayLT:
"""Lithuanian language date display class."""
def _display_gregorian(self, date_val):
"""display gregorian calendar date in different format"""
<|body_0|>
def display(self, date):
"""Return a text string representing the date."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_034653 | 10,035 | no_license | [
{
"docstring": "display gregorian calendar date in different format",
"name": "_display_gregorian",
"signature": "def _display_gregorian(self, date_val)"
},
{
"docstring": "Return a text string representing the date.",
"name": "display",
"signature": "def display(self, date)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014735 | Implement the Python class `DateDisplayLT` described below.
Class description:
Lithuanian language date display class.
Method signatures and docstrings:
- def _display_gregorian(self, date_val): display gregorian calendar date in different format
- def display(self, date): Return a text string representing the date. | Implement the Python class `DateDisplayLT` described below.
Class description:
Lithuanian language date display class.
Method signatures and docstrings:
- def _display_gregorian(self, date_val): display gregorian calendar date in different format
- def display(self, date): Return a text string representing the date.
... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class DateDisplayLT:
"""Lithuanian language date display class."""
def _display_gregorian(self, date_val):
"""display gregorian calendar date in different format"""
<|body_0|>
def display(self, date):
"""Return a text string representing the date."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateDisplayLT:
"""Lithuanian language date display class."""
def _display_gregorian(self, date_val):
"""display gregorian calendar date in different format"""
value = self.display_iso(date_val)
year = self._slash_year(date_val[2], date_val[3])
if self.format == 0:
... | the_stack_v2_python_sparse | gen/datehandler/_date_lt.py | balrok/gramps_addon | train | 2 |
c0d7c21eb777410d5e637c5dcd92fbadaa639f05 | [
"self.nthreads = 1\nself.serial = False\nself.timeout = -1\nself.all = False\nself.logfile = None\nself.sagenb = False\nself.long = False\nself.warn_long = None\nself.optional = set(['sage'])\nself.randorder = None\nself.global_iterations = 1\nself.file_iterations = 1\nself.initial = False\nself.force_lib = False\n... | <|body_start_0|>
self.nthreads = 1
self.serial = False
self.timeout = -1
self.all = False
self.logfile = None
self.sagenb = False
self.long = False
self.warn_long = None
self.optional = set(['sage'])
self.randorder = None
self.globa... | This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: D = DocTestD... | DocTestDefaults | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocTestDefaults:
"""This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EXAMPLES:: sage: from sage.doctest.contro... | stack_v2_sparse_classes_36k_train_034654 | 46,253 | no_license | [
{
"docstring": "Edit these parameters after creating an instance. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: D = DocTestDefaults(); D.optional {'sage'}",
"name": "__init__",
"signature": "def __init__(self, **kwds)"
},
{
"docstring": "Return the print representation.... | 3 | stack_v2_sparse_classes_30k_train_018012 | Implement the Python class `DocTestDefaults` described below.
Class description:
This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EX... | Implement the Python class `DocTestDefaults` described below.
Class description:
This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EX... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class DocTestDefaults:
"""This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EXAMPLES:: sage: from sage.doctest.contro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocTestDefaults:
"""This class is used for doctesting the Sage doctest module. It fills in attributes to be the same as the defaults defined in ``SAGE_LOCAL/bin/sage-runtests``, expect for a few places, which is mostly to make doctesting more predictable. EXAMPLES:: sage: from sage.doctest.control import DocT... | the_stack_v2_python_sparse | sage/src/sage/doctest/control.py | bopopescu/geosci | train | 0 |
3c275477e8c29dea96f8ade7285087113757a58f | [
"self._factor = factor\nself._bias_bra = False\nself._bias_ket = False",
"eps = packet.get_eps()\nqbra, Qbra, pbra, Pbra = pacbra.get_parameters(key=('q', 'Q', 'p', 'P'))\nqket, Qket, pket, Pket = packet.get_parameters(key=('q', 'Q', 'p', 'P'))\nif component is not None:\n kbra = array(pacbra.get_basis_shapes(... | <|body_start_0|>
self._factor = factor
self._bias_bra = False
self._bias_ket = False
<|end_body_0|>
<|body_start_1|>
eps = packet.get_eps()
qbra, Qbra, pbra, Pbra = pacbra.get_parameters(key=('q', 'Q', 'p', 'P'))
qket, Qket, pket, Pket = packet.get_parameters(key=('q', '... | This class implements an oracle by looking at a phase space distance. | SparsityOraclePSHAWP | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparsityOraclePSHAWP:
"""This class implements an oracle by looking at a phase space distance."""
def __init__(self, factor=1.5):
"""Initialize an oracle for estimating if a specific overlap integral :math:`\\langle \\Psi_k | \\Psi_l \\rangle` is approximately zero. The oracle works ... | stack_v2_sparse_classes_36k_train_034655 | 5,045 | permissive | [
{
"docstring": "Initialize an oracle for estimating if a specific overlap integral :math:`\\\\langle \\\\Psi_k | \\\\Psi_l \\\\rangle` is approximately zero. The oracle works by computing first and second moments :math:`\\\\mu` and :math:`\\\\sigma` of the highest order function :math:`\\\\phi_i` of both wavepa... | 3 | stack_v2_sparse_classes_30k_train_002142 | Implement the Python class `SparsityOraclePSHAWP` described below.
Class description:
This class implements an oracle by looking at a phase space distance.
Method signatures and docstrings:
- def __init__(self, factor=1.5): Initialize an oracle for estimating if a specific overlap integral :math:`\\langle \\Psi_k | \... | Implement the Python class `SparsityOraclePSHAWP` described below.
Class description:
This class implements an oracle by looking at a phase space distance.
Method signatures and docstrings:
- def __init__(self, factor=1.5): Initialize an oracle for estimating if a specific overlap integral :math:`\\langle \\Psi_k | \... | 225b5dd9b1af1998bd40b5f6467ee959292b6a83 | <|skeleton|>
class SparsityOraclePSHAWP:
"""This class implements an oracle by looking at a phase space distance."""
def __init__(self, factor=1.5):
"""Initialize an oracle for estimating if a specific overlap integral :math:`\\langle \\Psi_k | \\Psi_l \\rangle` is approximately zero. The oracle works ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparsityOraclePSHAWP:
"""This class implements an oracle by looking at a phase space distance."""
def __init__(self, factor=1.5):
"""Initialize an oracle for estimating if a specific overlap integral :math:`\\langle \\Psi_k | \\Psi_l \\rangle` is approximately zero. The oracle works by computing ... | the_stack_v2_python_sparse | WaveBlocksND/SparsityOraclePSHAWP.py | WaveBlocks/WaveBlocksND | train | 4 |
8f920582e79521c1b77270695cae6f5a483c42c8 | [
"\"\"\":field\n Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity.\n \"\"\"\nself.d... | <|body_start_0|>
""":field
Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity.... | Data for an Obi collision material. | CollisionMaterial | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=Ma... | stack_v2_sparse_classes_36k_train_034656 | 4,244 | permissive | [
{
"docstring": ":param dynamic_friction: Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity. :... | 2 | stack_v2_sparse_classes_30k_train_019142 | Implement the Python class `CollisionMaterial` described below.
Class description:
Data for an Obi collision material.
Method signatures and docstrings:
- def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=Mat... | Implement the Python class `CollisionMaterial` described below.
Class description:
Data for an Obi collision material.
Method signatures and docstrings:
- def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=Mat... | 9df96fba455b327bb360d8dd5886d8754046c690 | <|skeleton|>
class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=Ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=MaterialCombine... | the_stack_v2_python_sparse | Python/tdw/obi_data/collision_materials/collision_material.py | threedworld-mit/tdw | train | 427 |
8058c6600ba73fb5f0bc8b295f4f1004cf54bdf3 | [
"def update_receiver():\n self.req = MPI.nonblocking_receive(source=source, tag=tag)\nself.update_receiver = update_receiver\nself.update_receiver()",
"try:\n msg_available, data = self.req.test()\nexcept _pickle.UnpicklingError as e:\n error_print('unpickling error in MPI (%s), recovering by assuming no... | <|body_start_0|>
def update_receiver():
self.req = MPI.nonblocking_receive(source=source, tag=tag)
self.update_receiver = update_receiver
self.update_receiver()
<|end_body_0|>
<|body_start_1|>
try:
msg_available, data = self.req.test()
except _pickle.Unpi... | Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!** | NonblockingMPIMessageReceiver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonblockingMPIMessageReceiver:
"""Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!**"""
def __init__(self, source, tag):
"""Parameters ---------- source : int Rank of message source process. tag : int Message tag."""
<|body_0|>
def receive(... | stack_v2_sparse_classes_36k_train_034657 | 9,643 | no_license | [
{
"docstring": "Parameters ---------- source : int Rank of message source process. tag : int Message tag.",
"name": "__init__",
"signature": "def __init__(self, source, tag)"
},
{
"docstring": "Non-blocking receive message, if one is available. Returns ------- The received data, ``None`` if no d... | 2 | stack_v2_sparse_classes_30k_train_014452 | Implement the Python class `NonblockingMPIMessageReceiver` described below.
Class description:
Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!**
Method signatures and docstrings:
- def __init__(self, source, tag): Parameters ---------- source : int Rank of message source process. tag :... | Implement the Python class `NonblockingMPIMessageReceiver` described below.
Class description:
Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!**
Method signatures and docstrings:
- def __init__(self, source, tag): Parameters ---------- source : int Rank of message source process. tag :... | 858f2b673bedbec39fca9bdc9c825a3c2fefe513 | <|skeleton|>
class NonblockingMPIMessageReceiver:
"""Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!**"""
def __init__(self, source, tag):
"""Parameters ---------- source : int Rank of message source process. tag : int Message tag."""
<|body_0|>
def receive(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonblockingMPIMessageReceiver:
"""Wraps a call to MPI's Comm.irecv. **NOT THREAD SAFE - use inside a mutex block!**"""
def __init__(self, source, tag):
"""Parameters ---------- source : int Rank of message source process. tag : int Message tag."""
def update_receiver():
self.r... | the_stack_v2_python_sparse | lib/tools.py | roguextech/DanyloMalyuta-explicit_hybrid_mpc | train | 0 |
6dea838389ac83e4eab6519a632ccd1dff39842f | [
"if this is None:\n return copy.deepcopy(that)\nif that is None:\n return copy.deepcopy(this)\nresult = copy.deepcopy(this)\nresult_key_set = set(result.ids().keys())\nthat_key_set = set(that.ids().keys())\nresult._ids = {x: 1 for x in result_key_set.union(that_key_set)}\nreturn result",
"if this is None or... | <|body_start_0|>
if this is None:
return copy.deepcopy(that)
if that is None:
return copy.deepcopy(this)
result = copy.deepcopy(this)
result_key_set = set(result.ids().keys())
that_key_set = set(that.ids().keys())
result._ids = {x: 1 for x in resul... | Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object. | ExactSetOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExactSetOperator:
"""Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object."""
def union(cls, this, that):
"""Union operation for ExactSet."""
<|body_0|>
def intersection(cls, this, that):
"""Inter... | stack_v2_sparse_classes_36k_train_034658 | 19,268 | permissive | [
{
"docstring": "Union operation for ExactSet.",
"name": "union",
"signature": "def union(cls, this, that)"
},
{
"docstring": "Intersection operation for ExactSet.",
"name": "intersection",
"signature": "def intersection(cls, this, that)"
},
{
"docstring": "Difference operation fo... | 3 | stack_v2_sparse_classes_30k_train_002022 | Implement the Python class `ExactSetOperator` described below.
Class description:
Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object.
Method signatures and docstrings:
- def union(cls, this, that): Union operation for ExactSet.
- def intersection(cl... | Implement the Python class `ExactSetOperator` described below.
Class description:
Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object.
Method signatures and docstrings:
- def union(cls, this, that): Union operation for ExactSet.
- def intersection(cl... | 1727e9545a8f219b543c1b67da6b6653e36d931e | <|skeleton|>
class ExactSetOperator:
"""Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object."""
def union(cls, this, that):
"""Union operation for ExactSet."""
<|body_0|>
def intersection(cls, this, that):
"""Inter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExactSetOperator:
"""Set operations for ExactSet. The methods below all accept an ExactMultiSet object and returning an ExactMultiSet object."""
def union(cls, this, that):
"""Union operation for ExactSet."""
if this is None:
return copy.deepcopy(that)
if that is None:... | the_stack_v2_python_sparse | src/estimators/stratified_sketch.py | world-federation-of-advertisers/cardinality_estimation_evaluation_framework | train | 21 |
bac021f94f2e11735c86c690c60800a8c16a2fd2 | [
"queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineRoutingOverride=app_engine_routing_override)\nrequest = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(parent=parent_ref.RelativeName(), queue=queue)\nreturn self.queues_service.Creat... | <|body_start_0|>
queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineRoutingOverride=app_engine_routing_override)
request = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(parent=parent_ref.RelativeName(), queue=queue)
... | Client for queues service in the Cloud Tasks API. | Queues | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None):
"""Prepares and sends a Create request for creating a queue."""
<|body_0|>
def Patch(self, queu... | stack_v2_sparse_classes_36k_train_034659 | 9,305 | permissive | [
{
"docstring": "Prepares and sends a Create request for creating a queue.",
"name": "Create",
"signature": "def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None)"
},
{
"docstring": "Prepares and sends a Patch request for modifying a queue.... | 2 | stack_v2_sparse_classes_30k_train_005417 | Implement the Python class `Queues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None): Prepares and sends a Create request for creating... | Implement the Python class `Queues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None): Prepares and sends a Create request for creating... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None):
"""Prepares and sends a Create request for creating a queue."""
<|body_0|>
def Patch(self, queu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None):
"""Prepares and sends a Create request for creating a queue."""
queue = self.messages.Queue(name=queue_ref.Relati... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/api_lib/tasks/queues.py | bopopescu/socialliteapp | train | 0 |
744dcd144aab26d6fa138a570792b20f1ff9a44c | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, False, False]\nself.latex_name = 'Griewank Function'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = \\\\sum_{i=0}^{d... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])
self.n = 2
self.smooth = True
self.info = [True, False, False]
self.latex_name = 'Griewank Function'
self.latex_type = 'Many Local ... | Griewank Function. | Griewank | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domai... | stack_v2_sparse_classes_36k_train_034660 | 1,071 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010961 | Implement the Python class `Griewank` described below.
Class description:
Griewank Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Griewank` described below.
Class description:
Griewank Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])
self.n = 2
self.smooth = True
self.info = [True, False, False]
... | the_stack_v2_python_sparse | ctf/functions2d/griewank.py | cntaylor/ctf | train | 1 |
3ffc0cea58c9e08502ae852eaffb7d839ba35784 | [
"if not isinstance(data, pd.DataFrame):\n data = self.peaks(data)\nif align:\n data = self.alignbead(data, ref=ref)\n ref = None\ndata = data.sort_values(['bead', trackorder, 'peakposition', 'avg'])\nassert 'resolution' in data.columns\nif ref is None:\n ref = 'identity' if 'identity' in data.columns el... | <|body_start_0|>
if not isinstance(data, pd.DataFrame):
data = self.peaks(data)
if align:
data = self.alignbead(data, ref=ref)
ref = None
data = data.sort_values(['bead', trackorder, 'peakposition', 'avg'])
assert 'resolution' in data.columns
i... | config for aligning peaks | PeaksAlignmentConfigMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
<|body_0|>
def showhpin(data, positions, ref=None, style=None, **args):
"""disp... | stack_v2_sparse_classes_36k_train_034661 | 10,299 | no_license | [
{
"docstring": "display the data",
"name": "showone",
"signature": "def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs)"
},
{
"docstring": "display hairpin positions",
"name": "showhpin",
"signature": "def showhpin(data, positions, ref=Non... | 3 | null | Implement the Python class `PeaksAlignmentConfigMixin` described below.
Class description:
config for aligning peaks
Method signatures and docstrings:
- def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs): display the data
- def showhpin(data, positions, ref=None, styl... | Implement the Python class `PeaksAlignmentConfigMixin` described below.
Class description:
config for aligning peaks
Method signatures and docstrings:
- def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs): display the data
- def showhpin(data, positions, ref=None, styl... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
<|body_0|>
def showhpin(data, positions, ref=None, style=None, **args):
"""disp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
if not isinstance(data, pd.DataFrame):
data = self.peaks(data)
if align:
... | the_stack_v2_python_sparse | src/scripting/aligningexperiments/_view.py | depixusgenome/trackanalysis | train | 0 |
b8534b94aa3a1393bab2e9f4abc7fa871e89e733 | [
"super().__init__(dev_id, dev_name, description)\nself._scale_min = scale_min\nself._scale_max = scale_max\nself.range_from = range_from\nself.range_to = range_to",
"if packet.data[0] != 165:\n return\ntemp_scale = self._scale_max - self._scale_min\ntemp_range = self.range_to - self.range_from\nraw_val = packe... | <|body_start_0|>
super().__init__(dev_id, dev_name, description)
self._scale_min = scale_min
self._scale_max = scale_max
self.range_from = range_from
self.range_to = range_to
<|end_body_0|>
<|body_start_1|>
if packet.data[0] != 165:
return
temp_scale ... | Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to 100%) - A5-04-02 (Temp. and Humidity Sensor, Range -... | EnOceanTemperatureSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnOceanTemperatureSensor:
"""Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to ... | stack_v2_sparse_classes_36k_train_034662 | 9,398 | permissive | [
{
"docstring": "Initialize the EnOcean temperature sensor device.",
"name": "__init__",
"signature": "def __init__(self, dev_id: list[int], dev_name: str, description: EnOceanSensorEntityDescription, *, scale_min: int, scale_max: int, range_from: int, range_to: int) -> None"
},
{
"docstring": "U... | 2 | null | Implement the Python class `EnOceanTemperatureSensor` described below.
Class description:
Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidit... | Implement the Python class `EnOceanTemperatureSensor` described below.
Class description:
Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidit... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EnOceanTemperatureSensor:
"""Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnOceanTemperatureSensor:
"""Representation of an EnOcean temperature sensor device. EEPs (EnOcean Equipment Profiles): - A5-02-01 to A5-02-1B All 8 Bit Temperature Sensors of A5-02 - A5-10-01 to A5-10-14 (Room Operating Panels) - A5-04-01 (Temp. and Humidity Sensor, Range 0°C to +40°C and 0% to 100%) - A5-04... | the_stack_v2_python_sparse | homeassistant/components/enocean/sensor.py | home-assistant/core | train | 35,501 |
1cf1c50200bf7db66a330ac402c21562b213dc3c | [
"if self._isConstant:\n return np.full(len(x), self.getCalibrationMean())\nelse:\n bf = self.computeScaledCalibration()\n return self.getCalibrationMean() * bf.evaluate(x, y)",
"scale = self.getLocalCalibrationArray(x, y)\nnanoJansky = instFluxes * scale * units.nJy\nreturn nanoJansky.to(units.ABmag)",
... | <|body_start_0|>
if self._isConstant:
return np.full(len(x), self.getCalibrationMean())
else:
bf = self.computeScaledCalibration()
return self.getCalibrationMean() * bf.evaluate(x, y)
<|end_body_0|>
<|body_start_1|>
scale = self.getLocalCalibrationArray(x, y)... | PhotoCalib | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `... | stack_v2_sparse_classes_36k_train_034663 | 3,309 | no_license | [
{
"docstring": "Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `np.ndarray` (N,) Array of local calibration values (nJy/counts)."... | 3 | null | Implement the Python class `PhotoCalib` described below.
Class description:
Implement the PhotoCalib class.
Method signatures and docstrings:
- def getLocalCalibrationArray(self, x, y): Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x valu... | Implement the Python class `PhotoCalib` described below.
Class description:
Implement the PhotoCalib class.
Method signatures and docstrings:
- def getLocalCalibrationArray(self, x, y): Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x valu... | 5b0a8152295a779573e119dde2297b13acc35365 | <|skeleton|>
class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `np.ndarray` (N... | the_stack_v2_python_sparse | python/lsst/afw/image/_photoCalibContinued.py | lsst/afw | train | 18 | |
ea40a36f44e1bd812588da6ce9c432fd239fdd92 | [
"assert user_id\nuser = (yield UserService.get_user_detail(user_id=user_id))\nresult_string = UserMapper.to_record(user)\nself.set_status(httplib.OK)\nself.write(result_string)",
"assert user_id\nuser = (yield UserService.get_user_detail(user_id=user_id))\nrequest_body = json.loads(self.request.body)\nactivated_v... | <|body_start_0|>
assert user_id
user = (yield UserService.get_user_detail(user_id=user_id))
result_string = UserMapper.to_record(user)
self.set_status(httplib.OK)
self.write(result_string)
<|end_body_0|>
<|body_start_1|>
assert user_id
user = (yield UserService.g... | UserInformationHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""handle the post... | stack_v2_sparse_classes_36k_train_034664 | 3,088 | no_license | [
{
"docstring": "handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "handle the post request from /user/{user_id}?ac... | 2 | null | Implement the Python class `UserInformationHandler` described below.
Class description:
Implement the UserInformationHandler class.
Method signatures and docstrings:
- def get(self, user_id): handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information... | Implement the Python class `UserInformationHandler` described below.
Class description:
Implement the UserInformationHandler class.
Method signatures and docstrings:
- def get(self, user_id): handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information... | fd759c16b9864f6b1b47b1ba3f1af77f8d08af20 | <|skeleton|>
class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""handle the post... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserInformationHandler:
def get(self, user_id):
"""handle the get request from /user/{user_id}?access_token={access_token} and write it back with proper fetched user information :param String user_id: :return:"""
assert user_id
user = (yield UserService.get_user_detail(user_id=user_id)... | the_stack_v2_python_sparse | ParkingFinder/handlers/user_information.py | Big-Lemon/ParkingFinder | train | 2 | |
71d8fdef23819b4f0858263043396b6e8f829701 | [
"super(SearchMembers, self).__init__(*args, **kwargs)\nself.endpoint = 'search-members'\nself.list_id = None",
"if 'list_id' in queryparams:\n self.list_id = queryparams['list_id']\nelse:\n self.list_id = None\nreturn self._mc_client._get(url=self._build_path(), **queryparams)"
] | <|body_start_0|>
super(SearchMembers, self).__init__(*args, **kwargs)
self.endpoint = 'search-members'
self.list_id = None
<|end_body_0|>
<|body_start_1|>
if 'list_id' in queryparams:
self.list_id = queryparams['list_id']
else:
self.list_id = None
... | Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more. | SearchMembers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchMembers:
"""Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more."""
def __init__(self, *args, **kwargs):
"""Initialize... | stack_v2_sparse_classes_36k_train_034665 | 1,600 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Search for list members. This search can be restricted to a specific list, or can be used to search across all lists in an account. :param queryparams: The query st... | 2 | null | Implement the Python class `SearchMembers` described below.
Class description:
Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more.
Method signatures and docs... | Implement the Python class `SearchMembers` described below.
Class description:
Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more.
Method signatures and docs... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class SearchMembers:
"""Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more."""
def __init__(self, *args, **kwargs):
"""Initialize... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchMembers:
"""Manage campaign reports for your MailChimp account. All Reports endpoints are read-only. MailChimp’s campaign and Automation reports analyze clicks, opens, subscribers’ social activity, e-commerce data, and more."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint... | the_stack_v2_python_sparse | mailchimp3/entities/searchmembers.py | VingtCinq/python-mailchimp | train | 190 |
f1dc1d67d71adc23dad91ea1ba96677645e59ab3 | [
"self.old_sid = service.event_sid\nservice.event_sid = ''\nservice.event_timeout = 0\nself.callback = callback\nself.cargo = cargo\nself.service = service\naddr = '%s%s' % (service.url_base, service.event_sub_url)\nPaddr = parse_url(addr)\nheaders = {}\nheaders['User-agent'] = 'BRISA-CP'\nheaders['HOST'] = '%s:%d' ... | <|body_start_0|>
self.old_sid = service.event_sid
service.event_sid = ''
service.event_timeout = 0
self.callback = callback
self.cargo = cargo
self.service = service
addr = '%s%s' % (service.url_base, service.event_sub_url)
Paddr = parse_url(addr)
... | Wrapper for an event unsubscription. | UnsubscribeRequest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnsubscribeRequest:
"""Wrapper for an event unsubscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param event_host: 2-tuple (host, port) of the event listener server... | stack_v2_sparse_classes_36k_train_034666 | 17,901 | permissive | [
{
"docstring": "Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param event_host: 2-tuple (host, port) of the event listener server @param callback: callback @param cargo: callback parameters @type service: Service @type event_host: tuple @type callback: callable",
... | 3 | null | Implement the Python class `UnsubscribeRequest` described below.
Class description:
Wrapper for an event unsubscription.
Method signatures and docstrings:
- def __init__(self, service, event_host, callback, cargo): Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param even... | Implement the Python class `UnsubscribeRequest` described below.
Class description:
Wrapper for an event unsubscription.
Method signatures and docstrings:
- def __init__(self, service, event_host, callback, cargo): Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param even... | 69f9c870369085f4440033201e2fb263a463a523 | <|skeleton|>
class UnsubscribeRequest:
"""Wrapper for an event unsubscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param event_host: 2-tuple (host, port) of the event listener server... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnsubscribeRequest:
"""Wrapper for an event unsubscription."""
def __init__(self, service, event_host, callback, cargo):
"""Constructor for the UnsubscribeRequest class. @param service: service that is unsubscribing @param event_host: 2-tuple (host, port) of the event listener server @param callb... | the_stack_v2_python_sparse | WebBrickLibs/brisa/upnp/control_point/service.py | AndyThirtover/wb_gateway | train | 0 |
c1714e7ef3d00d6afe4027a59556d247d1d94da8 | [
"if N == 0:\n return 1\nelif N < 0:\n return 0\nelse:\n return self.recursive(N - 1) + self.recursive(N - 2) + self.recursive(N - 3)",
"cache = {0: 1}\n\ndef recurse(N):\n if N < 0:\n return 0\n elif N not in cache:\n cache[N] = recurse(N - 1) + recurse(N - 2) + recurse(N - 3)\n re... | <|body_start_0|>
if N == 0:
return 1
elif N < 0:
return 0
else:
return self.recursive(N - 1) + self.recursive(N - 2) + self.recursive(N - 3)
<|end_body_0|>
<|body_start_1|>
cache = {0: 1}
def recurse(N):
if N < 0:
... | ThreeStepSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeStepSolution:
def recursive(self, N):
"""We solve this problem using recursion."""
<|body_0|>
def top_down(self, N):
"""Top down approach using memoization"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N == 0:
return 1
... | stack_v2_sparse_classes_36k_train_034667 | 1,199 | no_license | [
{
"docstring": "We solve this problem using recursion.",
"name": "recursive",
"signature": "def recursive(self, N)"
},
{
"docstring": "Top down approach using memoization",
"name": "top_down",
"signature": "def top_down(self, N)"
}
] | 2 | null | Implement the Python class `ThreeStepSolution` described below.
Class description:
Implement the ThreeStepSolution class.
Method signatures and docstrings:
- def recursive(self, N): We solve this problem using recursion.
- def top_down(self, N): Top down approach using memoization | Implement the Python class `ThreeStepSolution` described below.
Class description:
Implement the ThreeStepSolution class.
Method signatures and docstrings:
- def recursive(self, N): We solve this problem using recursion.
- def top_down(self, N): Top down approach using memoization
<|skeleton|>
class ThreeStepSolutio... | 5347a98a61efbfef75e3e27ac564c423c4ec25bb | <|skeleton|>
class ThreeStepSolution:
def recursive(self, N):
"""We solve this problem using recursion."""
<|body_0|>
def top_down(self, N):
"""Top down approach using memoization"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreeStepSolution:
def recursive(self, N):
"""We solve this problem using recursion."""
if N == 0:
return 1
elif N < 0:
return 0
else:
return self.recursive(N - 1) + self.recursive(N - 2) + self.recursive(N - 3)
def top_down(self, N):
... | the_stack_v2_python_sparse | dynamic_programming/triple_steps.py | gtang31/algorithms | train | 0 | |
015a76f02549062a83a515b1b0a17f03ae0bddde | [
"self._shape = shape\nself._n = sum(shape)\nself._initial_data = [[None] * s for s in shape]\nif pi is None:\n pi = Permutation([1]).to_permutation_group_element()\nself.pi = pi\nending_row = max(shape)\nending_col = len(shape) - list(reversed(list(shape))).index(ending_row)\nself._ending_position = (ending_col,... | <|body_start_0|>
self._shape = shape
self._n = sum(shape)
self._initial_data = [[None] * s for s in shape]
if pi is None:
pi = Permutation([1]).to_permutation_group_element()
self.pi = pi
ending_row = max(shape)
ending_col = len(shape) - list(reversed(... | NonattackingBacktracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonattackingBacktracker:
def __init__(self, shape, pi=None):
"""EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: n._ending_position (3, 2) sage: n._initial_state (2, 1)"""
<|body_0|... | stack_v2_sparse_classes_36k_train_034668 | 29,038 | no_license | [
{
"docstring": "EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: n._ending_position (3, 2) sage: n._initial_state (2, 1)",
"name": "__init__",
"signature": "def __init__(self, shape, pi=None)"
},
{
... | 3 | null | Implement the Python class `NonattackingBacktracker` described below.
Class description:
Implement the NonattackingBacktracker class.
Method signatures and docstrings:
- def __init__(self, shape, pi=None): EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktra... | Implement the Python class `NonattackingBacktracker` described below.
Class description:
Implement the NonattackingBacktracker class.
Method signatures and docstrings:
- def __init__(self, shape, pi=None): EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktra... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class NonattackingBacktracker:
def __init__(self, shape, pi=None):
"""EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: n._ending_position (3, 2) sage: n._initial_state (2, 1)"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonattackingBacktracker:
def __init__(self, shape, pi=None):
"""EXAMPLES:: sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2])) sage: n._ending_position (3, 2) sage: n._initial_state (2, 1)"""
self._shape = shape
... | the_stack_v2_python_sparse | sage/src/sage/combinat/sf/ns_macdonald.py | bopopescu/geosci | train | 0 | |
e6c97b98de218a4a1496b80d657ae048f70cd08a | [
"super().__init__()\nself.first_layer_norm = LNorm(normalized_shape=hid_dim)\nself.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout, device)\nself.first_gate = Gate(hid_dim=hid_dim)\nself.second_layer_norm = LNorm(normalized_shape=hid_dim)\nself.positionwise_feedforward = PositionwiseFeedforwardLa... | <|body_start_0|>
super().__init__()
self.first_layer_norm = LNorm(normalized_shape=hid_dim)
self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout, device)
self.first_gate = Gate(hid_dim=hid_dim)
self.second_layer_norm = LNorm(normalized_shape=hid_dim)
se... | GatedEncoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GatedEncoderLayer:
def __init__(self, hid_dim: int, n_heads: int, pf_dim: int, dropout: float, device: str):
"""Gated Encoder layer of Encoder of the Transformer Parameters ---------- hid_dim: int input hidden_dim from the processed positioned-encoded & embedded vectorized input text n_h... | stack_v2_sparse_classes_36k_train_034669 | 14,453 | permissive | [
{
"docstring": "Gated Encoder layer of Encoder of the Transformer Parameters ---------- hid_dim: int input hidden_dim from the processed positioned-encoded & embedded vectorized input text n_heads: int number of head(s) for attention mechanism pf_dim: int input feed-forward dimension dropout: float dropout rate... | 2 | stack_v2_sparse_classes_30k_train_012787 | Implement the Python class `GatedEncoderLayer` described below.
Class description:
Implement the GatedEncoderLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim: int, n_heads: int, pf_dim: int, dropout: float, device: str): Gated Encoder layer of Encoder of the Transformer Parameters ---------... | Implement the Python class `GatedEncoderLayer` described below.
Class description:
Implement the GatedEncoderLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim: int, n_heads: int, pf_dim: int, dropout: float, device: str): Gated Encoder layer of Encoder of the Transformer Parameters ---------... | a6c870d4ed0788f15cfdf58c85ed5201dff60ee9 | <|skeleton|>
class GatedEncoderLayer:
def __init__(self, hid_dim: int, n_heads: int, pf_dim: int, dropout: float, device: str):
"""Gated Encoder layer of Encoder of the Transformer Parameters ---------- hid_dim: int input hidden_dim from the processed positioned-encoded & embedded vectorized input text n_h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GatedEncoderLayer:
def __init__(self, hid_dim: int, n_heads: int, pf_dim: int, dropout: float, device: str):
"""Gated Encoder layer of Encoder of the Transformer Parameters ---------- hid_dim: int input hidden_dim from the processed positioned-encoded & embedded vectorized input text n_heads: int numb... | the_stack_v2_python_sparse | src/gated_transformers_nlp/utils/gated_transformers/encoder.py | mnguyen0226/gated_transformers_nlp | train | 2 | |
9d5ba70c1a70117b15e7164acb3bb4a24d744664 | [
"task_states = []\nstatement = 'SELECT * FROM task_states WHERE experiment_id = %s AND tick = %s'\nresults = database.fetchall(statement, (experiment_id, tick))\nfor row in results:\n task_states.append(cls(id=row[0], task_id=row[1], experiment_id=row[2], tick=row[3], flops_left=row[4]))\nreturn task_states",
... | <|body_start_0|>
task_states = []
statement = 'SELECT * FROM task_states WHERE experiment_id = %s AND tick = %s'
results = database.fetchall(statement, (experiment_id, tick))
for row in results:
task_states.append(cls(id=row[0], task_id=row[1], experiment_id=row[2], tick=row[... | TaskState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskState:
def from_experiment_id_and_tick(cls, experiment_id, tick):
"""Query Task States by their Experiment id and tick."""
<|body_0|>
def google_id_has_at_least(self, google_id, authorization_level):
"""Return True if the User has at least the given auth level ov... | stack_v2_sparse_classes_36k_train_034670 | 1,436 | permissive | [
{
"docstring": "Query Task States by their Experiment id and tick.",
"name": "from_experiment_id_and_tick",
"signature": "def from_experiment_id_and_tick(cls, experiment_id, tick)"
},
{
"docstring": "Return True if the User has at least the given auth level over this TaskState.",
"name": "go... | 2 | stack_v2_sparse_classes_30k_train_008947 | Implement the Python class `TaskState` described below.
Class description:
Implement the TaskState class.
Method signatures and docstrings:
- def from_experiment_id_and_tick(cls, experiment_id, tick): Query Task States by their Experiment id and tick.
- def google_id_has_at_least(self, google_id, authorization_level)... | Implement the Python class `TaskState` described below.
Class description:
Implement the TaskState class.
Method signatures and docstrings:
- def from_experiment_id_and_tick(cls, experiment_id, tick): Query Task States by their Experiment id and tick.
- def google_id_has_at_least(self, google_id, authorization_level)... | 71aa937a9b7db7289d69ac85587387070d2af851 | <|skeleton|>
class TaskState:
def from_experiment_id_and_tick(cls, experiment_id, tick):
"""Query Task States by their Experiment id and tick."""
<|body_0|>
def google_id_has_at_least(self, google_id, authorization_level):
"""Return True if the User has at least the given auth level ov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskState:
def from_experiment_id_and_tick(cls, experiment_id, tick):
"""Query Task States by their Experiment id and tick."""
task_states = []
statement = 'SELECT * FROM task_states WHERE experiment_id = %s AND tick = %s'
results = database.fetchall(statement, (experiment_id, ... | the_stack_v2_python_sparse | opendc/models/task_state.py | atlarge-research/opendc-web-server | train | 2 | |
631c521f80c435c3631261e997daa7a170302d27 | [
"assert num_inputs >= 2\npath_names, ops = ([], [])\nfor i in range(num_inputs):\n s = stride if i < 2 else 1\n path_name = '%s/op-%d' % (arc_key, i)\n wrapped = primitives.instance(name=path_name, stride=s)\n ops.append(InputChoiceWrapperModule(wrapped, idx=i))\n path_names.append(path_name)\nreturn... | <|body_start_0|>
assert num_inputs >= 2
path_names, ops = ([], [])
for i in range(num_inputs):
s = stride if i < 2 else 1
path_name = '%s/op-%d' % (arc_key, i)
wrapped = primitives.instance(name=path_name, stride=s)
ops.append(InputChoiceWrapperMod... | all mixed ops for one block | DartsCNNSearchBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DartsCNNSearchBlock:
"""all mixed ops for one block"""
def search_block_instance(cls, primitives: PrimitiveSet, arc_key: str, num_inputs: int, stride: int=1) -> 'DartsCNNSearchBlock':
""":param primitives: primitive set for this block :param arc_key: key under which to register archi... | stack_v2_sparse_classes_36k_train_034671 | 3,495 | permissive | [
{
"docstring": ":param primitives: primitive set for this block :param arc_key: key under which to register architecture parameter names :param num_inputs: number of block inputs :param stride: stride for the CNN ops :return:",
"name": "search_block_instance",
"signature": "def search_block_instance(cls... | 2 | null | Implement the Python class `DartsCNNSearchBlock` described below.
Class description:
all mixed ops for one block
Method signatures and docstrings:
- def search_block_instance(cls, primitives: PrimitiveSet, arc_key: str, num_inputs: int, stride: int=1) -> 'DartsCNNSearchBlock': :param primitives: primitive set for thi... | Implement the Python class `DartsCNNSearchBlock` described below.
Class description:
all mixed ops for one block
Method signatures and docstrings:
- def search_block_instance(cls, primitives: PrimitiveSet, arc_key: str, num_inputs: int, stride: int=1) -> 'DartsCNNSearchBlock': :param primitives: primitive set for thi... | 06729b9cf517ec416fb798ae387c5bd9c3a278ac | <|skeleton|>
class DartsCNNSearchBlock:
"""all mixed ops for one block"""
def search_block_instance(cls, primitives: PrimitiveSet, arc_key: str, num_inputs: int, stride: int=1) -> 'DartsCNNSearchBlock':
""":param primitives: primitive set for this block :param arc_key: key under which to register archi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DartsCNNSearchBlock:
"""all mixed ops for one block"""
def search_block_instance(cls, primitives: PrimitiveSet, arc_key: str, num_inputs: int, stride: int=1) -> 'DartsCNNSearchBlock':
""":param primitives: primitive set for this block :param arc_key: key under which to register architecture param... | the_stack_v2_python_sparse | uninas/modules/blocks/darts.py | MLDL/uninas | train | 0 |
065a333c7e98a7e2387df0f73a6e6ec2bb96106a | [
"self.change_status_accum(form)\nself.data_collect_terminal_remark(form)\nreturn super().form_valid(form)",
"accum_in_form = form.cleaned_data['accumulator']\nif DataCollectTerminal.objects.filter(name=form.cleaned_data['name']):\n accum_in_db = DataCollectTerminal.objects.get(slug=self.object.slug).accumulato... | <|body_start_0|>
self.change_status_accum(form)
self.data_collect_terminal_remark(form)
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
accum_in_form = form.cleaned_data['accumulator']
if DataCollectTerminal.objects.filter(name=form.cleaned_data['name']):
... | Extension when creating and updating a terminal to change the battery status. | ModifiedMethodFormValidMixim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModifiedMethodFormValidMixim:
"""Extension when creating and updating a terminal to change the battery status."""
def form_valid(self, form):
"""Redefined method for enabling business logic when creating and modifying data collect terminals."""
<|body_0|>
def change_stat... | stack_v2_sparse_classes_36k_train_034672 | 3,556 | no_license | [
{
"docstring": "Redefined method for enabling business logic when creating and modifying data collect terminals.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Called to change the state of the battery. Possible states: 1. Installed 2. Uninstalled",
"nam... | 3 | stack_v2_sparse_classes_30k_train_000628 | Implement the Python class `ModifiedMethodFormValidMixim` described below.
Class description:
Extension when creating and updating a terminal to change the battery status.
Method signatures and docstrings:
- def form_valid(self, form): Redefined method for enabling business logic when creating and modifying data coll... | Implement the Python class `ModifiedMethodFormValidMixim` described below.
Class description:
Extension when creating and updating a terminal to change the battery status.
Method signatures and docstrings:
- def form_valid(self, form): Redefined method for enabling business logic when creating and modifying data coll... | 5aa1565a7e7f4ea03cb92fd2b8db964c02aca27b | <|skeleton|>
class ModifiedMethodFormValidMixim:
"""Extension when creating and updating a terminal to change the battery status."""
def form_valid(self, form):
"""Redefined method for enabling business logic when creating and modifying data collect terminals."""
<|body_0|>
def change_stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModifiedMethodFormValidMixim:
"""Extension when creating and updating a terminal to change the battery status."""
def form_valid(self, form):
"""Redefined method for enabling business logic when creating and modifying data collect terminals."""
self.change_status_accum(form)
self.... | the_stack_v2_python_sparse | dct/mixins.py | Singlelogic/inportal | train | 0 |
eb38ee0b3754ba5cbda846192e86317722f13909 | [
"self.match_labels = match_labels\nself.name = name\nself.service_name = service_name",
"if dictionary is None:\n return None\nmatch_labels = None\nif dictionary.get('matchLabels') != None:\n match_labels = list()\n for structure in dictionary.get('matchLabels'):\n match_labels.append(cohesity_man... | <|body_start_0|>
self.match_labels = match_labels
self.name = name
self.service_name = service_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
match_labels = None
if dictionary.get('matchLabels') != None:
match_labels = lis... | Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the selector name (string): Select all objects which have a label with key : "name"... | LabelSelector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSelector:
"""Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the selector name (string): Select all obj... | stack_v2_sparse_classes_36k_train_034673 | 2,409 | permissive | [
{
"docstring": "Constructor for the LabelSelector class",
"name": "__init__",
"signature": "def __init__(self, match_labels=None, name=None, service_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of th... | 2 | stack_v2_sparse_classes_30k_test_000635 | Implement the Python class `LabelSelector` described below.
Class description:
Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the... | Implement the Python class `LabelSelector` described below.
Class description:
Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LabelSelector:
"""Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the selector name (string): Select all obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSelector:
"""Implementation of the 'LabelSelector' model. TODO: type description here. Attributes: match_labels (list of LabelSelector_MatchLabelsEntry): This field is an object which consists of key-value pairs of all labels that must be matched by the selector name (string): Select all objects which ha... | the_stack_v2_python_sparse | cohesity_management_sdk/models/label_selector.py | cohesity/management-sdk-python | train | 24 |
8146b0b9737f711ea098f33043e3fa14ea62a09b | [
"samples = [sample]\ncategories_task = categories_from_metadata.s(samples, min_size=1)\ndistribution_task = make_distributions.s(samples)\npersist_task = persist_result.s(sample['analysis_result'], MODULE_NAME)\ntask_chain = chain(categories_task, distribution_task, persist_task)\nresult = task_chain.delay()\nretur... | <|body_start_0|>
samples = [sample]
categories_task = categories_from_metadata.s(samples, min_size=1)
distribution_task = make_distributions.s(samples)
persist_task = persist_result.s(sample['analysis_result'], MODULE_NAME)
task_chain = chain(categories_task, distribution_task, p... | Task for generating HMP results. | HMPWrangler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HMPWrangler:
"""Task for generating HMP results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_034674 | 1,461 | permissive | [
{
"docstring": "Gather single sample and process.",
"name": "run_sample",
"signature": "def run_sample(cls, sample_id, sample)"
},
{
"docstring": "Gather and process samples.",
"name": "run_sample_group",
"signature": "def run_sample_group(cls, sample_group, samples)"
}
] | 2 | null | Implement the Python class `HMPWrangler` described below.
Class description:
Task for generating HMP results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples. | Implement the Python class `HMPWrangler` described below.
Class description:
Task for generating HMP results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples.
<|skeleton|>
clas... | 609cd57c626c857c8efde8237a1f22f4d1e6065d | <|skeleton|>
class HMPWrangler:
"""Task for generating HMP results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HMPWrangler:
"""Task for generating HMP results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
samples = [sample]
categories_task = categories_from_metadata.s(samples, min_size=1)
distribution_task = make_distributions.s(samples)
... | the_stack_v2_python_sparse | app/display_modules/hmp/wrangler.py | MetaGenScope/metagenscope-server | train | 0 |
891f22e376a1dff14fd578490e8c68f66df5c324 | [
"pattern_matcher = BackEdgeSimpleInputMatcher()\npattern = pattern_matcher.pattern()\ngraph = build_graph_with_attrs(nodes_with_attrs=pattern['nodes'], edges_with_attrs=pattern['edges'], new_nodes_with_attrs=[('cycle_data', {'kind': 'data'}), ('condition', {'kind': 'data'}), ('init', {'kind': 'data', 'shape': np.ar... | <|body_start_0|>
pattern_matcher = BackEdgeSimpleInputMatcher()
pattern = pattern_matcher.pattern()
graph = build_graph_with_attrs(nodes_with_attrs=pattern['nodes'], edges_with_attrs=pattern['edges'], new_nodes_with_attrs=[('cycle_data', {'kind': 'data'}), ('condition', {'kind': 'data'}), ('init... | BackEdgeInputMatcherTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackEdgeInputMatcherTest:
def test1(self):
"""Case with constant input to init"""
<|body_0|>
def test2(self):
"""Case with non-constant input to init. Nothing should happen with graph."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pattern_matcher ... | stack_v2_sparse_classes_36k_train_034675 | 9,696 | permissive | [
{
"docstring": "Case with constant input to init",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "Case with non-constant input to init. Nothing should happen with graph.",
"name": "test2",
"signature": "def test2(self)"
}
] | 2 | null | Implement the Python class `BackEdgeInputMatcherTest` described below.
Class description:
Implement the BackEdgeInputMatcherTest class.
Method signatures and docstrings:
- def test1(self): Case with constant input to init
- def test2(self): Case with non-constant input to init. Nothing should happen with graph. | Implement the Python class `BackEdgeInputMatcherTest` described below.
Class description:
Implement the BackEdgeInputMatcherTest class.
Method signatures and docstrings:
- def test1(self): Case with constant input to init
- def test2(self): Case with non-constant input to init. Nothing should happen with graph.
<|sk... | e4bed7a31c9f00d8afbfcabee3f64f55496ae56a | <|skeleton|>
class BackEdgeInputMatcherTest:
def test1(self):
"""Case with constant input to init"""
<|body_0|>
def test2(self):
"""Case with non-constant input to init. Nothing should happen with graph."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackEdgeInputMatcherTest:
def test1(self):
"""Case with constant input to init"""
pattern_matcher = BackEdgeSimpleInputMatcher()
pattern = pattern_matcher.pattern()
graph = build_graph_with_attrs(nodes_with_attrs=pattern['nodes'], edges_with_attrs=pattern['edges'], new_nodes_wi... | the_stack_v2_python_sparse | tools/mo/unit_tests/mo/middle/TensorIteratorInput_test.py | openvinotoolkit/openvino | train | 3,953 | |
1e611737a52ac21b9885d3d4a26c8c3de1a43cd7 | [
"global _SESSIONS\nif not _SESSIONS:\n from evennia.server.sessionhandler import SESSIONS as _SESSIONS\nif ev_channel:\n channel = search.channel_search(ev_channel)\n if not channel:\n raise RuntimeError(\"Evennia Channel '%s' not found.\" % ev_channel)\n channel = channel[0]\n self.db.ev_chan... | <|body_start_0|>
global _SESSIONS
if not _SESSIONS:
from evennia.server.sessionhandler import SESSIONS as _SESSIONS
if ev_channel:
channel = search.channel_search(ev_channel)
if not channel:
raise RuntimeError("Evennia Channel '%s' not found." ... | An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals. | RSSBot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to ... | stack_v2_sparse_classes_36k_train_034676 | 13,744 | permissive | [
{
"docstring": "Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to connect to. rss_url (str): Full URL to the RSS feed to subscribe to. rss_update_rate (int): How often for the feedreader to update. Raises: RuntimeError: If `ev_channel` does not exist.",... | 2 | stack_v2_sparse_classes_30k_train_020616 | Implement the Python class `RSSBot` described below.
Class description:
An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals.
Method signatures and docstrings:
- def start(self, ev_channel=None, rss_url=None, rss_rate=None): Start by telling the portal to start a new RSS sessi... | Implement the Python class `RSSBot` described below.
Class description:
An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals.
Method signatures and docstrings:
- def start(self, ev_channel=None, rss_url=None, rss_rate=None): Start by telling the portal to start a new RSS sessi... | 384d08f9d877c7ad758292822e6f04292fdad047 | <|skeleton|>
class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSSBot:
"""An RSS relayer. The RSS protocol itself runs a ticker to update its feed at regular intervals."""
def start(self, ev_channel=None, rss_url=None, rss_rate=None):
"""Start by telling the portal to start a new RSS session Args: ev_channel (str): Key of the Evennia channel to connect to. r... | the_stack_v2_python_sparse | evennia/players/bots.py | robbintt/evennia | train | 1 |
a2086ecee67f7884d889cdaeb676d46741b81a8f | [
"self.matrix = matrix\nself.sumMatrix = None\nif matrix == None or len(matrix) == 0 or matrix[0] == None or (len(matrix[0]) == 0):\n return\nself.sumMatrix = [[0] * (len(matrix[0]) + 1) for i in range(len(matrix) + 1)]\nfor i in range(1, len(self.sumMatrix)):\n for j in range(1, len(self.sumMatrix[0])):\n ... | <|body_start_0|>
self.matrix = matrix
self.sumMatrix = None
if matrix == None or len(matrix) == 0 or matrix[0] == None or (len(matrix[0]) == 0):
return
self.sumMatrix = [[0] * (len(matrix[0]) + 1) for i in range(len(matrix) + 1)]
for i in range(1, len(self.sumMatrix))... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_034677 | 1,098 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_012261 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 60af9435e3bde9fc18cba8cc2fb44411e556cec7 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.matrix = matrix
self.sumMatrix = None
if matrix == None or len(matrix) == 0 or matrix[0] == None or (len(matrix[0]) == 0):
return
self.sumMatrix = [[0] * (len(matrix[0]) + 1) for... | the_stack_v2_python_sparse | 0304.二维区域和检索-矩阵不可变/0304-二维区域和检索-矩阵不可变.py | GChen-ai/MyLeetCode | train | 2 | |
1dac0e13dc3c0201506d2b6a4fdc19dec076e3bd | [
"self.__screen = screen\nself.__dns = DNS()\nself.__hostnameLabel = Label('Hostname')\nself.__primaryDNSLabel = Label('Primary DNS')\nself.__secondaryDNSLabel = Label('Secondary DNS')\nself.__searchListLabel = Label('Search')\nself.__hostname = Entry(15, socket.gethostname())\nself.__primaryDNS = Entry(15, self.__d... | <|body_start_0|>
self.__screen = screen
self.__dns = DNS()
self.__hostnameLabel = Label('Hostname')
self.__primaryDNSLabel = Label('Primary DNS')
self.__secondaryDNSLabel = Label('Secondary DNS')
self.__searchListLabel = Label('Search')
self.__hostname = Entry(15,... | Represents the DNS configuration screen | DNSConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNSConfig:
"""Represents the DNS configuration screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def __writeConfig(self):
"""Write configuration into the file @rtype: None @returns: no... | stack_v2_sparse_classes_36k_train_034678 | 2,694 | no_license | [
{
"docstring": "Constructor @type screen: SnackScreen @param screen: SnackScreen instance",
"name": "__init__",
"signature": "def __init__(self, screen)"
},
{
"docstring": "Write configuration into the file @rtype: None @returns: nothing",
"name": "__writeConfig",
"signature": "def __wri... | 3 | stack_v2_sparse_classes_30k_train_009194 | Implement the Python class `DNSConfig` described below.
Class description:
Represents the DNS configuration screen
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def __writeConfig(self): Write configuration into the file @rty... | Implement the Python class `DNSConfig` described below.
Class description:
Represents the DNS configuration screen
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def __writeConfig(self): Write configuration into the file @rty... | 1c738fd5e6ee3f8fd4f47acf2207038f20868212 | <|skeleton|>
class DNSConfig:
"""Represents the DNS configuration screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def __writeConfig(self):
"""Write configuration into the file @rtype: None @returns: no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DNSConfig:
"""Represents the DNS configuration screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
self.__screen = screen
self.__dns = DNS()
self.__hostnameLabel = Label('Hostname')
self.__primaryDNS... | the_stack_v2_python_sparse | zfrobisher-installer/src/ui/networkcfg/dnsconfig.py | fedosu85nce/work | train | 2 |
ee2c801c1b275cce525003c47caa7225648ff0a3 | [
"self.capacity = capacity\nself.head = Node(0, 0)\nself.tail = Node(0, 0)\nself.head.next = self.tail\nself.tail.previous = self.head\nself.map = {}",
"current = self.tail.previous\ncurrent.next = node\nnode.previous = current\nself.tail.previous = node\nnode.next = self.tail",
"previous_node = node.previous\nn... | <|body_start_0|>
self.capacity = capacity
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.previous = self.head
self.map = {}
<|end_body_0|>
<|body_start_1|>
current = self.tail.previous
current.next = node
node.p... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used... | stack_v2_sparse_classes_36k_train_034679 | 4,381 | no_license | [
{
"docstring": ":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used for a constant lookup for the corresponding node i... | 5 | stack_v2_sparse_classes_30k_train_018929 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: ... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: ... | 01cba9d7bf940fbfcaa4dfe15afdb9733e726e22 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":param capacity: the defined capacity of the cache =================================== This method initializes a doubly linked list with two nodes: head and tail, connected to one another. A map is also initialized. Given a key, this map is used for a constan... | the_stack_v2_python_sparse | AlgorithmProblems/leetcode_146.py | nabinn/DS_and_Algorithms | train | 1 | |
b0a9b5c6755d7d9a1412ad1f0b23b31050b7ef8a | [
"params = {'part': enf_parts(resource='playlistItems', value=parts), 'maxResults': max_results, 'onBehalfOfContentOwner': on_behalf_of_content_owner, 'videoId': video_id, 'pageToken': page_token, **kwargs}\nif playlist_item_id is not None:\n params['id'] = enf_comma_separated(field='playlist_item_id', value=play... | <|body_start_0|>
params = {'part': enf_parts(resource='playlistItems', value=parts), 'maxResults': max_results, 'onBehalfOfContentOwner': on_behalf_of_content_owner, 'videoId': video_id, 'pageToken': page_token, **kwargs}
if playlist_item_id is not None:
params['id'] = enf_comma_separated(fi... | A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource is used in that playlist. References: https://developers.google.com/youtube/v3/docs/pla... | PlaylistItemsResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaylistItemsResource:
"""A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource is used in that playlist. References: ... | stack_v2_sparse_classes_36k_train_034680 | 10,667 | permissive | [
{
"docstring": "Returns a collection of playlist items that match the API request parameters. Args: parts: Comma-separated list of one or more channel resource properties. Accepted values: id,contentDetails,snippet,snippet playlist_item_id: Specifies a comma-separated list of one or more unique playlist item ID... | 4 | null | Implement the Python class `PlaylistItemsResource` described below.
Class description:
A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource... | Implement the Python class `PlaylistItemsResource` described below.
Class description:
A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource... | 1ed2f67a55b8df75c5fab9aacd7d9ff4d460812a | <|skeleton|>
class PlaylistItemsResource:
"""A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource is used in that playlist. References: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaylistItemsResource:
"""A playlistItem resource identifies another resource, such as a video, that is included in a playlist. In addition, the playlistItem resource contains details about the included resource that pertain specifically to how that resource is used in that playlist. References: https://devel... | the_stack_v2_python_sparse | pyyoutube/resources/playlist_items.py | sns-sdks/python-youtube | train | 249 |
6b04bb6d719f32a86b1bc83ce357179226385ced | [
"self.num_hypotheses = num_hypotheses\nself.__name__ = 'mhp_loss'\nif avg_weight > 0.25 or avg_weight < 0.0:\n raise RuntimeError('avg_weight must be in [0,0.25]')\nself.avg_weight = avg_weight\nself.min_weight = 1.0 - self.avg_weight\nself.kl_weight = 0.001\nself.loss = keras.losses.get(loss)",
"xsum = tf.zer... | <|body_start_0|>
self.num_hypotheses = num_hypotheses
self.__name__ = 'mhp_loss'
if avg_weight > 0.25 or avg_weight < 0.0:
raise RuntimeError('avg_weight must be in [0,0.25]')
self.avg_weight = avg_weight
self.min_weight = 1.0 - self.avg_weight
self.kl_weight ... | Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning in an Uncertain World: ... | MhpLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl... | stack_v2_sparse_classes_36k_train_034681 | 7,780 | permissive | [
{
"docstring": "Set up the MHP loss function. Parameters: ----------- num_hypotheses: number of targets to generate (e.g., predict 8 possible future images). num_outputs: number of output variables per hypothesis (e.g., 64x64x3 for a 64x64 RGB image). Currently deprecated, but may be necessary later on.",
"... | 2 | stack_v2_sparse_classes_30k_train_010935 | Implement the Python class `MhpLoss` described below.
Class description:
Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe... | Implement the Python class `MhpLoss` described below.
Class description:
Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe... | be5c12f9d0e9d7078e6a5c283d3be059e7f3d040 | <|skeleton|>
class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning i... | the_stack_v2_python_sparse | costar_models/python/costar_models/mhp_loss.py | lk-greenbird/costar_plan | train | 0 |
e2fd2c3475a04b9b74c8cdedccbade8187518e58 | [
"headers = {'Authorization': 'Bearer %s' % access_token}\ntry:\n resp = requests.get(ASANA_USER_DETAILS_URL, headers=headers)\n resp.raise_for_status()\n return resp.json()['data']\nexcept ValueError:\n return None",
"self.process_error(self.data)\nparams = self.auth_complete_params(self.validate_stat... | <|body_start_0|>
headers = {'Authorization': 'Bearer %s' % access_token}
try:
resp = requests.get(ASANA_USER_DETAILS_URL, headers=headers)
resp.raise_for_status()
return resp.json()['data']
except ValueError:
return None
<|end_body_0|>
<|body_star... | Asana OAuth authentication mechanism | AsanaAuth | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsanaAuth:
"""Asana OAuth authentication mechanism"""
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
<|b... | stack_v2_sparse_classes_36k_train_034682 | 2,537 | permissive | [
{
"docstring": "Loads user data from service",
"name": "user_data",
"signature": "def user_data(self, access_token, *args, **kwargs)"
},
{
"docstring": "Completes loging process, must return user instance",
"name": "auth_complete",
"signature": "def auth_complete(self, *args, **kwargs)"
... | 2 | stack_v2_sparse_classes_30k_train_011353 | Implement the Python class `AsanaAuth` described below.
Class description:
Asana OAuth authentication mechanism
Method signatures and docstrings:
- def user_data(self, access_token, *args, **kwargs): Loads user data from service
- def auth_complete(self, *args, **kwargs): Completes loging process, must return user in... | Implement the Python class `AsanaAuth` described below.
Class description:
Asana OAuth authentication mechanism
Method signatures and docstrings:
- def user_data(self, access_token, *args, **kwargs): Loads user data from service
- def auth_complete(self, *args, **kwargs): Completes loging process, must return user in... | 36a02ed244c7b59ee1f2523e64e4749e404ab0f7 | <|skeleton|>
class AsanaAuth:
"""Asana OAuth authentication mechanism"""
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsanaAuth:
"""Asana OAuth authentication mechanism"""
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
headers = {'Authorization': 'Bearer %s' % access_token}
try:
resp = requests.get(ASANA_USER_DETAILS_URL, headers=headers)
... | the_stack_v2_python_sparse | src/social_auth/backends/asana.py | commonlims/commonlims | train | 4 |
b5a17feb0cf2e307c41f6a92b510c9d3e7b690e8 | [
"self.user = user\nself.workspace = workspace\nself.job_name = workflow_name\nself.safe_job_name = ''.join((s for s in self.job_name if s.isalnum()))\nself.input_archive_path = input_archive_path\nself.xll = xll\nself.yll = yll\nself.rotation = rotation\nself.model_units = model_units\nself.model_version = model_ve... | <|body_start_0|>
self.user = user
self.workspace = workspace
self.job_name = workflow_name
self.safe_job_name = ''.join((s for s in self.job_name if s.isalnum()))
self.input_archive_path = input_archive_path
self.xll = xll
self.yll = yll
self.rotation = ro... | Helper class that prepares and submits the new project upload jobs and workflow. | ProjectUploadWorkflow | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectUploadWorkflow:
"""Helper class that prepares and submits the new project upload jobs and workflow."""
def __init__(self, user, workspace, workflow_name, input_archive_path, xll, yll, rotation, model_units, model_version, srid, resource_db_url, resource_id, scenario_id, model_db, gs_e... | stack_v2_sparse_classes_36k_train_034683 | 6,106 | permissive | [
{
"docstring": "Constructor. Args: user(auth.User): Django user. workflow_name(str): Name of the job. input_archive_path(str): Path to input zip archive. xll(float): lower left x coordinate for model yll(float): lower left y coordinate for model rotation: model rotation (counter clockwise) model_units(str): mod... | 3 | null | Implement the Python class `ProjectUploadWorkflow` described below.
Class description:
Helper class that prepares and submits the new project upload jobs and workflow.
Method signatures and docstrings:
- def __init__(self, user, workspace, workflow_name, input_archive_path, xll, yll, rotation, model_units, model_vers... | Implement the Python class `ProjectUploadWorkflow` described below.
Class description:
Helper class that prepares and submits the new project upload jobs and workflow.
Method signatures and docstrings:
- def __init__(self, user, workspace, workflow_name, input_archive_path, xll, yll, rotation, model_units, model_vers... | 5e662d8346f2ffd414ac912a531eef06c5ae79d9 | <|skeleton|>
class ProjectUploadWorkflow:
"""Helper class that prepares and submits the new project upload jobs and workflow."""
def __init__(self, user, workspace, workflow_name, input_archive_path, xll, yll, rotation, model_units, model_version, srid, resource_db_url, resource_id, scenario_id, model_db, gs_e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectUploadWorkflow:
"""Helper class that prepares and submits the new project upload jobs and workflow."""
def __init__(self, user, workspace, workflow_name, input_archive_path, xll, yll, rotation, model_units, model_version, srid, resource_db_url, resource_id, scenario_id, model_db, gs_engine, app_pa... | the_stack_v2_python_sparse | tethysapp/modflow/condor_workflows/project_upload.py | Aquaveo/tethysapp-modflow | train | 0 |
0d51a587d0e721efa6423b6fc817f8675729a145 | [
"self.hierarchy = Hierarchy()\nself.assertIsNone(self.hierarchy.Parent.Key)\nself.assertEqual(self.hierarchy.Parent.Name, '')\nself.assertIsNone(self.hierarchy.BranchBool)\nself.assertEqual(self.hierarchy.Branch, BranchType.LEAF)\nself.assertFalse(self.hierarchy.HasChild)",
"self.hierarchy = Hierarchy()\nself.hie... | <|body_start_0|>
self.hierarchy = Hierarchy()
self.assertIsNone(self.hierarchy.Parent.Key)
self.assertEqual(self.hierarchy.Parent.Name, '')
self.assertIsNone(self.hierarchy.BranchBool)
self.assertEqual(self.hierarchy.Branch, BranchType.LEAF)
self.assertFalse(self.hierarch... | HierarchyTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HierarchyTests:
def test_empty_constructor(self):
"""Автор: Краснов Д.В."""
<|body_0|>
def test_add_set_get_hierarchy(self):
"""Автор: Краснов Д.В."""
<|body_1|>
def test_filled_constructor_1(self):
"""Автор: Краснов Д.В."""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_034684 | 20,083 | no_license | [
{
"docstring": "Автор: Краснов Д.В.",
"name": "test_empty_constructor",
"signature": "def test_empty_constructor(self)"
},
{
"docstring": "Автор: Краснов Д.В.",
"name": "test_add_set_get_hierarchy",
"signature": "def test_add_set_get_hierarchy(self)"
},
{
"docstring": "Автор: Кра... | 6 | stack_v2_sparse_classes_30k_train_012173 | Implement the Python class `HierarchyTests` described below.
Class description:
Implement the HierarchyTests class.
Method signatures and docstrings:
- def test_empty_constructor(self): Автор: Краснов Д.В.
- def test_add_set_get_hierarchy(self): Автор: Краснов Д.В.
- def test_filled_constructor_1(self): Автор: Красно... | Implement the Python class `HierarchyTests` described below.
Class description:
Implement the HierarchyTests class.
Method signatures and docstrings:
- def test_empty_constructor(self): Автор: Краснов Д.В.
- def test_add_set_get_hierarchy(self): Автор: Краснов Д.В.
- def test_filled_constructor_1(self): Автор: Красно... | 5559275accbfda0cb75c8c90d79090c10524e815 | <|skeleton|>
class HierarchyTests:
def test_empty_constructor(self):
"""Автор: Краснов Д.В."""
<|body_0|>
def test_add_set_get_hierarchy(self):
"""Автор: Краснов Д.В."""
<|body_1|>
def test_filled_constructor_1(self):
"""Автор: Краснов Д.В."""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HierarchyTests:
def test_empty_constructor(self):
"""Автор: Краснов Д.В."""
self.hierarchy = Hierarchy()
self.assertIsNone(self.hierarchy.Parent.Key)
self.assertEqual(self.hierarchy.Parent.Name, '')
self.assertIsNone(self.hierarchy.BranchBool)
self.assertEqual(s... | the_stack_v2_python_sparse | test_api/other_classes.py | 4l1fe/miscellaneous | train | 0 | |
f2f2e397e5c3d816e0664f9b35e93a2710c3b6b4 | [
"so_far = []\n\ndef dfs(node):\n if not node:\n so_far.append('None')\n return\n so_far.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ','.join(so_far)",
"def create_tree(node_list):\n first_elem_val = node_list.pop(0)\n if first_elem_val == 'None':\n ... | <|body_start_0|>
so_far = []
def dfs(node):
if not node:
so_far.append('None')
return
so_far.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(so_far)
<|end_body_0|>
<|body_star... | 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_36k_train_034685 | 2,410 | 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 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: 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:... | a5635356953df472e71d49c8db3b493ac59b860f | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
so_far = []
def dfs(node):
if not node:
so_far.append('None')
return
so_far.append(str(node.val))
dfs(node.le... | the_stack_v2_python_sparse | python/tree/q449_serialize_second.py | ksparkje/leetcode-practice | train | 1 | |
8737a8630b66163a17fb36ed2fbb2ca7f5b346df | [
"super(LimitedOffsetDataProvider, self).__init__(source, **kwargs)\nself.offset = max(offset, 0)\nself.limit = limit\nif self.limit is not None:\n self.limit = max(self.limit, 0)",
"if self.limit is not None and self.limit <= 0:\n return\nparent_gen = super(LimitedOffsetDataProvider, self).__iter__()\nfor d... | <|body_start_0|>
super(LimitedOffsetDataProvider, self).__init__(source, **kwargs)
self.offset = max(offset, 0)
self.limit = limit
if self.limit is not None:
self.limit = max(self.limit, 0)
<|end_body_0|>
<|body_start_1|>
if self.limit is not None and self.limit <= 0... | A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination). | LimitedOffsetDataProvider | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwar... | stack_v2_sparse_classes_36k_train_034686 | 12,222 | permissive | [
{
"docstring": ":param offset: the number of data to skip before providing. :param limit: the final number of data to provide.",
"name": "__init__",
"signature": "def __init__(self, source, offset=0, limit=None, **kwargs)"
},
{
"docstring": "Iterate over the source until `num_valid_data_read` is... | 2 | null | Implement the Python class `LimitedOffsetDataProvider` described below.
Class description:
A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination).
Method signatures and d... | Implement the Python class `LimitedOffsetDataProvider` described below.
Class description:
A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination).
Method signatures and d... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwargs):
... | the_stack_v2_python_sparse | lib/galaxy/datatypes/dataproviders/base.py | bwlang/galaxy | train | 0 |
81da836e0eaa2bd70607388b820d6a22a3effb09 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LicenseDetails()",
"from .entity import Entity\nfrom .service_plan_info import ServicePlanInfo\nfrom .entity import Entity\nfrom .service_plan_info import ServicePlanInfo\nfields: Dict[str, Callable[[Any], None]] = {'servicePlans': lam... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LicenseDetails()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .service_plan_info import ServicePlanInfo
from .entity import Entity
from .service_plan_i... | LicenseDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""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 Retur... | stack_v2_sparse_classes_36k_train_034687 | 2,913 | 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: LicenseDetails",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_009035 | Implement the Python class `LicenseDetails` described below.
Class description:
Implement the LicenseDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `LicenseDetails` described below.
Class description:
Implement the LicenseDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""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 Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LicenseDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LicenseDetails:
"""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: LicenseDet... | the_stack_v2_python_sparse | msgraph/generated/models/license_details.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
47d936a5d011a33fef8769f507ec7256d1f8d6d1 | [
"self.size = size\nself.vals = []\nself.count = 0.0\nself.ptr = 0",
"self.vals.append(float(val))\nself.count += val\nif len(self.vals) > self.size:\n self.count -= self.vals[self.ptr]\n self.ptr += 1\n return self.count / self.size\nreturn self.count / len(self.vals)"
] | <|body_start_0|>
self.size = size
self.vals = []
self.count = 0.0
self.ptr = 0
<|end_body_0|>
<|body_start_1|>
self.vals.append(float(val))
self.count += val
if len(self.vals) > self.size:
self.count -= self.vals[self.ptr]
self.ptr += 1
... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.vals = ... | stack_v2_sparse_classes_36k_train_034688 | 1,316 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.vals = []
self.count = 0.0
self.ptr = 0
def next(self, val):
""":type val: int :rtype: float"""
self.vals.append(float(val))
... | the_stack_v2_python_sparse | Python/346__Moving_Average_from_Data_Stream.py | FIRESTROM/Leetcode | train | 2 | |
255a3bee33240a8eeed8f7028cebc14f4b157d47 | [
"fp = StringIO()\ng = generator.Generator(fp, mangle_from_=False)\ng.flatten(self, unixfrom=unixfrom, linesep=linesep)\nreturn fp.getvalue()",
"fp = BytesIO()\ng = generator.BytesGenerator(fp, mangle_from_=False)\ng.flatten(self, unixfrom=unixfrom, linesep=linesep)\nreturn fp.getvalue()"
] | <|body_start_0|>
fp = StringIO()
g = generator.Generator(fp, mangle_from_=False)
g.flatten(self, unixfrom=unixfrom, linesep=linesep)
return fp.getvalue()
<|end_body_0|>
<|body_start_1|>
fp = BytesIO()
g = generator.BytesGenerator(fp, mangle_from_=False)
g.flatten... | MIMEMixin | [
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"Python-2.0.1",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MIMEMixin:
def as_string(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '... | stack_v2_sparse_classes_36k_train_034689 | 17,809 | permissive | [
{
"docstring": "Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details.",
"name": "as_string",
"signature":... | 2 | null | Implement the Python class `MIMEMixin` described below.
Class description:
Implement the MIMEMixin class.
Method signatures and docstrings:
- def as_string(self, unixfrom=False, linesep='\n'): Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header.... | Implement the Python class `MIMEMixin` described below.
Class description:
Implement the MIMEMixin class.
Method signatures and docstrings:
- def as_string(self, unixfrom=False, linesep='\n'): Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header.... | c74a6fad5475495756a5bdb18b2cab2b68d429bc | <|skeleton|>
class MIMEMixin:
def as_string(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MIMEMixin:
def as_string(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #134... | the_stack_v2_python_sparse | django/core/mail/message.py | django/django | train | 73,530 | |
3a4b5445d056702f1cf55f9a72c23f98ee67eaad | [
"gs = GridSpec(7, 1)\nax_spectrum, ax_residuals = get_axes(ax_spectrum, ax_residuals, 8, 7, [gs[:5, :]], [gs[5:, :]], kwargs2={'sharex': ax_spectrum})\nkwargs_spectrum = kwargs_spectrum or {}\nkwargs_residuals = kwargs_residuals or {}\nself.plot_excess(ax_spectrum, **kwargs_spectrum)\nself.plot_residuals_spectral(a... | <|body_start_0|>
gs = GridSpec(7, 1)
ax_spectrum, ax_residuals = get_axes(ax_spectrum, ax_residuals, 8, 7, [gs[:5, :]], [gs[5:, :]], kwargs2={'sharex': ax_spectrum})
kwargs_spectrum = kwargs_spectrum or {}
kwargs_residuals = kwargs_residuals or {}
self.plot_excess(ax_spectrum, **... | Plot mixin for the spectral datasets. | PlotMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotMixin:
"""Plot mixin for the spectral datasets."""
def plot_fit(self, ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None):
"""Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.plot_excess` and `~SpectrumDataset.plot_residuals_spectra... | stack_v2_sparse_classes_36k_train_034690 | 14,646 | permissive | [
{
"docstring": "Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.plot_excess` and `~SpectrumDataset.plot_residuals_spectral`. Parameters ---------- ax_spectrum : `~matplotlib.axes.Axes` Axes to plot spectrum on ax_residuals : `~matplotlib.axes.Axes` Axes to plot residuals on kwargs_spectrum : ... | 5 | null | Implement the Python class `PlotMixin` described below.
Class description:
Plot mixin for the spectral datasets.
Method signatures and docstrings:
- def plot_fit(self, ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None): Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.... | Implement the Python class `PlotMixin` described below.
Class description:
Plot mixin for the spectral datasets.
Method signatures and docstrings:
- def plot_fit(self, ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None): Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.... | 60f03adb8fc7851b9f3ca039512c03a669e3fe10 | <|skeleton|>
class PlotMixin:
"""Plot mixin for the spectral datasets."""
def plot_fit(self, ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None):
"""Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.plot_excess` and `~SpectrumDataset.plot_residuals_spectra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlotMixin:
"""Plot mixin for the spectral datasets."""
def plot_fit(self, ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None):
"""Plot spectrum and residuals in two panels. Calls `~SpectrumDataset.plot_excess` and `~SpectrumDataset.plot_residuals_spectral`. Parameter... | the_stack_v2_python_sparse | gammapy/datasets/spectrum.py | gammapy/gammapy | train | 204 |
9f29d6160eb058ee132b67d102ac0028e0396e06 | [
"fig = fig or kwargs.pop('fig', None)\nif fig is None:\n fig = pyplot.gcf()\nelif not isinstance(fig, Figure):\n fig = pyplot.figure(fig)\nif len(args) == 0:\n args = (111,)\nif not hasattr(series, 'ensoindices'):\n errmsg = 'ENSO indices should be defined for the input series!'\n raise AttributeErro... | <|body_start_0|>
fig = fig or kwargs.pop('fig', None)
if fig is None:
fig = pyplot.gcf()
elif not isinstance(fig, Figure):
fig = pyplot.figure(fig)
if len(args) == 0:
args = (111,)
if not hasattr(series, 'ensoindices'):
errmsg = 'EN... | Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the series to plot. ``series`` must be a :class:`~scikits.hydroclimpy.enso.ClimateSeries`, and ... | ENSOPhaseComparisonPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ENSOPhaseComparisonPlot:
"""Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the series to plot. ``series`` must be a :cl... | stack_v2_sparse_classes_36k_train_034691 | 17,056 | no_license | [
{
"docstring": "Initializes instance. Parameters ---------- fig : {None, figure instance} Figure from which the plot will depend. If None, the current figure is selected. series : ClimateSeries Series to convert. freq : {var}, optional A valid frequency specifier (as a string or integer), or a 3-letter string c... | 5 | stack_v2_sparse_classes_30k_train_009264 | Implement the Python class `ENSOPhaseComparisonPlot` described below.
Class description:
Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the s... | Implement the Python class `ENSOPhaseComparisonPlot` described below.
Class description:
Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the s... | 676501c18194b776d20102411463c6400d63db67 | <|skeleton|>
class ENSOPhaseComparisonPlot:
"""Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the series to plot. ``series`` must be a :cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ENSOPhaseComparisonPlot:
"""Class for plotting the comparison of data between ENSO phases. The object is instantiated with the same optional parameters as for a standard :class:`matplotlib.axes.Subplot`. The parameter ``series`` must be given to define the series to plot. ``series`` must be a :class:`~scikits... | the_stack_v2_python_sparse | scikits/hydroclimpy/plotlib/ensotools.py | pierregm/scikits.hydroclimpy | train | 8 |
99d77434a38ed9531a540b0057ec035d9f421b9b | [
"data = self.build_slack_message(feedback)\nresp = requests.post(self.webhook_url, json=data)\nif resp.status_code != 200:\n raise Exception('Slack notify failed with HTTP status %d' % resp.status_code)",
"with translation.override(self.language):\n message = gettext('New feedback received for {url}').forma... | <|body_start_0|>
data = self.build_slack_message(feedback)
resp = requests.post(self.webhook_url, json=data)
if resp.status_code != 200:
raise Exception('Slack notify failed with HTTP status %d' % resp.status_code)
<|end_body_0|>
<|body_start_1|>
with translation.override(se... | SlackNotifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlackNotifier:
def notify(self, feedback):
"""Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback"""
<|body_0|>
def build_slack_message(self, feedback):
"""Build a Slack message dict from the fee... | stack_v2_sparse_classes_36k_train_034692 | 5,707 | permissive | [
{
"docstring": "Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback",
"name": "notify",
"signature": "def notify(self, feedback)"
},
{
"docstring": "Build a Slack message dict from the feedback object. :param feedback: Feedb... | 4 | null | Implement the Python class `SlackNotifier` described below.
Class description:
Implement the SlackNotifier class.
Method signatures and docstrings:
- def notify(self, feedback): Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback
- def build_slac... | Implement the Python class `SlackNotifier` described below.
Class description:
Implement the SlackNotifier class.
Method signatures and docstrings:
- def notify(self, feedback): Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback
- def build_slac... | b0f99a0be768df3b3a0cae20fe29a4018cd67ef7 | <|skeleton|>
class SlackNotifier:
def notify(self, feedback):
"""Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback"""
<|body_0|>
def build_slack_message(self, feedback):
"""Build a Slack message dict from the fee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlackNotifier:
def notify(self, feedback):
"""Send a Slack notification for the given feedback. :param feedback: Feedback object :type feedback: feedback.models.Feedback"""
data = self.build_slack_message(feedback)
resp = requests.post(self.webhook_url, json=data)
if resp.statu... | the_stack_v2_python_sparse | feedback/models.py | enterstudio/digihel | train | 1 | |
111dfd63ea7e770057df4d10ea75fa20428291d7 | [
"self.players = []\nself.variant = None\nself.decks = None\nself.initialize_players()\nself.initialize_deck()\nself.initialize_game()",
"while True:\n try:\n player_count = int(input('Please enter the number of players. Enter in the range of 2 and 10 : '))\n if player_count < 2:\n rais... | <|body_start_0|>
self.players = []
self.variant = None
self.decks = None
self.initialize_players()
self.initialize_deck()
self.initialize_game()
<|end_body_0|>
<|body_start_1|>
while True:
try:
player_count = int(input('Please enter th... | Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome. | Game | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome."""
def __init__(self):
"""This constructor initializes a new game"""
<|body_0|>
def initialize_players(self):
"""This function initia... | stack_v2_sparse_classes_36k_train_034693 | 3,872 | permissive | [
{
"docstring": "This constructor initializes a new game",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function initializes new players based on the user input",
"name": "initialize_players",
"signature": "def initialize_players(self)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_011996 | Implement the Python class `Game` described below.
Class description:
Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome.
Method signatures and docstrings:
- def __init__(self): This constructor initializes a new game
- def initialize_players(self):... | Implement the Python class `Game` described below.
Class description:
Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome.
Method signatures and docstrings:
- def __init__(self): This constructor initializes a new game
- def initialize_players(self):... | d18a9f9a44f987cba3fe3f93fe8cec2afe950db4 | <|skeleton|>
class Game:
"""Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome."""
def __init__(self):
"""This constructor initializes a new game"""
<|body_0|>
def initialize_players(self):
"""This function initia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Game class initializes Players, Game variant and the Deck. This class also handles the gameplay and decides the outcome."""
def __init__(self):
"""This constructor initializes a new game"""
self.players = []
self.variant = None
self.decks = None
self.initi... | the_stack_v2_python_sparse | Game.py | abhinav-mk/War-Game | train | 0 |
969ba5f67f272118480f3b605466b5c231e24391 | [
"resultDict = {}\nfor pileupType in stepHelper.data.pileup.listSections_():\n datasets = getattr(getattr(stepHelper.data.pileup, pileupType), 'dataset')\n blockDict = {}\n for dataset in datasets:\n blockNames = dbsReader.listFileBlocks(dataset)\n for dbsBlockName in blockNames:\n ... | <|body_start_0|>
resultDict = {}
for pileupType in stepHelper.data.pileup.listSections_():
datasets = getattr(getattr(stepHelper.data.pileup, pileupType), 'dataset')
blockDict = {}
for dataset in datasets:
blockNames = dbsReader.listFileBlocks(dataset)... | Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox | PileupFetcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PileupFetcher:
"""Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox"""
def _queryDbsAndGetPileupConfig(self, stepHelper, dbsReader):
"""Method iterates over components of the pileup configuratio... | stack_v2_sparse_classes_36k_train_034694 | 4,412 | no_license | [
{
"docstring": "Method iterates over components of the pileup configuration input and queries DBS. Then iterates over results from DBS. There needs to be a list of files and their locations for each dataset name. Use dbsReader the result data structure is a Python dict following dictionary: FileList is a list o... | 3 | stack_v2_sparse_classes_30k_train_007664 | Implement the Python class `PileupFetcher` described below.
Class description:
Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox
Method signatures and docstrings:
- def _queryDbsAndGetPileupConfig(self, stepHelper, dbsReader): M... | Implement the Python class `PileupFetcher` described below.
Class description:
Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox
Method signatures and docstrings:
- def _queryDbsAndGetPileupConfig(self, stepHelper, dbsReader): M... | 122f9332f2e944154dd0df68b6b3f2875427b032 | <|skeleton|>
class PileupFetcher:
"""Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox"""
def _queryDbsAndGetPileupConfig(self, stepHelper, dbsReader):
"""Method iterates over components of the pileup configuratio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PileupFetcher:
"""Pull dataset block/SE : LFN list from DBS for the pileup datasets required by the steps in the job. Save these maps as files in the sandbox"""
def _queryDbsAndGetPileupConfig(self, stepHelper, dbsReader):
"""Method iterates over components of the pileup configuration input and q... | the_stack_v2_python_sparse | src/python/WMCore/WMSpec/Steps/Fetchers/PileupFetcher.py | cinquo/WMCore | train | 1 |
ff932b54247826da6aa74b34c4766d8df88cc3f6 | [
"i = 0\nj = 1\nif len(nums) == 1:\n pass\nelif len(nums) == 2:\n if nums[0] == 0:\n nums[0], nums[1] = (nums[1], nums[0])\nelse:\n while j < len(nums) and i < len(nums):\n while nums[i] != 0:\n i += 1\n if i == len(nums):\n break\n j = min(i, len(nu... | <|body_start_0|>
i = 0
j = 1
if len(nums) == 1:
pass
elif len(nums) == 2:
if nums[0] == 0:
nums[0], nums[1] = (nums[1], nums[0])
else:
while j < len(nums) and i < len(nums):
while nums[i] != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroesz(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_034695 | 1,451 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "mo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroesz(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroesz(self, nums): :type nums: List[int] :rtype: ... | 2903e5500e242768f5ae51f0cc875a2f291fcfff | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroesz(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
i = 0
j = 1
if len(nums) == 1:
pass
elif len(nums) == 2:
if nums[0] == 0:
nums[0], nums[1] = (num... | the_stack_v2_python_sparse | Move Zeroes/main.py | MSJYYT/LeetCode_with_Python | train | 0 | |
3491ad03c0f4d6f13dec2594eada7be988e69cd8 | [
"parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)\nUnmarshaller._unmarshal_relationships(pkg_reader, package, parts)\nfor part in parts.values():\n part.after_unmarshal()\npackage.after_unmarshal()",
"parts = {}\nfor partname, content_type, blob in pkg_reader.iter_sparts():\n parts[p... | <|body_start_0|>
parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)
Unmarshaller._unmarshal_relationships(pkg_reader, package, parts)
for part in parts.values():
part.after_unmarshal()
package.after_unmarshal()
<|end_body_0|>
<|body_start_1|>
pa... | Hosts static methods for unmarshalling a package from a |PackageReader| instance. | Unmarshaller | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t... | stack_v2_sparse_classes_36k_train_034696 | 20,155 | permissive | [
{
"docstring": "Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_factory*. Package relationships are added to *pkg*.",
"name": "unmarshal",
"signature": "def unmarshal(pkg_reader, package, part_factory)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_015635 | Implement the Python class `Unmarshaller` described below.
Class description:
Hosts static methods for unmarshalling a package from a |PackageReader| instance.
Method signatures and docstrings:
- def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content... | Implement the Python class `Unmarshaller` described below.
Class description:
Hosts static methods for unmarshalling a package from a |PackageReader| instance.
Method signatures and docstrings:
- def unmarshal(pkg_reader, package, part_factory): Construct graph of parts and realized relationships based on the content... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unmarshaller:
"""Hosts static methods for unmarshalling a package from a |PackageReader| instance."""
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of *pkg_reader*, delegating construction of each part to *part_facto... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/opc/package.py | ryfeus/lambda-packs | train | 1,283 |
58223a5755289cb41d090f31f16a1f492c9f3b46 | [
"Amino.__init__(self, atoms, ref)\nself.reference = ref\nself.SSbonded = 0\nself.SSbondedpartner = None",
"if 'CYX' in self.patches or self.name == 'CYX':\n self.ffname = 'CYX'\nelif self.SSbonded:\n self.ffname = 'CYX'\nelif 'CYM' in self.patches or self.name == 'CYM':\n self.ffname = 'CYM'\nelif not se... | <|body_start_0|>
Amino.__init__(self, atoms, ref)
self.reference = ref
self.SSbonded = 0
self.SSbondedpartner = None
<|end_body_0|>
<|body_start_1|>
if 'CYX' in self.patches or self.name == 'CYX':
self.ffname = 'CYX'
elif self.SSbonded:
self.ffnam... | Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class. | CYS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CYS:
"""Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
def setSta... | stack_v2_sparse_classes_36k_train_034697 | 22,508 | permissive | [
{
"docstring": "Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)",
"name": "__init__",
"signature": "def __init__(self, atoms, ref)"
},
{
"docstring": "Set the state of the CYS object. If SS-bonded, use CYX. If negatively charged, use CYM. If HG is ... | 2 | stack_v2_sparse_classes_30k_train_007724 | Implement the Python class `CYS` described below.
Class description:
Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to be stored i... | Implement the Python class `CYS` described below.
Class description:
Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to be stored i... | a50f0b2f7104007c730baa51b4ec65c891008c47 | <|skeleton|>
class CYS:
"""Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
def setSta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CYS:
"""Cysteine class This class gives data about the Cysteine object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
Amino.__init__(self, atoms, ref)
... | the_stack_v2_python_sparse | mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/src/aa.py | e-mayo/mscreen | train | 10 |
7f91ea3c98907597d5448f682966786f1d91b46c | [
"super().__init__(cookie)\nsymbols, count = self._parse_cookie()\nself._symbols = symbols\nself._count = count",
"symbols = re.split('([=:&])', self._value)\nlast = (len(symbols) - 3) // 4\ncount = last + 1\nreturn (symbols, count)",
"replacement = copy(self._symbols)\ncurrent = index * 4 + 2\nreplacement[curre... | <|body_start_0|>
super().__init__(cookie)
symbols, count = self._parse_cookie()
self._symbols = symbols
self._count = count
<|end_body_0|>
<|body_start_1|>
symbols = re.split('([=:&])', self._value)
last = (len(symbols) - 3) // 4
count = last + 1
return (... | This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string. | ComplexCookie | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""S... | stack_v2_sparse_classes_36k_train_034698 | 3,236 | permissive | [
{
"docstring": "Sets the string, parses the cookie into tokens, and sets the value count.",
"name": "__init__",
"signature": "def __init__(self, cookie)"
},
{
"docstring": "Parse the cookie into a set of tokens to specify key/value pairs and delimiters. Cookie strings are decomposed by =, then :... | 4 | stack_v2_sparse_classes_30k_train_020524 | Implement the Python class `ComplexCookie` described below.
Class description:
This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string.
Method s... | Implement the Python class `ComplexCookie` described below.
Class description:
This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string.
Method s... | 4483b301034a096b716646a470a6642b3df8ce61 | <|skeleton|>
class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""Sets the strin... | the_stack_v2_python_sparse | ava/parsers/cookie.py | indeedsecurity/ava-ce | train | 3 |
70d1bbbb1fd62a2b977b7f956e3d36e29dd047ec | [
"assert dataset in ('europarl7', 'un2000'), 'invalid dataset'\nprocessed_file = os.path.join(path, dataset + '-' + split + '.h5')\nassert os.path.exists(processed_file), \"Dataset at '\" + processed_file + \"' not found\"\nself.subset_pct = subset_pct\nsuper(TextNMT, self).__init__(time_steps, processed_file, vocab... | <|body_start_0|>
assert dataset in ('europarl7', 'un2000'), 'invalid dataset'
processed_file = os.path.join(path, dataset + '-' + split + '.h5')
assert os.path.exists(processed_file), "Dataset at '" + processed_file + "' not found"
self.subset_pct = subset_pct
super(TextNMT, self... | Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text file. tokenizer (function) : Tokenizer function. onehot_input (boolean): On... | TextNMT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextNMT:
"""Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text file. tokenizer (function) : Tokenizer f... | stack_v2_sparse_classes_36k_train_034699 | 22,856 | permissive | [
{
"docstring": "Load French and English sentence data from file.",
"name": "__init__",
"signature": "def __init__(self, time_steps, path, tokenizer=None, onehot_input=False, get_prev_target=False, split=None, dataset='un2000', subset_pct=100)"
},
{
"docstring": "Tokenizer and vocab are unused bu... | 2 | stack_v2_sparse_classes_30k_train_008778 | Implement the Python class `TextNMT` described below.
Class description:
Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text f... | Implement the Python class `TextNMT` described below.
Class description:
Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text f... | cba318c9f0a2acf2ab8a3d7725b588b2a8b17cb9 | <|skeleton|>
class TextNMT:
"""Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text file. tokenizer (function) : Tokenizer f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextNMT:
"""Datasets for neural machine translation on French / English bilingual datasets. Available at http://www-lium.univ-lemans.fr/~schwenk/cslm_joint_paper/data/bitexts.tgz Arguments: time_steps (int) : Length of a sequence. path (str) : Path to text file. tokenizer (function) : Tokenizer function. oneh... | the_stack_v2_python_sparse | neon/data/text.py | anlthms/neon | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.