blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
93da32f98d204be5e1e010852b8b6442f9a335b4
[ "credentials = service_account.Credentials.from_service_account_file(filename)\nkwargs['credentials'] = credentials\nreturn cls(*args, **kwargs)", "if client_config is not None:\n warnings.warn('The `client_config` argument is deprecated.', PendingDeprecationWarning, stacklevel=2)\nelse:\n client_config = g...
<|body_start_0|> credentials = service_account.Credentials.from_service_account_file(filename) kwargs['credentials'] = credentials return cls(*args, **kwargs) <|end_body_0|> <|body_start_1|> if client_config is not None: warnings.warn('The `client_config` argument is depreca...
Service to fetch data and metrics across resources.
GoogleAdsServiceClient
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleAdsServiceClient: """Service to fetch data and metrics across resources.""" def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private ke...
stack_v2_sparse_classes_75kplus_train_068600
15,850
permissive
[ { "docstring": "Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: GoogleAdsServiceClient: Th...
4
null
Implement the Python class `GoogleAdsServiceClient` described below. Class description: Service to fetch data and metrics across resources. Method signatures and docstrings: - def from_service_account_file(cls, filename, *args, **kwargs): Creates an instance of this client using the provided credentials file. Args: f...
Implement the Python class `GoogleAdsServiceClient` described below. Class description: Service to fetch data and metrics across resources. Method signatures and docstrings: - def from_service_account_file(cls, filename, *args, **kwargs): Creates an instance of this client using the provided credentials file. Args: f...
0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a
<|skeleton|> class GoogleAdsServiceClient: """Service to fetch data and metrics across resources.""" def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private ke...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GoogleAdsServiceClient: """Service to fetch data and metrics across resources.""" def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. ...
the_stack_v2_python_sparse
google/ads/google_ads/v1/services/google_ads_service_client.py
juanmacugat/google-ads-python
train
1
67a1c4bd52df576b0ffbb7180ccd00fcc7f6ec34
[ "if self.singledot is not None and self.doubledot is not None and (self.dotregime is not None):\n return True\nelse:\n return False", "if self.pinchoff is not None:\n return True\nelse:\n return False" ]
<|body_start_0|> if self.singledot is not None and self.doubledot is not None and (self.dotregime is not None): return True else: return False <|end_body_0|> <|body_start_1|> if self.pinchoff is not None: return True else: return False <|e...
Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier): pre-trained double dot classifier. dotregime (optional nt.Classifier): pre-tr...
Classifiers
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Classifiers: """Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier): pre-trained double dot classifier. dot...
stack_v2_sparse_classes_75kplus_train_068601
7,268
permissive
[ { "docstring": "Checks if dot classifiers are specified/not None. If so, the `Classifiers` instance can be used in a dot tuning algorithm.", "name": "is_dot_classifier", "signature": "def is_dot_classifier(self) -> bool" }, { "docstring": "Checks if pinch-off classifier is specified/not None. If...
2
stack_v2_sparse_classes_30k_test_002193
Implement the Python class `Classifiers` described below. Class description: Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier):...
Implement the Python class `Classifiers` described below. Class description: Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier):...
caf50f78c335cd1af4ed11e02c100ddf8d6755a5
<|skeleton|> class Classifiers: """Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier): pre-trained double dot classifier. dot...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Classifiers: """Class grouping binary classifiers required for tuning. Parameters: pinchoff (optional nt.Classifier): pre-trained pinch-off classifier. singledot (optional nt.Classifier): pre-trained single dot classifier. doubledot (optional nt.Classifier): pre-trained double dot classifier. dotregime (optio...
the_stack_v2_python_sparse
nanotune/tuningstages/settings.py
picarro-yren/nanotune
train
0
8f92fec21b8ed7ef95084dc8d6440f8bf40bb6f5
[ "if head == None:\n return None\np1 = None\np2 = head\nwhile p2:\n tmp = p2.next\n p2.next = p1\n p1 = p2\n p2 = tmp\nreturn p1", "if head == None or head.next == None:\n return True\nfast = head\nslow = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\nif fast:\n...
<|body_start_0|> if head == None: return None p1 = None p2 = head while p2: tmp = p2.next p2.next = p1 p1 = p2 p2 = tmp return p1 <|end_body_0|> <|body_start_1|> if head == None or head.next == None: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if head == None: return None...
stack_v2_sparse_classes_75kplus_train_068602
1,409
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }, { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, head)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def isPalindrome(self, head): :type head: ListNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def isPalindrome(self, head): :type head: ListNode :rtype: bool <|skeleton|> class Solution: def revers...
1520e1e9bb0c428797a3e5234e5b328110472c20
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" if head == None: return None p1 = None p2 = head while p2: tmp = p2.next p2.next = p1 p1 = p2 p2 = tmp return p1 d...
the_stack_v2_python_sparse
LinkedList/234. Palindrome Linked List.py
tinkle1129/Leetcode_Solution
train
0
2691cb02c918312249e2d85878b4ff3ffd0b1cb0
[ "for i in range(retries):\n try:\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.connect((host, port))\n return client\n except ConnectionRefusedError:\n client.close()\n if startup is not None and i == 0:\n startup()\n elif i == retri...
<|body_start_0|> for i in range(retries): try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((host, port)) return client except ConnectionRefusedError: client.close() if startup is...
Various socket convenience functions
SocketUtils
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocketUtils: """Various socket convenience functions""" def connect(host: str, port: int, retries=5, retrygap=2, startup=None): """Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname to connect to :param port: port # :param retries: number o...
stack_v2_sparse_classes_75kplus_train_068603
2,213
permissive
[ { "docstring": "Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname to connect to :param port: port # :param retries: number of retries to connect :param retrygap: time to sleep between retries in seconds :param startup: function to be called to start server if server ...
2
stack_v2_sparse_classes_30k_train_046729
Implement the Python class `SocketUtils` described below. Class description: Various socket convenience functions Method signatures and docstrings: - def connect(host: str, port: int, retries=5, retrygap=2, startup=None): Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname t...
Implement the Python class `SocketUtils` described below. Class description: Various socket convenience functions Method signatures and docstrings: - def connect(host: str, port: int, retries=5, retrygap=2, startup=None): Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname t...
6692749712fd5c654f467f658833ad91fb7e32be
<|skeleton|> class SocketUtils: """Various socket convenience functions""" def connect(host: str, port: int, retries=5, retrygap=2, startup=None): """Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname to connect to :param port: port # :param retries: number o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SocketUtils: """Various socket convenience functions""" def connect(host: str, port: int, retries=5, retrygap=2, startup=None): """Create TCP/IP stream-based connection to given host / port, with retries :param host: hostname to connect to :param port: port # :param retries: number of retries to ...
the_stack_v2_python_sparse
src/Python/pyDotNet/src/pydotnet/core/io/SocketUtils.py
stjordanis/.Net-Bridge
train
1
c55f1e260e27665a32fea9d7d8a92c8ed12268af
[ "logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.ppx = 0.0\nself.ppy = 0.0\nself.ppz = 0.0\nself.pvx = 0.0\nself.pvy = 0.0\nself.pvz = 0.0\nself.p = self.blender_obj.position\nself.v = [0.0, 0.0, 0.0]\nself.pv = [0.0, 0.0, 0.0]\nself.a = [0.0, 0.0, 0.0]\nself.tic...
<|body_start_0|> logger.info('%s initialization' % obj.name) super(self.__class__, self).__init__(obj, parent) self.ppx = 0.0 self.ppy = 0.0 self.ppz = 0.0 self.pvx = 0.0 self.pvy = 0.0 self.pvz = 0.0 self.p = self.blender_obj.position self...
Accelerometer sensor
AccelerometerClass
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccelerometerClass: """Accelerometer sensor""" def __init__(self, obj, parent=None): """Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.""" <|body_0|> def default_action(self): """Co...
stack_v2_sparse_classes_75kplus_train_068604
3,250
permissive
[ { "docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.", "name": "__init__", "signature": "def __init__(self, obj, parent=None)" }, { "docstring": "Compute the speed and accleration of the robot The speed ...
2
stack_v2_sparse_classes_30k_test_000064
Implement the Python class `AccelerometerClass` described below. Class description: Accelerometer sensor Method signatures and docstrings: - def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent. - def def...
Implement the Python class `AccelerometerClass` described below. Class description: Accelerometer sensor Method signatures and docstrings: - def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent. - def def...
07fcb64fea3b58b258e917eb1aed0a585f863418
<|skeleton|> class AccelerometerClass: """Accelerometer sensor""" def __init__(self, obj, parent=None): """Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.""" <|body_0|> def default_action(self): """Co...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccelerometerClass: """Accelerometer sensor""" def __init__(self, obj, parent=None): """Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.""" logger.info('%s initialization' % obj.name) super(self.__cla...
the_stack_v2_python_sparse
src/morse/sensors/accelerometer.py
DefaultUser/morse
train
2
2361b9a96d30fbe16752a84561bf8799304d433a
[ "self.vocab, self.ids_to_tokens = load_vocab(vocab_file)\nnever_split = ('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]')\nself.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split)\nself.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)", "split_tokens = []\nfor token in se...
<|body_start_0|> self.vocab, self.ids_to_tokens = load_vocab(vocab_file) never_split = ('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]') self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab...
BERT用の文章の単語分割クラスを実装
BertTokenizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertTokenizer: """BERT用の文章の単語分割クラスを実装""" def __init__(self, vocab_file, do_lower_case=True): """vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか""" <|body_0|> def tokenize(self, text): """文章を単語に分割する関数""" <|body_1|> def convert_tokens_to_ids(sel...
stack_v2_sparse_classes_75kplus_train_068605
30,882
permissive
[ { "docstring": "vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか", "name": "__init__", "signature": "def __init__(self, vocab_file, do_lower_case=True)" }, { "docstring": "文章を単語に分割する関数", "name": "tokenize", "signature": "def tokenize(self, text)" }, { "docstring": "分割された単語リ...
4
stack_v2_sparse_classes_30k_train_005346
Implement the Python class `BertTokenizer` described below. Class description: BERT用の文章の単語分割クラスを実装 Method signatures and docstrings: - def __init__(self, vocab_file, do_lower_case=True): vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか - def tokenize(self, text): 文章を単語に分割する関数 - def convert_tokens_to_ids(self, t...
Implement the Python class `BertTokenizer` described below. Class description: BERT用の文章の単語分割クラスを実装 Method signatures and docstrings: - def __init__(self, vocab_file, do_lower_case=True): vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか - def tokenize(self, text): 文章を単語に分割する関数 - def convert_tokens_to_ids(self, t...
bada8e07bd7503ed6d7a371fafb7a29b52b06d62
<|skeleton|> class BertTokenizer: """BERT用の文章の単語分割クラスを実装""" def __init__(self, vocab_file, do_lower_case=True): """vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか""" <|body_0|> def tokenize(self, text): """文章を単語に分割する関数""" <|body_1|> def convert_tokens_to_ids(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BertTokenizer: """BERT用の文章の単語分割クラスを実装""" def __init__(self, vocab_file, do_lower_case=True): """vocab_file:ボキャブラリーへのパス do_lower_case:前処理で単語を小文字化するかどうか""" self.vocab, self.ids_to_tokens = load_vocab(vocab_file) never_split = ('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]') se...
the_stack_v2_python_sparse
8_nlp_sentiment_bert/utils/bert.py
YutaroOgawa/pytorch_advanced
train
811
fc9f3a6515efcebec041e506c4fdfe03abe0be86
[ "super().__init__()\nself._client = docker.from_env()\nself._image_name = os.getenv('TESSIA_EXECUTOR_IMAGE')\nif not self._image_name:\n raise RuntimeError('Executor image not defined in environment variable TESSIA_EXECUTOR_IMAGE')\nself._compose_name = os.getenv('TESSIA_COMPOSE_NAME')\nif not self._image_name:\...
<|body_start_0|> super().__init__() self._client = docker.from_env() self._image_name = os.getenv('TESSIA_EXECUTOR_IMAGE') if not self._image_name: raise RuntimeError('Executor image not defined in environment variable TESSIA_EXECUTOR_IMAGE') self._compose_name = os.g...
Starts an executor by spawning a new container
ContainerSpawner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContainerSpawner: """Starts an executor by spawning a new container""" def __init__(self): """Constructor, creates logger instance and initialize connection to docker daemon.""" <|body_0|> def spawn(self, job_args, environment=None): """Starts a job executing con...
stack_v2_sparse_classes_75kplus_train_068606
17,167
permissive
[ { "docstring": "Constructor, creates logger instance and initialize connection to docker daemon.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Starts a job executing container in a specified environment Args: job_args (dict): job arguments environment (dict): environ...
4
null
Implement the Python class `ContainerSpawner` described below. Class description: Starts an executor by spawning a new container Method signatures and docstrings: - def __init__(self): Constructor, creates logger instance and initialize connection to docker daemon. - def spawn(self, job_args, environment=None): Start...
Implement the Python class `ContainerSpawner` described below. Class description: Starts an executor by spawning a new container Method signatures and docstrings: - def __init__(self): Constructor, creates logger instance and initialize connection to docker daemon. - def spawn(self, job_args, environment=None): Start...
9c9040f6a173af5c495f5447889e9349fa56f234
<|skeleton|> class ContainerSpawner: """Starts an executor by spawning a new container""" def __init__(self): """Constructor, creates logger instance and initialize connection to docker daemon.""" <|body_0|> def spawn(self, job_args, environment=None): """Starts a job executing con...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ContainerSpawner: """Starts an executor by spawning a new container""" def __init__(self): """Constructor, creates logger instance and initialize connection to docker daemon.""" super().__init__() self._client = docker.from_env() self._image_name = os.getenv('TESSIA_EXECUT...
the_stack_v2_python_sparse
tessia/server/scheduler/spawner.py
tessia-project/tessia
train
10
9c084d45991e103e762463e289f6b70cc90bb0ba
[ "if not head:\n return head\nslow, fast = (head, head)\nmeet = False\nwhile fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n if slow == fast:\n meet = True\n break\nif not meet:\n return None\nelse:\n curr = head\n while curr != slow:\n curr = curr...
<|body_start_0|> if not head: return head slow, fast = (head, head) meet = False while fast.next and fast.next.next: fast = fast.next.next slow = slow.next if slow == fast: meet = True break if not me...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def detectCycle_2(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return hea...
stack_v2_sparse_classes_75kplus_train_068607
1,810
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "detectCycle", "signature": "def detectCycle(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "detectCycle_2", "signature": "def detectCycle_2(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_015207
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def detectCycle_2(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def detectCycle_2(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: def d...
f2c4f727689567e00ee06560132fca55a6fd9286
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def detectCycle_2(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" if not head: return head slow, fast = (head, head) meet = False while fast.next and fast.next.next: fast = fast.next.next slow = slow.next ...
the_stack_v2_python_sparse
leetcode/142_Linked_List_Cycle II.py
JianxiangWang/python-journey
train
1
8554f0ed18dc9542f069b21fa01bc4ac1d25de26
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('pt0713_silnuext', 'pt0713_silnuext')\nclient = sodapy.Socrata('data.mass.gov', None)\nresponse = client.get('x99p-b88k', limit=9787, offset=0)\ns = json.dumps(response, sort_keys=True, indent=2)\nrepo.dr...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('pt0713_silnuext', 'pt0713_silnuext') client = sodapy.Socrata('data.mass.gov', None) response = client.get('x99p-b88k', limit=9787, offset=0) ...
fld
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class fld: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening...
stack_v2_sparse_classes_75kplus_train_068608
3,332
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
stack_v2_sparse_classes_30k_val_002439
Implement the Python class `fld` described below. Class description: Implement the fld class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create...
Implement the Python class `fld` described below. Class description: Implement the fld class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create...
41051ded77dfaeff98f02dcb7d3cfe7c9a0e5149
<|skeleton|> class fld: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything happening...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class fld: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('pt0713_silnuext', 'pt0713_silnuext') cl...
the_stack_v2_python_sparse
CS591DataMechanics/BostonCrimeAndHousingPriceAnalyzation/proj1/fld.py
sylvia0801/Undergrad-Projects
train
1
58b259c6faac4c66dd66b24101818afb6b4108a9
[ "serv_obj = self.pool.get('fleet.service.type')\ndomain = category and [('category', '=', category)] or []\nvalues = {}\nser_name = serv_obj.search(cr, uid, domain)\nfor serv in serv_obj.browse(cr, uid, ser_name):\n values.update({serv.name: serv.name})\nif values:\n return {'domain': {'service_type': [('name...
<|body_start_0|> serv_obj = self.pool.get('fleet.service.type') domain = category and [('category', '=', category)] or [] values = {} ser_name = serv_obj.search(cr, uid, domain) for serv in serv_obj.browse(cr, uid, ser_name): values.update({serv.name: serv.name}) ...
To manage services reports
service_wiz
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class service_wiz: """To manage services reports""" def onchange_cato(self, cr, uid, ids, category): """Get domain for service types according to category. @return: list of months""" <|body_0|> def print_report(self, cr, uid, ids, context=None): """Print report. @retur...
stack_v2_sparse_classes_75kplus_train_068609
2,746
no_license
[ { "docstring": "Get domain for service types according to category. @return: list of months", "name": "onchange_cato", "signature": "def onchange_cato(self, cr, uid, ids, category)" }, { "docstring": "Print report. @return: Dictionary of print attributes", "name": "print_report", "signat...
2
null
Implement the Python class `service_wiz` described below. Class description: To manage services reports Method signatures and docstrings: - def onchange_cato(self, cr, uid, ids, category): Get domain for service types according to category. @return: list of months - def print_report(self, cr, uid, ids, context=None):...
Implement the Python class `service_wiz` described below. Class description: To manage services reports Method signatures and docstrings: - def onchange_cato(self, cr, uid, ids, category): Get domain for service types according to category. @return: list of months - def print_report(self, cr, uid, ids, context=None):...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class service_wiz: """To manage services reports""" def onchange_cato(self, cr, uid, ids, category): """Get domain for service types according to category. @return: list of months""" <|body_0|> def print_report(self, cr, uid, ids, context=None): """Print report. @retur...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class service_wiz: """To manage services reports""" def onchange_cato(self, cr, uid, ids, category): """Get domain for service types according to category. @return: list of months""" serv_obj = self.pool.get('fleet.service.type') domain = category and [('category', '=', category)] or []...
the_stack_v2_python_sparse
v_7/Dongola/admin_affairs/service/wizard/service_wizard.py
musabahmed/baba
train
0
da354d43425298a978f3537801bdd2756246e767
[ "user = create_user()\nsurvey = create_survey()\nsurvey.form_fields.create(key='field-1', label='First Form Field', field_type=RADIO_FIELD, choices='1,2,3,4,5')\npublish(survey, user)\nsubmission = {'field-1': '3'}\nself.client.force_authenticate(user=user)\nresponse = self.client.post(reverse('api:surveys-submissi...
<|body_start_0|> user = create_user() survey = create_survey() survey.form_fields.create(key='field-1', label='First Form Field', field_type=RADIO_FIELD, choices='1,2,3,4,5') publish(survey, user) submission = {'field-1': '3'} self.client.force_authenticate(user=user) ...
CoachSurveyAPITest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoachSurveyAPITest: def test_basic_submit(self): """Test that a submission can be received""" <|body_0|> def test_current_after_registration_days_none_available(self): """Test that a survey is kept from the user before the specified number of days after registration ...
stack_v2_sparse_classes_75kplus_train_068610
19,399
no_license
[ { "docstring": "Test that a submission can be received", "name": "test_basic_submit", "signature": "def test_basic_submit(self)" }, { "docstring": "Test that a survey is kept from the user before the specified number of days after registration has passed.", "name": "test_current_after_regist...
6
stack_v2_sparse_classes_30k_train_021437
Implement the Python class `CoachSurveyAPITest` described below. Class description: Implement the CoachSurveyAPITest class. Method signatures and docstrings: - def test_basic_submit(self): Test that a submission can be received - def test_current_after_registration_days_none_available(self): Test that a survey is kep...
Implement the Python class `CoachSurveyAPITest` described below. Class description: Implement the CoachSurveyAPITest class. Method signatures and docstrings: - def test_basic_submit(self): Test that a submission can be received - def test_current_after_registration_days_none_available(self): Test that a survey is kep...
f1af2d84cff2c5ba242e6330256344c02deea726
<|skeleton|> class CoachSurveyAPITest: def test_basic_submit(self): """Test that a submission can be received""" <|body_0|> def test_current_after_registration_days_none_available(self): """Test that a survey is kept from the user before the specified number of days after registration ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CoachSurveyAPITest: def test_basic_submit(self): """Test that a submission can be received""" user = create_user() survey = create_survey() survey.form_fields.create(key='field-1', label='First Form Field', field_type=RADIO_FIELD, choices='1,2,3,4,5') publish(survey, us...
the_stack_v2_python_sparse
survey/tests.py
praekeltfoundation/gem-bbb-indo-server
train
0
05564c351a89e02d8ca61a17578df2a66017d861
[ "assert isinstance(encoder, ITransfrom), 'Invalid property encoder %s' % encoder\nassert isinstance(elements, list), 'Invalid elements %s' % elements\nassert isinstance(isModel, bool), 'Invalid is model flag %s' % isModel\nself.encoder = encoder\nself.elements = elements\nself.isModel = isModel", "assert isinstan...
<|body_start_0|> assert isinstance(encoder, ITransfrom), 'Invalid property encoder %s' % encoder assert isinstance(elements, list), 'Invalid elements %s' % elements assert isinstance(isModel, bool), 'Invalid is model flag %s' % isModel self.encoder = encoder self.elements = eleme...
Implementation for a @see: ITransfrom that updates the path before encoding .
EncoderPathUpdater
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderPathUpdater: """Implementation for a @see: ITransfrom that updates the path before encoding .""" def __init__(self, encoder, elements, isModel): """Construct the path updater.""" <|body_0|> def transform(self, value, target, support): """@see: ITransfrom.t...
stack_v2_sparse_classes_75kplus_train_068611
5,809
no_license
[ { "docstring": "Construct the path updater.", "name": "__init__", "signature": "def __init__(self, encoder, elements, isModel)" }, { "docstring": "@see: ITransfrom.transform", "name": "transform", "signature": "def transform(self, value, target, support)" } ]
2
stack_v2_sparse_classes_30k_train_034108
Implement the Python class `EncoderPathUpdater` described below. Class description: Implementation for a @see: ITransfrom that updates the path before encoding . Method signatures and docstrings: - def __init__(self, encoder, elements, isModel): Construct the path updater. - def transform(self, value, target, support...
Implement the Python class `EncoderPathUpdater` described below. Class description: Implementation for a @see: ITransfrom that updates the path before encoding . Method signatures and docstrings: - def __init__(self, encoder, elements, isModel): Construct the path updater. - def transform(self, value, target, support...
e0b3466b34d31548996d57be4a9dac134d904380
<|skeleton|> class EncoderPathUpdater: """Implementation for a @see: ITransfrom that updates the path before encoding .""" def __init__(self, encoder, elements, isModel): """Construct the path updater.""" <|body_0|> def transform(self, value, target, support): """@see: ITransfrom.t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EncoderPathUpdater: """Implementation for a @see: ITransfrom that updates the path before encoding .""" def __init__(self, encoder, elements, isModel): """Construct the path updater.""" assert isinstance(encoder, ITransfrom), 'Invalid property encoder %s' % encoder assert isinstan...
the_stack_v2_python_sparse
components/ally-core-http/ally/core/http/impl/processor/encoder/path_support.py
cristidomsa/Ally-Py
train
0
90ea601806ef2632c534d1d4a5df84a6c3c78308
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsInformationProtectionAppLearningSummary()", "from .application_type import ApplicationType\nfrom .entity import Entity\nfrom .application_type import ApplicationType\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any],...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return WindowsInformationProtectionAppLearningSummary() <|end_body_0|> <|body_start_1|> from .application_type import ApplicationType from .entity import Entity from .application_type i...
Windows Information Protection AppLearning Summary entity.
WindowsInformationProtectionAppLearningSummary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowsInformationProtectionAppLearningSummary: """Windows Information Protection AppLearning Summary entity.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionAppLearningSummary: """Creates a new instance of the appropriate c...
stack_v2_sparse_classes_75kplus_train_068612
2,829
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: WindowsInformationProtectionAppLearningSummary", "name": "create_from_discriminator_value", "signature": "de...
3
null
Implement the Python class `WindowsInformationProtectionAppLearningSummary` described below. Class description: Windows Information Protection AppLearning Summary entity. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionAppLea...
Implement the Python class `WindowsInformationProtectionAppLearningSummary` described below. Class description: Windows Information Protection AppLearning Summary entity. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionAppLea...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class WindowsInformationProtectionAppLearningSummary: """Windows Information Protection AppLearning Summary entity.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionAppLearningSummary: """Creates a new instance of the appropriate c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WindowsInformationProtectionAppLearningSummary: """Windows Information Protection AppLearning Summary entity.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionAppLearningSummary: """Creates a new instance of the appropriate class based on...
the_stack_v2_python_sparse
msgraph/generated/models/windows_information_protection_app_learning_summary.py
microsoftgraph/msgraph-sdk-python
train
135
9838acaf9191e34cd5814edc3f9e10548000e3e1
[ "import operator\nlookups = []\nfor frequency, name in FREQUENCY_CHOICES:\n time = datetime.now() - timedelta(seconds=frequency)\n lookups.append(models.Q(frequency=frequency, last_sent_time__lte=time))\nreturn self.filter(reduce(operator.or_, lookups))", "feed_cache = {}\nfor subscription in self.due():\n ...
<|body_start_0|> import operator lookups = [] for frequency, name in FREQUENCY_CHOICES: time = datetime.now() - timedelta(seconds=frequency) lookups.append(models.Q(frequency=frequency, last_sent_time__lte=time)) return self.filter(reduce(operator.or_, lookups)) <...
SubscriptionManager
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubscriptionManager: def due(self): """Returns a queryset of all ``Subcription`` objects that are due to be sent.""" <|body_0|> def send_due(self, fail_silently=True): """Sends an alerts to each user who has a due ``Subscription`` if there are new items for their sub...
stack_v2_sparse_classes_75kplus_train_068613
6,918
permissive
[ { "docstring": "Returns a queryset of all ``Subcription`` objects that are due to be sent.", "name": "due", "signature": "def due(self)" }, { "docstring": "Sends an alerts to each user who has a due ``Subscription`` if there are new items for their subscription. *NOTE*: This can potentially take...
2
stack_v2_sparse_classes_30k_train_004700
Implement the Python class `SubscriptionManager` described below. Class description: Implement the SubscriptionManager class. Method signatures and docstrings: - def due(self): Returns a queryset of all ``Subcription`` objects that are due to be sent. - def send_due(self, fail_silently=True): Sends an alerts to each ...
Implement the Python class `SubscriptionManager` described below. Class description: Implement the SubscriptionManager class. Method signatures and docstrings: - def due(self): Returns a queryset of all ``Subcription`` objects that are due to be sent. - def send_due(self, fail_silently=True): Sends an alerts to each ...
d07094f9d6b2528d282ed99af0063002480bc00b
<|skeleton|> class SubscriptionManager: def due(self): """Returns a queryset of all ``Subcription`` objects that are due to be sent.""" <|body_0|> def send_due(self, fail_silently=True): """Sends an alerts to each user who has a due ``Subscription`` if there are new items for their sub...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SubscriptionManager: def due(self): """Returns a queryset of all ``Subcription`` objects that are due to be sent.""" import operator lookups = [] for frequency, name in FREQUENCY_CHOICES: time = datetime.now() - timedelta(seconds=frequency) lookups.appen...
the_stack_v2_python_sparse
populous/alerts/models.py
caiges/populous
train
2
ff23ce6e378b65dcf0a3864393dc22f86a7da7e0
[ "if request.user.username == 'Admin':\n question = request.data['question']\n answer = request.data['answer']\n order = FAQ.objects.all().order_by('-order').first().order\n FAQ.objects.create(question=question, answer=answer, view=0, order=order + 1)\n return Response(data={'FAQ 추가 완료!'}, status=stat...
<|body_start_0|> if request.user.username == 'Admin': question = request.data['question'] answer = request.data['answer'] order = FAQ.objects.all().order_by('-order').first().order FAQ.objects.create(question=question, answer=answer, view=0, order=order + 1) ...
FAQManagementViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FAQManagementViewSet: def add_faq(self, request): """FAQ 추가 [admin token required]""" <|body_0|> def delete_faq(self, request): """FAQ 삭제 [admin token required] : 특정 FAQ 삭제""" <|body_1|> def update_faq(self, request): """FAQ 질문 or 답변 업데이트 [admin ...
stack_v2_sparse_classes_75kplus_train_068614
35,811
no_license
[ { "docstring": "FAQ 추가 [admin token required]", "name": "add_faq", "signature": "def add_faq(self, request)" }, { "docstring": "FAQ 삭제 [admin token required] : 특정 FAQ 삭제", "name": "delete_faq", "signature": "def delete_faq(self, request)" }, { "docstring": "FAQ 질문 or 답변 업데이트 [adm...
4
stack_v2_sparse_classes_30k_train_024004
Implement the Python class `FAQManagementViewSet` described below. Class description: Implement the FAQManagementViewSet class. Method signatures and docstrings: - def add_faq(self, request): FAQ 추가 [admin token required] - def delete_faq(self, request): FAQ 삭제 [admin token required] : 특정 FAQ 삭제 - def update_faq(self...
Implement the Python class `FAQManagementViewSet` described below. Class description: Implement the FAQManagementViewSet class. Method signatures and docstrings: - def add_faq(self, request): FAQ 추가 [admin token required] - def delete_faq(self, request): FAQ 삭제 [admin token required] : 특정 FAQ 삭제 - def update_faq(self...
bcc955bddd9941f2bc54f7577c26c1ddc6b36a48
<|skeleton|> class FAQManagementViewSet: def add_faq(self, request): """FAQ 추가 [admin token required]""" <|body_0|> def delete_faq(self, request): """FAQ 삭제 [admin token required] : 특정 FAQ 삭제""" <|body_1|> def update_faq(self, request): """FAQ 질문 or 답변 업데이트 [admin ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FAQManagementViewSet: def add_faq(self, request): """FAQ 추가 [admin token required]""" if request.user.username == 'Admin': question = request.data['question'] answer = request.data['answer'] order = FAQ.objects.all().order_by('-order').first().order ...
the_stack_v2_python_sparse
admin_page/views.py
bgy1060/Daily_Project
train
1
f61b5f4d60bdc36754b30f7c4c836fe2e0398117
[ "result_particles = []\nnd_timestamp, non_data, non_start, non_end = self._chunker.get_next_non_data_with_index(clean=False)\ntimestamp, chunk, start, end = self._chunker.get_next_data_with_index()\nself.handle_non_data(non_data, non_end, start)\nwhile chunk is not None:\n header_match = SIO_HEADER_MATCHER.match...
<|body_start_0|> result_particles = [] nd_timestamp, non_data, non_start, non_end = self._chunker.get_next_non_data_with_index(clean=False) timestamp, chunk, start, end = self._chunker.get_next_data_with_index() self.handle_non_data(non_data, non_end, start) while chunk is not No...
FlortDjSioParser
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlortDjSioParser: def parse_chunks(self): """Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples with sample particles encountered in this...
stack_v2_sparse_classes_75kplus_train_068615
9,506
permissive
[ { "docstring": "Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples with sample particles encountered in this parsing, plus the state. An empty list of nothing wa...
2
stack_v2_sparse_classes_30k_train_030128
Implement the Python class `FlortDjSioParser` described below. Class description: Implement the FlortDjSioParser class. Method signatures and docstrings: - def parse_chunks(self): Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go unt...
Implement the Python class `FlortDjSioParser` described below. Class description: Implement the FlortDjSioParser class. Method signatures and docstrings: - def parse_chunks(self): Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go unt...
bdbf01f5614e7188ce19596704794466e5683b30
<|skeleton|> class FlortDjSioParser: def parse_chunks(self): """Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples with sample particles encountered in this...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FlortDjSioParser: def parse_chunks(self): """Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples with sample particles encountered in this parsing, plus...
the_stack_v2_python_sparse
mi/dataset/parser/flort_dj_sio.py
oceanobservatories/mi-instrument
train
1
0caff98b6af102045370af991e6c95337cbdd080
[ "rospy.loginfo('Initializing NotePublisher')\nself.publisher = rospy.Publisher('baxter_artist_notes', baxter_artist.msg.Note, queue_size=QUEUE_SIZE)\nrospy.loginfo('Sleeping...')\nrospy.sleep(5)", "msg = baxter_artist.msg.Note()\nmsg.starttime = starttime\nmsg.pitch = pitch\nrospy.loginfo('publish - pitch: ' + st...
<|body_start_0|> rospy.loginfo('Initializing NotePublisher') self.publisher = rospy.Publisher('baxter_artist_notes', baxter_artist.msg.Note, queue_size=QUEUE_SIZE) rospy.loginfo('Sleeping...') rospy.sleep(5) <|end_body_0|> <|body_start_1|> msg = baxter_artist.msg.Note() ...
Publish notes to the baxter_artist_notes rostopic
NotePublisher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotePublisher: """Publish notes to the baxter_artist_notes rostopic""" def __init__(self): """Initialize a NotePublisher""" <|body_0|> def pub_note(self, pitch, starttime): """Publish a note to the rostopic Args: pitch (int): the pitch of the note to play startti...
stack_v2_sparse_classes_75kplus_train_068616
1,900
permissive
[ { "docstring": "Initialize a NotePublisher", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Publish a note to the rostopic Args: pitch (int): the pitch of the note to play starttime (rospy.Time): when the note should be played.", "name": "pub_note", "signature":...
3
null
Implement the Python class `NotePublisher` described below. Class description: Publish notes to the baxter_artist_notes rostopic Method signatures and docstrings: - def __init__(self): Initialize a NotePublisher - def pub_note(self, pitch, starttime): Publish a note to the rostopic Args: pitch (int): the pitch of the...
Implement the Python class `NotePublisher` described below. Class description: Publish notes to the baxter_artist_notes rostopic Method signatures and docstrings: - def __init__(self): Initialize a NotePublisher - def pub_note(self, pitch, starttime): Publish a note to the rostopic Args: pitch (int): the pitch of the...
a4c95faefc964c147807dffccf55e7d7a5c58bb0
<|skeleton|> class NotePublisher: """Publish notes to the baxter_artist_notes rostopic""" def __init__(self): """Initialize a NotePublisher""" <|body_0|> def pub_note(self, pitch, starttime): """Publish a note to the rostopic Args: pitch (int): the pitch of the note to play startti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NotePublisher: """Publish notes to the baxter_artist_notes rostopic""" def __init__(self): """Initialize a NotePublisher""" rospy.loginfo('Initializing NotePublisher') self.publisher = rospy.Publisher('baxter_artist_notes', baxter_artist.msg.Note, queue_size=QUEUE_SIZE) ro...
the_stack_v2_python_sparse
src/artist_performer/publisher.py
jasonsbrooks/ARTIST
train
0
d82dbe7c7573089296df82cb748bea89cc42ef6a
[ "author = request.GET.get('author')\nif 'sub' in request.GET:\n get_object_or_404(Subscription.objects.select_related('author'), user=request.user, author__username=author).delete()\nelse:\n self.post(request, author)\nreturn redirect('author_url', username=author)", "author = get_author(request, author)\nu...
<|body_start_0|> author = request.GET.get('author') if 'sub' in request.GET: get_object_or_404(Subscription.objects.select_related('author'), user=request.user, author__username=author).delete() else: self.post(request, author) return redirect('author_url', userna...
Subscriptions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subscriptions: def get(self, request): """Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылить, чтобы не повторяться.""" <|body_0|> def post(self, request, author=None): """С...
stack_v2_sparse_classes_75kplus_train_068617
7,041
no_license
[ { "docstring": "Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылить, чтобы не повторяться.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Создание подписки на автора если ее е...
3
stack_v2_sparse_classes_30k_train_019480
Implement the Python class `Subscriptions` described below. Class description: Implement the Subscriptions class. Method signatures and docstrings: - def get(self, request): Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылит...
Implement the Python class `Subscriptions` described below. Class description: Implement the Subscriptions class. Method signatures and docstrings: - def get(self, request): Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылит...
dba6f5daf5b046a900f6e8c4b295b919aa03ed43
<|skeleton|> class Subscriptions: def get(self, request): """Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылить, чтобы не повторяться.""" <|body_0|> def post(self, request, author=None): """С...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Subscriptions: def get(self, request): """Так как специалисты по фронтенду сделали на разных страницах обсолютно по разному обработку одного и тогоже действия пришлось немного закостылить, чтобы не повторяться.""" author = request.GET.get('author') if 'sub' in request.GET: ...
the_stack_v2_python_sparse
recipes/views.py
zYoma/foodgram-project
train
0
e6c1db56f8a2e134896c17f833fc5d42da49ab27
[ "super().__init__()\nself.modes_to_measure = _np.arange(1, self.HARM_NUM // 2 + 1)\nself.drive_num = 0\nself.wait_acquisition = 1\nself.wait_pv_update = 0\nself.fitting_clearance_ini = 0\nself.fitting_clearance_fin = 100\nself.fitting_consider_offset = True", "dtmp = '{0:24s} = {1:9d}\\n'.format\nftmp = '{0:24s} ...
<|body_start_0|> super().__init__() self.modes_to_measure = _np.arange(1, self.HARM_NUM // 2 + 1) self.drive_num = 0 self.wait_acquisition = 1 self.wait_pv_update = 0 self.fitting_clearance_ini = 0 self.fitting_clearance_fin = 100 self.fitting_consider_off...
.
DriveDampLParams
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DriveDampLParams: """.""" def __init__(self): """.""" <|body_0|> def __str__(self): """.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__() self.modes_to_measure = _np.arange(1, self.HARM_NUM // 2 + 1) self.drive_...
stack_v2_sparse_classes_75kplus_train_068618
45,488
permissive
[ { "docstring": ".", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ".", "name": "__str__", "signature": "def __str__(self)" } ]
2
stack_v2_sparse_classes_30k_train_024762
Implement the Python class `DriveDampLParams` described below. Class description: . Method signatures and docstrings: - def __init__(self): . - def __str__(self): .
Implement the Python class `DriveDampLParams` described below. Class description: . Method signatures and docstrings: - def __init__(self): . - def __str__(self): . <|skeleton|> class DriveDampLParams: """.""" def __init__(self): """.""" <|body_0|> def __str__(self): """.""" ...
39644161d98964a3a3d80d63269201f0a1712e82
<|skeleton|> class DriveDampLParams: """.""" def __init__(self): """.""" <|body_0|> def __str__(self): """.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DriveDampLParams: """.""" def __init__(self): """.""" super().__init__() self.modes_to_measure = _np.arange(1, self.HARM_NUM // 2 + 1) self.drive_num = 0 self.wait_acquisition = 1 self.wait_pv_update = 0 self.fitting_clearance_ini = 0 self.f...
the_stack_v2_python_sparse
apsuite/commisslib/measure_bbb_data.py
lnls-fac/apsuite
train
1
9df01b0390c3487feac2b607c62fb261a667e75f
[ "if self.auth_type == 'open':\n self.logger.info('{0}/names.nsf does not require authentication'.format(self.url))\nelse:\n usernames = self.build_userlist(userlist)\n valid_accounts = self.brute_accounts(usernames)\n print('\\n')\n if valid_accounts:\n self.logger.info('Found {0} valid {1}'.f...
<|body_start_0|> if self.auth_type == 'open': self.logger.info('{0}/names.nsf does not require authentication'.format(self.url)) else: usernames = self.build_userlist(userlist) valid_accounts = self.brute_accounts(usernames) print('\n') if vali...
BruteForce
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BruteForce: def bruteforce(self, userlist): """Perform a reverse brute force attack with multiple usernames and one password.""" <|body_0|> def build_userlist(self, userlist): """Build a list of usernames from the user supplied wordlist.""" <|body_1|> de...
stack_v2_sparse_classes_75kplus_train_068619
3,450
permissive
[ { "docstring": "Perform a reverse brute force attack with multiple usernames and one password.", "name": "bruteforce", "signature": "def bruteforce(self, userlist)" }, { "docstring": "Build a list of usernames from the user supplied wordlist.", "name": "build_userlist", "signature": "def...
3
stack_v2_sparse_classes_30k_train_006975
Implement the Python class `BruteForce` described below. Class description: Implement the BruteForce class. Method signatures and docstrings: - def bruteforce(self, userlist): Perform a reverse brute force attack with multiple usernames and one password. - def build_userlist(self, userlist): Build a list of usernames...
Implement the Python class `BruteForce` described below. Class description: Implement the BruteForce class. Method signatures and docstrings: - def bruteforce(self, userlist): Perform a reverse brute force attack with multiple usernames and one password. - def build_userlist(self, userlist): Build a list of usernames...
da7831cf4cd1578dce4c10707afe4172622b90c9
<|skeleton|> class BruteForce: def bruteforce(self, userlist): """Perform a reverse brute force attack with multiple usernames and one password.""" <|body_0|> def build_userlist(self, userlist): """Build a list of usernames from the user supplied wordlist.""" <|body_1|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BruteForce: def bruteforce(self, userlist): """Perform a reverse brute force attack with multiple usernames and one password.""" if self.auth_type == 'open': self.logger.info('{0}/names.nsf does not require authentication'.format(self.url)) else: usernames = sel...
the_stack_v2_python_sparse
domi_owned/bruteforce.py
JnTournier/domi-owned
train
1
1a46db908b47d7c6395d88b40c228d52ec521b2d
[ "kw = super(ProjectEventView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw", "context = super(ProjectEventView, self).get_context_data(**kwargs)\nproject = get_object_or_404(Project, id=self.kwargs['pk'])\nevents = project.event_set.all()\nreporting_ct = project....
<|body_start_0|> kw = super(ProjectEventView, self).get_form_kwargs() kw.update({'organization': self.request.user.organization}) return kw <|end_body_0|> <|body_start_1|> context = super(ProjectEventView, self).get_context_data(**kwargs) project = get_object_or_404(Project, id=...
Display all the events associated with a project.
ProjectEventView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" <|body_0|> def get_context_data(self, **kwargs): """Return events belonging to the project.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_75kplus_train_068620
12,378
permissive
[ { "docstring": "Pass organization to form.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }, { "docstring": "Return events belonging to the project.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_val_002906
Implement the Python class `ProjectEventView` described below. Class description: Display all the events associated with a project. Method signatures and docstrings: - def get_form_kwargs(self): Pass organization to form. - def get_context_data(self, **kwargs): Return events belonging to the project.
Implement the Python class `ProjectEventView` described below. Class description: Display all the events associated with a project. Method signatures and docstrings: - def get_form_kwargs(self): Pass organization to form. - def get_context_data(self, **kwargs): Return events belonging to the project. <|skeleton|> cl...
dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9
<|skeleton|> class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" <|body_0|> def get_context_data(self, **kwargs): """Return events belonging to the project.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" kw = super(ProjectEventView, self).get_form_kwargs() kw.update({'organization': self.request.user.organization}) return kw def get_con...
the_stack_v2_python_sparse
project/editorial/views/events.py
ProjectFacet/facet
train
25
605363fec6f05317d023c7680a9dd2642346ce63
[ "try:\n cluster_info = settings.GANETI_CLUSTER_INFO\nexcept (AttributeError, ImportError):\n return\nip, port, username, password = cluster_info\nbackend = orm.Backend.objects.create(clustername=ip, port=port, username=username, password=password)\nfor vm in orm.VirtualMachine.objects.all():\n vm.backend =...
<|body_start_0|> try: cluster_info = settings.GANETI_CLUSTER_INFO except (AttributeError, ImportError): return ip, port, username, password = cluster_info backend = orm.Backend.objects.create(clustername=ip, port=port, username=username, password=password) ...
Migration
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Migration: def forwards(self, orm): """Write your forwards methods here.""" <|body_0|> def backwards(self, orm): """Write your backwards methods here.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: cluster_info = settings.GANETI_CL...
stack_v2_sparse_classes_75kplus_train_068621
9,034
permissive
[ { "docstring": "Write your forwards methods here.", "name": "forwards", "signature": "def forwards(self, orm)" }, { "docstring": "Write your backwards methods here.", "name": "backwards", "signature": "def backwards(self, orm)" } ]
2
stack_v2_sparse_classes_30k_train_019826
Implement the Python class `Migration` described below. Class description: Implement the Migration class. Method signatures and docstrings: - def forwards(self, orm): Write your forwards methods here. - def backwards(self, orm): Write your backwards methods here.
Implement the Python class `Migration` described below. Class description: Implement the Migration class. Method signatures and docstrings: - def forwards(self, orm): Write your forwards methods here. - def backwards(self, orm): Write your backwards methods here. <|skeleton|> class Migration: def forwards(self,...
11e79c1c2add88c1e3dbe51e2915fb1bddd1bbf1
<|skeleton|> class Migration: def forwards(self, orm): """Write your forwards methods here.""" <|body_0|> def backwards(self, orm): """Write your backwards methods here.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Migration: def forwards(self, orm): """Write your forwards methods here.""" try: cluster_info = settings.GANETI_CLUSTER_INFO except (AttributeError, ImportError): return ip, port, username, password = cluster_info backend = orm.Backend.objects.cr...
the_stack_v2_python_sparse
snf-cyclades-app/synnefo/db/migrations/0035_default_backend.py
dimara/synnefo
train
0
170403e15747dc8bfaa2c7e663561e369b0ad954
[ "GalkinModel.__init__(self, kwargs_model, kwargs_cosmo, kwargs_numerics=kwargs_numerics, analytic_kinematics=analytic_kinematics)\nself._observation_list = []\nself._num_observations = len(kwargs_aperture_list)\nfor i in range(self._num_observations):\n self._observation_list.append(GalkinObservation(kwargs_aper...
<|body_start_0|> GalkinModel.__init__(self, kwargs_model, kwargs_cosmo, kwargs_numerics=kwargs_numerics, analytic_kinematics=analytic_kinematics) self._observation_list = [] self._num_observations = len(kwargs_aperture_list) for i in range(self._num_observations): self._obser...
class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in list of observational settings. Does not work with IFU observations (yet)
GalkinMultiObservation
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GalkinMultiObservation: """class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in list of observational settings. Does not w...
stack_v2_sparse_classes_75kplus_train_068622
3,833
permissive
[ { "docstring": ":param kwargs_model: keyword arguments describing the model components :param kwargs_aperture_list: list of keyword arguments describing the spectroscopic aperture, see Aperture() class :param kwargs_psf_list: list of keyword argument specifying the PSF of the observation :param kwargs_cosmo: ke...
2
null
Implement the Python class `GalkinMultiObservation` described below. Class description: class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in lis...
Implement the Python class `GalkinMultiObservation` described below. Class description: class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in lis...
73c9645f26f6983fe7961104075ebe8bf7a4b54c
<|skeleton|> class GalkinMultiObservation: """class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in list of observational settings. Does not w...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GalkinMultiObservation: """class to efficiently model the velocity dispersion measurement of a set of different observations with individual apertures and seeing conditions for a given lens The main difference to the Galkin main class is that it feeds in list of observational settings. Does not work with IFU ...
the_stack_v2_python_sparse
lenstronomy/GalKin/galkin_multiobservation.py
lenstronomy/lenstronomy
train
41
7c750af997f3f9f78313860ccdef6d58f44dc5b0
[ "self.c = capacity\nself.h = {}\nself.q = []", "rt = self.h.get(key)\nif rt:\n self.q.remove(key)\n self.q.append(key)\n return rt\nelse:\n return -1", "occupied = self.h.get(key)\nif occupied:\n self.h[key] = value\n self.q.remove(key)\n self.q.append(key)\nelse:\n if len(self.h.keys())...
<|body_start_0|> self.c = capacity self.h = {} self.q = [] <|end_body_0|> <|body_start_1|> rt = self.h.get(key) if rt: self.q.remove(key) self.q.append(key) return rt else: return -1 <|end_body_1|> <|body_start_2|> ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_75kplus_train_068623
1,404
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_041358
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
a755bd7ecc0a9642f4009eb0681a14b0c05d3bc4
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.c = capacity self.h = {} self.q = [] def get(self, key): """:rtype: int""" rt = self.h.get(key) if rt: self.q.remove(key) self.q.append(key) r...
the_stack_v2_python_sparse
python_projects/LRU_Cache.py
burgesschentz/AlgorithmProjects
train
0
92cdcabd82b1879c52261ba887362c1c4e63a9d2
[ "super(CustomBatchNormManualModule, self).__init__()\nself.n_neurons = n_neurons\nself.gamma = nn.Parameter(torch.ones(n_neurons))\nself.beta = nn.Parameter(torch.zeros(n_neurons))\nself.eps = eps", "if not input.shape[1] == self.n_neurons:\n raise Exception('Input size is not correct. Input is {}, while it wa...
<|body_start_0|> super(CustomBatchNormManualModule, self).__init__() self.n_neurons = n_neurons self.gamma = nn.Parameter(torch.ones(n_neurons)) self.beta = nn.Parameter(torch.zeros(n_neurons)) self.eps = eps <|end_body_0|> <|body_start_1|> if not input.shape[1] == self....
This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
CustomBatchNormManualModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backw...
stack_v2_sparse_classes_75kplus_train_068624
11,418
no_license
[ { "docstring": "Initializes CustomBatchNormManualModule object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability TODO: Save parameters for the number of neurons and eps. Initialize parameters gamma and beta via nn.Parameter", "name": "__init__"...
2
stack_v2_sparse_classes_30k_train_021624
Implement the Python class `CustomBatchNormManualModule` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backwa...
Implement the Python class `CustomBatchNormManualModule` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backwa...
c50b7d208baa441e8ee9e12c83b018320213af67
<|skeleton|> class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backw...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.""" ...
the_stack_v2_python_sparse
assignment_1/code/custom_batchnorm.py
YoniSchirris/dl
train
1
a35d7839dde88420998d37a6ba5430e50646e019
[ "try:\n print('收到修改个人信息请求')\n body = json.loads(self.request.body)\n self.sqlhandler = None\n self.teaUid = body['teaUid']\n self.teaPassword = body['teaPassword']\n self.teaName = body['teaName']\n self.teaSex = body['teaSex']\n self.teaAge = body['teaAge']\n self.teaPhoneNumber = body['...
<|body_start_0|> try: print('收到修改个人信息请求') body = json.loads(self.request.body) self.sqlhandler = None self.teaUid = body['teaUid'] self.teaPassword = body['teaPassword'] self.teaName = body['teaName'] self.teaSex = body['teaSex'...
TeaSetInfoRequestHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeaSetInfoRequestHandler: def post(self): """获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级""" <|body_0|> def SetTeaInfo(self): """给学生设置个人信息""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: print('收到修改个人信息请求') body = json.loads(self.req...
stack_v2_sparse_classes_75kplus_train_068625
2,411
no_license
[ { "docstring": "获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级", "name": "post", "signature": "def post(self)" }, { "docstring": "给学生设置个人信息", "name": "SetTeaInfo", "signature": "def SetTeaInfo(self)" } ]
2
stack_v2_sparse_classes_30k_val_002353
Implement the Python class `TeaSetInfoRequestHandler` described below. Class description: Implement the TeaSetInfoRequestHandler class. Method signatures and docstrings: - def post(self): 获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级 - def SetTeaInfo(self): 给学生设置个人信息
Implement the Python class `TeaSetInfoRequestHandler` described below. Class description: Implement the TeaSetInfoRequestHandler class. Method signatures and docstrings: - def post(self): 获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级 - def SetTeaInfo(self): 给学生设置个人信息 <|skeleton|> class TeaSetInfoRequestHandler: def post(self...
b28eb4163b02bd0a931653b94851592f2654b199
<|skeleton|> class TeaSetInfoRequestHandler: def post(self): """获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级""" <|body_0|> def SetTeaInfo(self): """给学生设置个人信息""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TeaSetInfoRequestHandler: def post(self): """获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级""" try: print('收到修改个人信息请求') body = json.loads(self.request.body) self.sqlhandler = None self.teaUid = body['teaUid'] self.teaPassword = body['teaPassword'] ...
the_stack_v2_python_sparse
server/teacher/TeaSetInfoRequestHandler.py
lyh-ADT/edu-app
train
1
02e17a753ee773477fcf2ba49621e108f262395a
[ "self.typology = 'Simple'\nself.trace = trace\nself.dip = dip\nself.upper_depth = upper_depth\nself.lower_depth = lower_depth\nself.surface = SimpleFaultSurface.from_fault_data(self.trace, self.upper_depth, self.lower_depth, self.dip, mesh_spacing)\nself.length = trace.get_length()\nself.downdip_width = None\nself....
<|body_start_0|> self.typology = 'Simple' self.trace = trace self.dip = dip self.upper_depth = upper_depth self.lower_depth = lower_depth self.surface = SimpleFaultSurface.from_fault_data(self.trace, self.upper_depth, self.lower_depth, self.dip, mesh_spacing) self...
Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic d...
SimpleFaultGeometry
[ "AGPL-3.0-only", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleFaultGeometry: """Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km...
stack_v2_sparse_classes_75kplus_train_068626
6,464
permissive
[ { "docstring": "Sets up the fault geometry parameters from the input fault definitions :param float mesh_spacing: Spacing (km) of the fault surface mesh", "name": "__init__", "signature": "def __init__(self, trace, dip, upper_depth, lower_depth, mesh_spacing=1.0)" }, { "docstring": "Calculates t...
2
stack_v2_sparse_classes_30k_train_041026
Implement the Python class `SimpleFaultGeometry` described below. Class description: Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float u...
Implement the Python class `SimpleFaultGeometry` described below. Class description: Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float u...
0da9ba5a575360081715e8b90c71d4b16c6687c8
<|skeleton|> class SimpleFaultGeometry: """Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleFaultGeometry: """Describes the geometrical propeties of a simple fault surface :param str typology: Source typology :param trace: Fault trace as instance of :class: openquake.hazardlib.geo.line.Line :param float dip: Fault dip (degrees) :param float upper_depth: Upper seismogenic depth (km) :param floa...
the_stack_v2_python_sparse
openquake/hmtk/faults/fault_geometries.py
GFZ-Centre-for-Early-Warning/shakyground
train
1
11a1aaaeb59ad8c7e7eab3a8ee1656e35a8ee11d
[ "form = forms.GomokuRecordForm()\nctx = {'form': form}\nreturn render(request, 'gomoku_app/gomoku_file_form.html', ctx)", "form = forms.GomokuRecordForm(request.POST, request.FILES)\nuser = get_user_model().objects.get(username=self.request.user)\nif form.is_valid():\n file = form.cleaned_data['file']\n mod...
<|body_start_0|> form = forms.GomokuRecordForm() ctx = {'form': form} return render(request, 'gomoku_app/gomoku_file_form.html', ctx) <|end_body_0|> <|body_start_1|> form = forms.GomokuRecordForm(request.POST, request.FILES) user = get_user_model().objects.get(username=self.requ...
View which will unpack data from gomoku record file, then signal will create proper record file object
ExtractDataRedirectView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtractDataRedirectView: """View which will unpack data from gomoku record file, then signal will create proper record file object""" def get(self, request): """GET method view""" <|body_0|> def post(self, request): """POST method view""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus_train_068627
3,452
no_license
[ { "docstring": "GET method view", "name": "get", "signature": "def get(self, request)" }, { "docstring": "POST method view", "name": "post", "signature": "def post(self, request)" } ]
2
null
Implement the Python class `ExtractDataRedirectView` described below. Class description: View which will unpack data from gomoku record file, then signal will create proper record file object Method signatures and docstrings: - def get(self, request): GET method view - def post(self, request): POST method view
Implement the Python class `ExtractDataRedirectView` described below. Class description: View which will unpack data from gomoku record file, then signal will create proper record file object Method signatures and docstrings: - def get(self, request): GET method view - def post(self, request): POST method view <|ske...
4ce3e6813e16ecaf0a118e0cc5548a091aa97646
<|skeleton|> class ExtractDataRedirectView: """View which will unpack data from gomoku record file, then signal will create proper record file object""" def get(self, request): """GET method view""" <|body_0|> def post(self, request): """POST method view""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExtractDataRedirectView: """View which will unpack data from gomoku record file, then signal will create proper record file object""" def get(self, request): """GET method view""" form = forms.GomokuRecordForm() ctx = {'form': form} return render(request, 'gomoku_app/gomok...
the_stack_v2_python_sparse
src/gomoku_app/views.py
adam-harmasz/gomoku_v_0_2
train
0
1b3154d139398a7f0080a0d763516aa09c3fb181
[ "if not (probe and typeMapper):\n raise Exception('Argument exception - request classifier must have valid probe and type mapper')\nself.probe = probe\nself.typeMapper = typeMapper", "counter = txn.getCounterForProbe(self.probe)\nif counter:\n data = counter.data\n if self.typeMapper:\n return sel...
<|body_start_0|> if not (probe and typeMapper): raise Exception('Argument exception - request classifier must have valid probe and type mapper') self.probe = probe self.typeMapper = typeMapper <|end_body_0|> <|body_start_1|> counter = txn.getCounterForProbe(self.probe) ...
Classifies transactions based on data in a given probe
ProbeDataClassifier
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProbeDataClassifier: """Classifies transactions based on data in a given probe""" def __init__(self, probe, typeMapper): """Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the transaction :type probe: xpedite.types.probe.Probe :param type...
stack_v2_sparse_classes_75kplus_train_068628
1,896
permissive
[ { "docstring": "Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the transaction :type probe: xpedite.types.probe.Probe :param typeMapper: a callback to map probe data to a category :type typeMapper: bool", "name": "__init__", "signature": "def __init__(self,...
2
stack_v2_sparse_classes_30k_train_034571
Implement the Python class `ProbeDataClassifier` described below. Class description: Classifies transactions based on data in a given probe Method signatures and docstrings: - def __init__(self, probe, typeMapper): Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the trans...
Implement the Python class `ProbeDataClassifier` described below. Class description: Classifies transactions based on data in a given probe Method signatures and docstrings: - def __init__(self, probe, typeMapper): Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the trans...
d6b67e98d4b640c98499a373425f1f009e5b9061
<|skeleton|> class ProbeDataClassifier: """Classifies transactions based on data in a given probe""" def __init__(self, probe, typeMapper): """Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the transaction :type probe: xpedite.types.probe.Probe :param type...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProbeDataClassifier: """Classifies transactions based on data in a given probe""" def __init__(self, probe, typeMapper): """Constructs an instance of ProbeDataClassifier :param probe: A probe that is expected to be in the transaction :type probe: xpedite.types.probe.Probe :param typeMapper: a cal...
the_stack_v2_python_sparse
scripts/lib/xpedite/txn/classifier.py
dendisuhubdy/Xpedite
train
1
e74ea41b014a04f6fd35ccbe5f273f546b02318c
[ "L = [[0 for i in range(n + 1)] for i in range(m + 1)]\nfor i in range(1, n + 1):\n L[1][i] = 1\nfor i in range(1, m + 1):\n L[i][1] = 1\nfor i in range(2, m + 1):\n for j in range(2, n + 1):\n L[i][j] = L[i - 1][j] + L[i][j - 1]\nreturn L[m][n]", "def f(i, j):\n if i == 0 and j == 0:\n ...
<|body_start_0|> L = [[0 for i in range(n + 1)] for i in range(m + 1)] for i in range(1, n + 1): L[1][i] = 1 for i in range(1, m + 1): L[i][1] = 1 for i in range(2, m + 1): for j in range(2, n + 1): L[i][j] = L[i - 1][j] + L[i][j - 1] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_0|> def uniquePaths_2(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_1|> def uniquePaths_3(self, m, n): """:type m: int :type n: int :rtype...
stack_v2_sparse_classes_75kplus_train_068629
1,233
no_license
[ { "docstring": ":type m: int :type n: int :rtype: int", "name": "uniquePaths", "signature": "def uniquePaths(self, m, n)" }, { "docstring": ":type m: int :type n: int :rtype: int", "name": "uniquePaths_2", "signature": "def uniquePaths_2(self, m, n)" }, { "docstring": ":type m: i...
3
stack_v2_sparse_classes_30k_train_034500
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int - def uniquePaths_2(self, m, n): :type m: int :type n: int :rtype: int - def uniquePaths_3(self, m, n): :type m...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int - def uniquePaths_2(self, m, n): :type m: int :type n: int :rtype: int - def uniquePaths_3(self, m, n): :type m...
bd8df12c0d4afd048cf1b58b04c27fa1f3622769
<|skeleton|> class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_0|> def uniquePaths_2(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_1|> def uniquePaths_3(self, m, n): """:type m: int :type n: int :rtype...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" L = [[0 for i in range(n + 1)] for i in range(m + 1)] for i in range(1, n + 1): L[1][i] = 1 for i in range(1, m + 1): L[i][1] = 1 for i in range(2, m + 1): ...
the_stack_v2_python_sparse
62_unique_paths.py
aojugg/leetcode
train
0
5b93de504b0861a22f9fe63fda0d0c0966d18adb
[ "new = ChillDictionary()\nself[key] = new\nreturn new", "if key in self:\n return self[key]\nself[key] = default\nreturn default", "out = dict()\nfor key in self:\n if isinstance(self[key], ChillDictionary):\n out[key] = self[key].dict()\n else:\n out[key] = self[key]\nreturn out" ]
<|body_start_0|> new = ChillDictionary() self[key] = new return new <|end_body_0|> <|body_start_1|> if key in self: return self[key] self[key] = default return default <|end_body_1|> <|body_start_2|> out = dict() for key in self: ...
Dictionary that sets empty keys to chill dictionaries.
ChillDictionary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChillDictionary: """Dictionary that sets empty keys to chill dictionaries.""" def __missing__(self, key): """Called when a missing key is invoked.""" <|body_0|> def set(self, key, default): """Similar to get, except sets the internal key to the default.""" ...
stack_v2_sparse_classes_75kplus_train_068630
11,082
no_license
[ { "docstring": "Called when a missing key is invoked.", "name": "__missing__", "signature": "def __missing__(self, key)" }, { "docstring": "Similar to get, except sets the internal key to the default.", "name": "set", "signature": "def set(self, key, default)" }, { "docstring": "...
3
stack_v2_sparse_classes_30k_train_037083
Implement the Python class `ChillDictionary` described below. Class description: Dictionary that sets empty keys to chill dictionaries. Method signatures and docstrings: - def __missing__(self, key): Called when a missing key is invoked. - def set(self, key, default): Similar to get, except sets the internal key to t...
Implement the Python class `ChillDictionary` described below. Class description: Dictionary that sets empty keys to chill dictionaries. Method signatures and docstrings: - def __missing__(self, key): Called when a missing key is invoked. - def set(self, key, default): Similar to get, except sets the internal key to t...
68b5f01334c6357bec4a440f8d54e7552b890291
<|skeleton|> class ChillDictionary: """Dictionary that sets empty keys to chill dictionaries.""" def __missing__(self, key): """Called when a missing key is invoked.""" <|body_0|> def set(self, key, default): """Similar to get, except sets the internal key to the default.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChillDictionary: """Dictionary that sets empty keys to chill dictionaries.""" def __missing__(self, key): """Called when a missing key is invoked.""" new = ChillDictionary() self[key] = new return new def set(self, key, default): """Similar to get, except sets...
the_stack_v2_python_sparse
grading/grading.py
sZwX74/mbmt
train
0
007a3022c412c1b162a6c076f39f3b25c61322dc
[ "self.capacity = capacity\nself.table = {}\nself.step = 0\nself.freq_2_key = {}", "if key in self.table:\n v, freq = self.table[key]\n self.table[key] = (v, freq + 1)\n self.freq_2_key[freq].remove(key)\n if len(self.freq_2_key[freq]) == 0:\n del self.freq_2_key[freq]\n if freq + 1 not in se...
<|body_start_0|> self.capacity = capacity self.table = {} self.step = 0 self.freq_2_key = {} <|end_body_0|> <|body_start_1|> if key in self.table: v, freq = self.table[key] self.table[key] = (v, freq + 1) self.freq_2_key[freq].remove(key) ...
LFUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_068631
3,407
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_val_001608
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
4d73e4c1f2017828ff2d36058819988146356abe
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LFUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.table = {} self.step = 0 self.freq_2_key = {} def get(self, key): """:type key: int :rtype: int""" if key in self.table: v, freq = self.table...
the_stack_v2_python_sparse
python/leetcode/system_design/460_lfu_cache.py
zchen0211/topcoder
train
0
a17853f729d79e6cd9d61e82ecd3ce4a3f07fe9b
[ "super().__init__()\nif weights.dim() != 1:\n raise ValueError('weights must be a one-dimensional tensor.')\nself.register_buffer('weights', weights)", "if samples.shape[-1] != self.weights.shape[-1]:\n raise RuntimeError('Output shape of samples not equal to that of weights')\nreturn torch.einsum('...m, m'...
<|body_start_0|> super().__init__() if weights.dim() != 1: raise ValueError('weights must be a one-dimensional tensor.') self.register_buffer('weights', weights) <|end_body_0|> <|body_start_1|> if samples.shape[-1] != self.weights.shape[-1]: raise RuntimeError('O...
Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >>> linear_objective = LinearMCObjective(weigh...
LinearMCObjective
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearMCObjective: """Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >...
stack_v2_sparse_classes_75kplus_train_068632
8,967
permissive
[ { "docstring": "Linear Objective. Args: weights: A one-dimensional tensor with `m` elements representing the linear weights on the outputs.", "name": "__init__", "signature": "def __init__(self, weights: Tensor) -> None" }, { "docstring": "Evaluate the linear objective on the samples. Args: samp...
2
stack_v2_sparse_classes_30k_train_047263
Implement the Python class `LinearMCObjective` described below. Class description: Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>>...
Implement the Python class `LinearMCObjective` described below. Class description: Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>>...
af13f0a38b579ab504f49a01f1ced13532a3ad49
<|skeleton|> class LinearMCObjective: """Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinearMCObjective: """Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >>> linear_obj...
the_stack_v2_python_sparse
botorch/acquisition/objective.py
shalijiang/bo
train
1
fe668ccd05a105915ac46ec0fcab245e1c1ef886
[ "try:\n path = os.path.join(ROOT_DIR, '../tests/results.json')\n results = self.__get_mock_results(path)\nexcept Exception as ex:\n raise ex\nraise gen.Return(results)", "try:\n results = '{\"$oid\": \"59dc3e8c8f54a9000d1fb89f\"}'\n if not results:\n raise Exception('Failed to write results ...
<|body_start_0|> try: path = os.path.join(ROOT_DIR, '../tests/results.json') results = self.__get_mock_results(path) except Exception as ex: raise ex raise gen.Return(results) <|end_body_0|> <|body_start_1|> try: results = '{"$oid": "59dc3...
Provides a testing mock for the mongo results handler
TestResultsProvider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestResultsProvider: """Provides a testing mock for the mongo results handler""" def get_results(self, result_id=None): """Method implements the results mock of mongo args: result_id: key to get data from results db Returns: data responding to the result_id""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_068633
3,775
no_license
[ { "docstring": "Method implements the results mock of mongo args: result_id: key to get data from results db Returns: data responding to the result_id", "name": "get_results", "signature": "def get_results(self, result_id=None)" }, { "docstring": "Method implements the write results mock of mong...
6
stack_v2_sparse_classes_30k_train_036831
Implement the Python class `TestResultsProvider` described below. Class description: Provides a testing mock for the mongo results handler Method signatures and docstrings: - def get_results(self, result_id=None): Method implements the results mock of mongo args: result_id: key to get data from results db Returns: da...
Implement the Python class `TestResultsProvider` described below. Class description: Provides a testing mock for the mongo results handler Method signatures and docstrings: - def get_results(self, result_id=None): Method implements the results mock of mongo args: result_id: key to get data from results db Returns: da...
7c3edfbb6c2708b96b8c8d61fe865dbb1357690e
<|skeleton|> class TestResultsProvider: """Provides a testing mock for the mongo results handler""" def get_results(self, result_id=None): """Method implements the results mock of mongo args: result_id: key to get data from results db Returns: data responding to the result_id""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestResultsProvider: """Provides a testing mock for the mongo results handler""" def get_results(self, result_id=None): """Method implements the results mock of mongo args: result_id: key to get data from results db Returns: data responding to the result_id""" try: path = os.p...
the_stack_v2_python_sparse
results/webapi/providers/test_results_provider.py
KamilBabayev/webapi_temp
train
0
58c518cc25c1c52d486e42f18c2d51f7a6a704f4
[ "params = get_params(locals())\nraw_result = await self.api_request('getFriends', params)\nif return_raw_response:\n return raw_result\nresult = GroupsGetMembersFieldsResponse(**raw_result)\nreturn result", "params = get_params(locals())\nraw_result = await self.api_request('getSubscription', params)\nif retur...
<|body_start_0|> params = get_params(locals()) raw_result = await self.api_request('getFriends', params) if return_raw_response: return raw_result result = GroupsGetMembersFieldsResponse(**raw_result) return result <|end_body_0|> <|body_start_1|> params = get...
Donut
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Donut: async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Optional[int]=None, fields: typing.Optional[typing.List[str]]=None) -> typing.Union[dict, GroupsGetMembersFieldsResponse]: """:param owner_id: :param offset...
stack_v2_sparse_classes_75kplus_train_068634
2,692
permissive
[ { "docstring": ":param owner_id: :param offset: :param count: :param fields: :param return_raw_response: - return result at dict :return:", "name": "get_friends", "signature": "async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Op...
4
null
Implement the Python class `Donut` described below. Class description: Implement the Donut class. Method signatures and docstrings: - async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Optional[int]=None, fields: typing.Optional[typing.List[str...
Implement the Python class `Donut` described below. Class description: Implement the Donut class. Method signatures and docstrings: - async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Optional[int]=None, fields: typing.Optional[typing.List[str...
d88311a680e52faf04f3a18f9c5b381ee9e94a8f
<|skeleton|> class Donut: async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Optional[int]=None, fields: typing.Optional[typing.List[str]]=None) -> typing.Union[dict, GroupsGetMembersFieldsResponse]: """:param owner_id: :param offset...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Donut: async def get_friends(self, owner_id: int, return_raw_response: bool=False, offset: typing.Optional[int]=None, count: typing.Optional[int]=None, fields: typing.Optional[typing.List[str]]=None) -> typing.Union[dict, GroupsGetMembersFieldsResponse]: """:param owner_id: :param offset: :param count...
the_stack_v2_python_sparse
vkwave/api/methods/donut.py
prog1ckg/vkwave
train
0
545c8eb00e8fccc48337122a49737e786fad4e3f
[ "sql = \"select table_name from user_tables where table_name='%s'\" % table_name.upper()\nrecords = db_query.select(sql)\nif len(records) == 0:\n return False\nreturn True", "field = attr.name\nif attr.attr_type == type_def.TYPE_UINT32 or attr.attr_type == type_def.TYPE_INT32:\n field = '\"%s\" NUMBER(10, 0...
<|body_start_0|> sql = "select table_name from user_tables where table_name='%s'" % table_name.upper() records = db_query.select(sql) if len(records) == 0: return False return True <|end_body_0|> <|body_start_1|> field = attr.name if attr.attr_type == type_de...
Class: DBOperator Description: ݿṹ Others:
DBOperator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBOperator: """Class: DBOperator Description: ݿṹ Others:""" def check_table_exists(self, db_query, table_name): """Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others:""" <|body_0|> def get_field_def(self, attr): ...
stack_v2_sparse_classes_75kplus_train_068635
1,773
no_license
[ { "docstring": "Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others:", "name": "check_table_exists", "signature": "def check_table_exists(self, db_query, table_name)" }, { "docstring": "Method: get_field_def Description: õֶεĶַ Parameter: Re...
2
stack_v2_sparse_classes_30k_train_016760
Implement the Python class `DBOperator` described below. Class description: Class: DBOperator Description: ݿṹ Others: Method signatures and docstrings: - def check_table_exists(self, db_query, table_name): Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others: - d...
Implement the Python class `DBOperator` described below. Class description: Class: DBOperator Description: ݿṹ Others: Method signatures and docstrings: - def check_table_exists(self, db_query, table_name): Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others: - d...
e78df71fbc5d73dd93ba9452d4b54183fe1e7e1f
<|skeleton|> class DBOperator: """Class: DBOperator Description: ݿṹ Others:""" def check_table_exists(self, db_query, table_name): """Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others:""" <|body_0|> def get_field_def(self, attr): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DBOperator: """Class: DBOperator Description: ݿṹ Others:""" def check_table_exists(self, db_query, table_name): """Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,򷵻false Others:""" sql = "select table_name from user_tables where table_name='%s...
the_stack_v2_python_sparse
weixin/code/rfid_plt/base_platform/db_sync/db_operator.py
allenforrest/wxbiz
train
0
c7d3058adb3adc382a053cd838abdc54a7ba6bb6
[ "self.__password = password\nself.__class_code = class_code\nself.__msg = {'Class Code': '', 'Password': ''}", "if len(self.__class_code) == 0:\n self.__msg['Class Code'] += 'Class Code cannot be empty.\\n'\nif len(self.__password) == 0:\n self.__msg['Password'] += 'Password cannot be empty.\\n'\nif not all...
<|body_start_0|> self.__password = password self.__class_code = class_code self.__msg = {'Class Code': '', 'Password': ''} <|end_body_0|> <|body_start_1|> if len(self.__class_code) == 0: self.__msg['Class Code'] += 'Class Code cannot be empty.\n' if len(self.__passwo...
This class is responsible for the page login.
LoginController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoginController: """This class is responsible for the page login.""" def __init__(self, password, class_code): """Init variables. :param password: the student password :param class_code: the student class code""" <|body_0|> def check_validation(self): """Check va...
stack_v2_sparse_classes_75kplus_train_068636
2,337
no_license
[ { "docstring": "Init variables. :param password: the student password :param class_code: the student class code", "name": "__init__", "signature": "def __init__(self, password, class_code)" }, { "docstring": "Check validation of student password & class_code.", "name": "check_validation", ...
4
stack_v2_sparse_classes_30k_train_005788
Implement the Python class `LoginController` described below. Class description: This class is responsible for the page login. Method signatures and docstrings: - def __init__(self, password, class_code): Init variables. :param password: the student password :param class_code: the student class code - def check_valid...
Implement the Python class `LoginController` described below. Class description: This class is responsible for the page login. Method signatures and docstrings: - def __init__(self, password, class_code): Init variables. :param password: the student password :param class_code: the student class code - def check_valid...
607e459d737ac689d6974bf05f452abf89cbdfe2
<|skeleton|> class LoginController: """This class is responsible for the page login.""" def __init__(self, password, class_code): """Init variables. :param password: the student password :param class_code: the student class code""" <|body_0|> def check_validation(self): """Check va...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoginController: """This class is responsible for the page login.""" def __init__(self, password, class_code): """Init variables. :param password: the student password :param class_code: the student class code""" self.__password = password self.__class_code = class_code se...
the_stack_v2_python_sparse
UiController/logInPageController.py
alexshachor/TheBackEye
train
0
f153e5e737100848da34512649d749f117760581
[ "self.file_name = file_name\nself.file_handler = None\nreturn", "print('enter: ', self.file_name)\nself.file_handler = open(self.file_name, 'r')\nreturn self.file_handler", "print('exit: ', exc_type, exc_val, exc_tb)\nif self.file_handler:\n self.file_handler.close()\nreturn True" ]
<|body_start_0|> self.file_name = file_name self.file_handler = None return <|end_body_0|> <|body_start_1|> print('enter: ', self.file_name) self.file_handler = open(self.file_name, 'r') return self.file_handler <|end_body_1|> <|body_start_2|> print('exit: ', ex...
MyOpen
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyOpen: def __init__(self, file_name): """初始化""" <|body_0|> def __enter__(self): """返回 file_handler""" <|body_1|> def __exit__(self, exc_type, exc_val, exc_tb): """关闭文件并返回 True""" <|body_2|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_75kplus_train_068637
7,325
no_license
[ { "docstring": "初始化", "name": "__init__", "signature": "def __init__(self, file_name)" }, { "docstring": "返回 file_handler", "name": "__enter__", "signature": "def __enter__(self)" }, { "docstring": "关闭文件并返回 True", "name": "__exit__", "signature": "def __exit__(self, exc_t...
3
null
Implement the Python class `MyOpen` described below. Class description: Implement the MyOpen class. Method signatures and docstrings: - def __init__(self, file_name): 初始化 - def __enter__(self): 返回 file_handler - def __exit__(self, exc_type, exc_val, exc_tb): 关闭文件并返回 True
Implement the Python class `MyOpen` described below. Class description: Implement the MyOpen class. Method signatures and docstrings: - def __init__(self, file_name): 初始化 - def __enter__(self): 返回 file_handler - def __exit__(self, exc_type, exc_val, exc_tb): 关闭文件并返回 True <|skeleton|> class MyOpen: def __init__(...
d04cf523ef71b08fe43ed0ddf6ba194f1715fd79
<|skeleton|> class MyOpen: def __init__(self, file_name): """初始化""" <|body_0|> def __enter__(self): """返回 file_handler""" <|body_1|> def __exit__(self, exc_type, exc_val, exc_tb): """关闭文件并返回 True""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyOpen: def __init__(self, file_name): """初始化""" self.file_name = file_name self.file_handler = None return def __enter__(self): """返回 file_handler""" print('enter: ', self.file_name) self.file_handler = open(self.file_name, 'r') return self...
the_stack_v2_python_sparse
python_cookbook/chapter8_class_and_object/chapter8_class_and_object.py
leizhen10000/learnPython
train
0
17255d87d5b3395fce38a522127d52beea687d42
[ "clf = None\nif not is_categorical:\n clf = neighbors.KNeighborsRegressor(n_neighbors=k)\nelse:\n clf = ScrappyKNN()\nmissing_idxes = np.where(pd.isnull(X[:, column]))[0]\nif len(missing_idxes) == 0:\n return None\nX_copy = np.delete(X, missing_idxes, 0)\nX_train = np.delete(X_copy, column, 1)\ncol_mean = ...
<|body_start_0|> clf = None if not is_categorical: clf = neighbors.KNeighborsRegressor(n_neighbors=k) else: clf = ScrappyKNN() missing_idxes = np.where(pd.isnull(X[:, column]))[0] if len(missing_idxes) == 0: return None X_copy = np.dele...
Imputer class.
Imputer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Imputer: """Imputer class.""" def _fit(self, X, column, k=10, is_categorical=False): """Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti...
stack_v2_sparse_classes_75kplus_train_068638
8,299
no_license
[ { "docstring": "Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or categorical feature - Returns: clf: trained k nearest neighbour classifier", "name": "_...
4
stack_v2_sparse_classes_30k_train_015314
Implement the Python class `Imputer` described below. Class description: Imputer class. Method signatures and docstrings: - def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares...
Implement the Python class `Imputer` described below. Class description: Imputer class. Method signatures and docstrings: - def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares...
5c3f723b43e0bbc88f3ed50f6ac66a116df696ff
<|skeleton|> class Imputer: """Imputer class.""" def _fit(self, X, column, k=10, is_categorical=False): """Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Imputer: """Imputer class.""" def _fit(self, X, column, k=10, is_categorical=False): """Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or cate...
the_stack_v2_python_sparse
knn_imputation.py
YujiaFan10/Machine-Learning-634
train
0
f2d2aaf2387714112c9fcce70df4a07e61d62267
[ "threading.Thread.__init__(self, group=group, target=target, name=name, args=args, kwargs=kw_args)\nself._srvr = SOAPpy.WSDL.Proxy(wsdl)\nself._queue = queue\nself._lock = threading.Lock()", "while True:\n function, item, output = self._queue.get()\n try:\n info = eval('self._srvr.%s(item)' % functio...
<|body_start_0|> threading.Thread.__init__(self, group=group, target=target, name=name, args=args, kwargs=kw_args) self._srvr = SOAPpy.WSDL.Proxy(wsdl) self._queue = queue self._lock = threading.Lock() <|end_body_0|> <|body_start_1|> while True: function, item, outpu...
A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection.
ThreadedWSDLFetcher
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreadedWSDLFetcher: """A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection.""" def __init__(self, queue, wsdl, group=None, targ...
stack_v2_sparse_classes_75kplus_train_068639
2,483
permissive
[ { "docstring": "Parameters ---------- queue: Queue.Queue Task queue that contains triples of a string with the function name to be queried on the WSDL server, the query string, and the container (list) to attach results to. wsdl: str URL of the WSDL server. The remaining parameters are the same as for the threa...
2
stack_v2_sparse_classes_30k_train_034131
Implement the Python class `ThreadedWSDLFetcher` described below. Class description: A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection. Method signature...
Implement the Python class `ThreadedWSDLFetcher` described below. Class description: A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection. Method signature...
9459b51bb6f33c7d3c644cd95a9d72a0862470e6
<|skeleton|> class ThreadedWSDLFetcher: """A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection.""" def __init__(self, queue, wsdl, group=None, targ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThreadedWSDLFetcher: """A Thread class that fetches instructions from the queue passed to the constructor and queries the given WSDL server attaching the result to a given list. Notes ----- Requires SOAPpy and an active internet connection.""" def __init__(self, queue, wsdl, group=None, target=None, name...
the_stack_v2_python_sparse
pyorganism/io/wsdl.py
Midnighter/pyorganism
train
2
07a5a08de00dfad9ee22820ed6e10c7b44eca0e9
[ "if len(names) == 0:\n self._leader = None\nelse:\n self._leader = Person(names[0])\n current_person = self._leader\n for name in names[1:]:\n current_person.next = Person(name)\n current_person = current_person.next", "if self._leader is None:\n raise ShortChainError\nelse:\n retu...
<|body_start_0|> if len(names) == 0: self._leader = None else: self._leader = Person(names[0]) current_person = self._leader for name in names[1:]: current_person.next = Person(name) current_person = current_person.next <|en...
A chain of people.
PeopleChain
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeopleChain: """A chain of people.""" def __init__(self, names): """Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None""" <|body_0|> def get_l...
stack_v2_sparse_classes_75kplus_train_068640
2,417
no_license
[ { "docstring": "Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None", "name": "__init__", "signature": "def __init__(self, names)" }, { "docstring": "Return the name of...
2
stack_v2_sparse_classes_30k_train_018585
Implement the Python class `PeopleChain` described below. Class description: A chain of people. Method signatures and docstrings: - def __init__(self, names): Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: li...
Implement the Python class `PeopleChain` described below. Class description: A chain of people. Method signatures and docstrings: - def __init__(self, names): Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: li...
e00ae4246165e031b00cb7be0e9c0c1d60d49a75
<|skeleton|> class PeopleChain: """A chain of people.""" def __init__(self, names): """Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None""" <|body_0|> def get_l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PeopleChain: """A chain of people.""" def __init__(self, names): """Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None""" if len(names) == 0: self._...
the_stack_v2_python_sparse
python_class_proj/pycharm/csc148/exercises/ex2/tsets.py
Mohan-Zhang-u/From_UofT
train
0
8216f9570e209ebf0adeadca074657a457035629
[ "self.file = template\nself.params = params\nself.template = None\nif template_string:\n self.template = template_string\nelse:\n if not self.file.startswith(os.path.sep):\n self.file = os.path.join(config.TEMPLATE_DIR, self.file)\n if not (os.path.exists(self.file) and os.path.isfile(self.file)):\n...
<|body_start_0|> self.file = template self.params = params self.template = None if template_string: self.template = template_string else: if not self.file.startswith(os.path.sep): self.file = os.path.join(config.TEMPLATE_DIR, self.file) ...
A very simple template class. Basically a wrapper around the printf style string substition.
Template
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Template: """A very simple template class. Basically a wrapper around the printf style string substition.""" def __init__(self, params, template=None, template_string=None): """Create a new template object.""" <|body_0|> def process(self, data): """Process the te...
stack_v2_sparse_classes_75kplus_train_068641
1,908
no_license
[ { "docstring": "Create a new template object.", "name": "__init__", "signature": "def __init__(self, params, template=None, template_string=None)" }, { "docstring": "Process the template with the template parameters bound to the matching values of data dictionary. Returns the template output as ...
3
stack_v2_sparse_classes_30k_val_001980
Implement the Python class `Template` described below. Class description: A very simple template class. Basically a wrapper around the printf style string substition. Method signatures and docstrings: - def __init__(self, params, template=None, template_string=None): Create a new template object. - def process(self, ...
Implement the Python class `Template` described below. Class description: A very simple template class. Basically a wrapper around the printf style string substition. Method signatures and docstrings: - def __init__(self, params, template=None, template_string=None): Create a new template object. - def process(self, ...
583411b6620fcc1cd2c635a738782869e830f89d
<|skeleton|> class Template: """A very simple template class. Basically a wrapper around the printf style string substition.""" def __init__(self, params, template=None, template_string=None): """Create a new template object.""" <|body_0|> def process(self, data): """Process the te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Template: """A very simple template class. Basically a wrapper around the printf style string substition.""" def __init__(self, params, template=None, template_string=None): """Create a new template object.""" self.file = template self.params = params self.template = None ...
the_stack_v2_python_sparse
repopy/templates.py
efroese/svnsh
train
0
8a4de9d85f86018c8ad2dae69f42da9d10f9af3b
[ "if not p and (not q):\n return True\nif not p or not q:\n return False\nif p.val != q.val:\n return self.isSameTree(p.left, q.left) and self.isSameTree(q.right, q.right)", "if not p and (not q):\n return True\nif not p or not q:\n return False\nqueue1 = collections.deque([q])\nqueue2 = collections...
<|body_start_0|> if not p and (not q): return True if not p or not q: return False if p.val != q.val: return self.isSameTree(p.left, q.left) and self.isSameTree(q.right, q.right) <|end_body_0|> <|body_start_1|> if not p and (not q): return...
题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点""" def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: """DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :return:""" <|body_0|> def isSameTree2(self, ...
stack_v2_sparse_classes_75kplus_train_068642
2,168
no_license
[ { "docstring": "DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :return:", "name": "isSameTree", "signature": "def isSameTree(self, p: TreeNode, q: TreeNode) -> bool" }, { "docstring": "BFS c :param p: :param q: :return:", "name": "isSameTree2", "sig...
2
stack_v2_sparse_classes_30k_train_041591
Implement the Python class `Solution` described below. Class description: 题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点 Method signatures and docstrings: - def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :...
Implement the Python class `Solution` described below. Class description: 题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点 Method signatures and docstrings: - def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :...
578cacff5851c5c2522981693c34e3c318002d30
<|skeleton|> class Solution: """题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点""" def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: """DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :return:""" <|body_0|> def isSameTree2(self, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: """题解思路:利用递归,暴力思路 如果q,p全空,那么自然完全相等返回True 如果有一个空,那么返回False 递归判断下一个节点""" def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: """DFS 时间复杂度: O(min(m,n)) m和n 是p和q的深度 空间复杂度: O(min(m,n)) m和n 是p和q的深度 :param p: :param q: :return:""" if not p and (not q): return True ...
the_stack_v2_python_sparse
相同的树.py
cjrzs/MyLeetCode
train
8
eef8fba1d80a5522f3b62d44be6a28f5dda4719e
[ "start = time_ns() // 1000000\nbuffer = bytes()\nwhile not buffer.endswith(b'z00\\n'):\n wait = timeout - (time_ns() // 1000000 - start)\n if wait <= 0:\n break\n buffer += self.read(1 if not buffer else 0, wait)\nif not buffer:\n return {}\nmsgs = buffer.split(b'\\n')\nif buffer.endswith(b'\\n')...
<|body_start_0|> start = time_ns() // 1000000 buffer = bytes() while not buffer.endswith(b'z00\n'): wait = timeout - (time_ns() // 1000000 - start) if wait <= 0: break buffer += self.read(1 if not buffer else 0, wait) if not buffer: ...
A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link.
SimpleSerialTarget
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleSerialTarget: """A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link.""" def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSerialMessage]: """Receive :py:class:`SimpleSerialMessage` messages, while waiting upto :paramref:`~.recv_msgs.tim...
stack_v2_sparse_classes_75kplus_train_068643
2,759
permissive
[ { "docstring": "Receive :py:class:`SimpleSerialMessage` messages, while waiting upto :paramref:`~.recv_msgs.timeout` seconds. :param timeout: How long to wait. :return: The received messages with their char.", "name": "recv_msgs", "signature": "def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSer...
2
stack_v2_sparse_classes_30k_train_011750
Implement the Python class `SimpleSerialTarget` described below. Class description: A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link. Method signatures and docstrings: - def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSerialMessage]: Receive :py:class:`SimpleSerialMessage...
Implement the Python class `SimpleSerialTarget` described below. Class description: A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link. Method signatures and docstrings: - def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSerialMessage]: Receive :py:class:`SimpleSerialMessage...
f40b69968ad9bbb8300b451640a82e1ac83aa7ba
<|skeleton|> class SimpleSerialTarget: """A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link.""" def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSerialMessage]: """Receive :py:class:`SimpleSerialMessage` messages, while waiting upto :paramref:`~.recv_msgs.tim...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleSerialTarget: """A SimpleSerial-ish target, sends and receives SimpleSerial messages over a serial link.""" def recv_msgs(self, timeout: int) -> Mapping[str, SimpleSerialMessage]: """Receive :py:class:`SimpleSerialMessage` messages, while waiting upto :paramref:`~.recv_msgs.timeout` seconds...
the_stack_v2_python_sparse
pyecsca/sca/target/simpleserial.py
J08nY/pyecsca
train
40
536ed79a32703b4c03374a2d55242c59e548df6f
[ "m_path = os.path.join(model_path, name)\nif not os.path.exists(m_path):\n raise ValueError('[InsurancePriceModel] %s do not exist' % m_path)\nkeras_path = os.path.join(m_path, KERAS)\nreturn KerasModel(keras_path)", "if not os.path.exists(model_path):\n raise ValueError('[InsurancePriceModel] %s do not exi...
<|body_start_0|> m_path = os.path.join(model_path, name) if not os.path.exists(m_path): raise ValueError('[InsurancePriceModel] %s do not exist' % m_path) keras_path = os.path.join(m_path, KERAS) return KerasModel(keras_path) <|end_body_0|> <|body_start_1|> if not os...
InsurancePriceModel
InsurancePriceModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InsurancePriceModel: """InsurancePriceModel""" def load_sub_model(model_path, name): """load sub model :param model_path: path for sub model :param name:sub model name :return: keras model""" <|body_0|> def __init__(self, model_path): """Loader :param model_path:...
stack_v2_sparse_classes_75kplus_train_068644
3,270
no_license
[ { "docstring": "load sub model :param model_path: path for sub model :param name:sub model name :return: keras model", "name": "load_sub_model", "signature": "def load_sub_model(model_path, name)" }, { "docstring": "Loader :param model_path: string :return:", "name": "__init__", "signatu...
3
null
Implement the Python class `InsurancePriceModel` described below. Class description: InsurancePriceModel Method signatures and docstrings: - def load_sub_model(model_path, name): load sub model :param model_path: path for sub model :param name:sub model name :return: keras model - def __init__(self, model_path): Load...
Implement the Python class `InsurancePriceModel` described below. Class description: InsurancePriceModel Method signatures and docstrings: - def load_sub_model(model_path, name): load sub model :param model_path: path for sub model :param name:sub model name :return: keras model - def __init__(self, model_path): Load...
c3c453f402bedc7a22dc0f873a602180f94678ef
<|skeleton|> class InsurancePriceModel: """InsurancePriceModel""" def load_sub_model(model_path, name): """load sub model :param model_path: path for sub model :param name:sub model name :return: keras model""" <|body_0|> def __init__(self, model_path): """Loader :param model_path:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InsurancePriceModel: """InsurancePriceModel""" def load_sub_model(model_path, name): """load sub model :param model_path: path for sub model :param name:sub model name :return: keras model""" m_path = os.path.join(model_path, name) if not os.path.exists(m_path): raise ...
the_stack_v2_python_sparse
model-serving/model_serving/models/insurance_price_model/insurance_price_model.py
StevenYang88/tuanxian_price
train
0
6dcf7f343ee8609ce02daf7574b86a91cd5e3894
[ "self.end_time_usecs = end_time_usecs\nself.location = location\nself.policy_id = policy_id\nself.protection_job_id = protection_job_id\nself.protection_job_name = protection_job_name\nself.retention_period = retention_period\nself.start_time_usecs = start_time_usecs\nself.storage_domain = storage_domain\nself.tota...
<|body_start_0|> self.end_time_usecs = end_time_usecs self.location = location self.policy_id = policy_id self.protection_job_id = protection_job_id self.protection_job_name = protection_job_name self.retention_period = retention_period self.start_time_usecs = sta...
Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the object. policy_id (string): Specifies the id of the policy. protection_job_id (long|i...
ProtectionInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtectionInfo: """Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the object. policy_id (string): Specifies the i...
stack_v2_sparse_classes_75kplus_train_068645
3,705
permissive
[ { "docstring": "Constructor for the ProtectionInfo class", "name": "__init__", "signature": "def __init__(self, end_time_usecs=None, location=None, policy_id=None, protection_job_id=None, protection_job_name=None, retention_period=None, start_time_usecs=None, storage_domain=None, total_snapshots=None)" ...
2
null
Implement the Python class `ProtectionInfo` described below. Class description: Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the obje...
Implement the Python class `ProtectionInfo` described below. Class description: Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the obje...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ProtectionInfo: """Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the object. policy_id (string): Specifies the i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProtectionInfo: """Implementation of the 'ProtectionInfo' model. dataLocation defines data location related information. Attributes: end_time_usecs (long|int): Specifies the end time for object retention. location (string): Specifies the location of the object. policy_id (string): Specifies the id of the poli...
the_stack_v2_python_sparse
cohesity_management_sdk/models/protection_info.py
cohesity/management-sdk-python
train
24
912c977ab1136937807f5b515b80fb20c42ac2ce
[ "self.filename = filename\ninput_file = open(self.filename, 'r')\nself.data = input_file.readlines()\ninput_file.close()\nself.line_no = 0", "line = self.data[self.line_no]\nself.line_no += 1\nwhile line.startswith('#') or line.startswith('%'):\n line = self.data[self.line_no]\n self.line_no += 1\ncomment_m...
<|body_start_0|> self.filename = filename input_file = open(self.filename, 'r') self.data = input_file.readlines() input_file.close() self.line_no = 0 <|end_body_0|> <|body_start_1|> line = self.data[self.line_no] self.line_no += 1 while line.startswith('...
This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method.
OptFile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptFile: """This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method.""" def __init__(self, filename): """This function reads the option file pointed by filename.""" ...
stack_v2_sparse_classes_75kplus_train_068646
1,306
permissive
[ { "docstring": "This function reads the option file pointed by filename.", "name": "__init__", "signature": "def __init__(self, filename)" }, { "docstring": "This function returns the next option we read from the option file.", "name": "get_next_option", "signature": "def get_next_option...
2
stack_v2_sparse_classes_30k_train_044456
Implement the Python class `OptFile` described below. Class description: This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method. Method signatures and docstrings: - def __init__(self, filename): This fun...
Implement the Python class `OptFile` described below. Class description: This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method. Method signatures and docstrings: - def __init__(self, filename): This fun...
bc0cce2378aa071a5537d25c1a738e58ef610561
<|skeleton|> class OptFile: """This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method.""" def __init__(self, filename): """This function reads the option file pointed by filename.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OptFile: """This class is used to open and read an option file. It stores the information locally and returns each option individually, after each call to its get_next_option method.""" def __init__(self, filename): """This function reads the option file pointed by filename.""" self.filen...
the_stack_v2_python_sparse
bbp/comps/optfile.py
alborzgh/bbp
train
0
35627b9641f4490165d5df8f4d2df351e57659ba
[ "with self._get_session() as session:\n response = requests.get(url, params=params or {}, headers=headers or {})\n response.raise_for_status()\n return response.json(object_hook=json_obj_hook)", "session = requests.Session()\nsession.mount(self._base_url, adapter=TimeoutHTTPAdapter(timeout=60, max_retrie...
<|body_start_0|> with self._get_session() as session: response = requests.get(url, params=params or {}, headers=headers or {}) response.raise_for_status() return response.json(object_hook=json_obj_hook) <|end_body_0|> <|body_start_1|> session = requests.Session() ...
BaseAPI
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseAPI: def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None): """Perform an HTTP GET request, and return the JSON response payload. Same timeouts and retry strategy as `_get_session` above.""" <|body_0|> def _get_session(self) -> Se...
stack_v2_sparse_classes_75kplus_train_068647
3,062
permissive
[ { "docstring": "Perform an HTTP GET request, and return the JSON response payload. Same timeouts and retry strategy as `_get_session` above.", "name": "get_json_from_url", "signature": "def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None)" }, { "docstrin...
3
null
Implement the Python class `BaseAPI` described below. Class description: Implement the BaseAPI class. Method signatures and docstrings: - def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None): Perform an HTTP GET request, and return the JSON response payload. Same timeouts and...
Implement the Python class `BaseAPI` described below. Class description: Implement the BaseAPI class. Method signatures and docstrings: - def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None): Perform an HTTP GET request, and return the JSON response payload. Same timeouts and...
45dff06ba21f1afdb43a434c9ba0fc49e07b48d8
<|skeleton|> class BaseAPI: def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None): """Perform an HTTP GET request, and return the JSON response payload. Same timeouts and retry strategy as `_get_session` above.""" <|body_0|> def _get_session(self) -> Se...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseAPI: def get_json_from_url(self, url, params=None, *, json_obj_hook: t.Callable=None, headers=None): """Perform an HTTP GET request, and return the JSON response payload. Same timeouts and retry strategy as `_get_session` above.""" with self._get_session() as session: response ...
the_stack_v2_python_sparse
hasher-matcher-actioner/hmalib/common/external_api.py
facebook/ThreatExchange
train
1,146
33b528fa2b23de58e8d325c2dcdd2fe335d60c52
[ "Base.__init__(self, target, opts)\nself.host, self.port, self.scheme, self.path = self._parse_url(self.target)\nreturn", "opts = f\"--no-analysis --skip-poc --crawl --user-agent '{self.useragent}'\"\nopts += ' -o /tmp/'\ntarget = self.target\nif self.opts['attack_url']:\n target = self.opts['attack_url']\nif ...
<|body_start_0|> Base.__init__(self, target, opts) self.host, self.port, self.scheme, self.path = self._parse_url(self.target) return <|end_body_0|> <|body_start_1|> opts = f"--no-analysis --skip-poc --crawl --user-agent '{self.useragent}'" opts += ' -o /tmp/' target = s...
Cross-Site Request Forgery module
CSRF
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CSRF: """Cross-Site Request Forgery module""" def __init__(self, target, opts): """init""" <|body_0|> def xsrfprobe(self): """DESCR: Crawl and check for CSRF vulnerabilities. (ext) TOOLS: xsrfprobe""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_068648
2,308
no_license
[ { "docstring": "init", "name": "__init__", "signature": "def __init__(self, target, opts)" }, { "docstring": "DESCR: Crawl and check for CSRF vulnerabilities. (ext) TOOLS: xsrfprobe", "name": "xsrfprobe", "signature": "def xsrfprobe(self)" } ]
2
null
Implement the Python class `CSRF` described below. Class description: Cross-Site Request Forgery module Method signatures and docstrings: - def __init__(self, target, opts): init - def xsrfprobe(self): DESCR: Crawl and check for CSRF vulnerabilities. (ext) TOOLS: xsrfprobe
Implement the Python class `CSRF` described below. Class description: Cross-Site Request Forgery module Method signatures and docstrings: - def __init__(self, target, opts): init - def xsrfprobe(self): DESCR: Crawl and check for CSRF vulnerabilities. (ext) TOOLS: xsrfprobe <|skeleton|> class CSRF: """Cross-Site ...
ddc052c8d7d43a60fc00ea40d85111d5bd7a282e
<|skeleton|> class CSRF: """Cross-Site Request Forgery module""" def __init__(self, target, opts): """init""" <|body_0|> def xsrfprobe(self): """DESCR: Crawl and check for CSRF vulnerabilities. (ext) TOOLS: xsrfprobe""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CSRF: """Cross-Site Request Forgery module""" def __init__(self, target, opts): """init""" Base.__init__(self, target, opts) self.host, self.port, self.scheme, self.path = self._parse_url(self.target) return def xsrfprobe(self): """DESCR: Crawl and check for C...
the_stack_v2_python_sparse
src/modules/web/csrf.py
noptrix/nullscan
train
52
b67f224a3ea135397e9ebc22d3ad9b7bfd416452
[ "region = self.get_object()\nuser = self.request.user\nif user.is_staff:\n pass\nelif user.has_any_role() and user.club.region == region:\n pass\nelif user == region.dive_officer:\n pass\nelse:\n raise PermissionDenied\nqueryset = User.objects.filter(club__region=region, qualifications__certificate__is_...
<|body_start_0|> region = self.get_object() user = self.request.user if user.is_staff: pass elif user.has_any_role() and user.club.region == region: pass elif user == region.dive_officer: pass else: raise PermissionDenied ...
RegionViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegionViewSet: def active_instructors(self, request, pk=None): """Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in the region and the region's Dive Officer. Everyone else is forbidden.""" <|body_0|> def div...
stack_v2_sparse_classes_75kplus_train_068649
11,808
no_license
[ { "docstring": "Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in the region and the region's Dive Officer. Everyone else is forbidden.", "name": "active_instructors", "signature": "def active_instructors(self, request, pk=None)" }, ...
2
stack_v2_sparse_classes_30k_train_022264
Implement the Python class `RegionViewSet` described below. Class description: Implement the RegionViewSet class. Method signatures and docstrings: - def active_instructors(self, request, pk=None): Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in th...
Implement the Python class `RegionViewSet` described below. Class description: Implement the RegionViewSet class. Method signatures and docstrings: - def active_instructors(self, request, pk=None): Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in th...
8d5086ba5c42ee77c4e4b18d5880650075f575d5
<|skeleton|> class RegionViewSet: def active_instructors(self, request, pk=None): """Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in the region and the region's Dive Officer. Everyone else is forbidden.""" <|body_0|> def div...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegionViewSet: def active_instructors(self, request, pk=None): """Return a list of the active instructors in the region. Admins can see this list, as can committee members of clubs in the region and the region's Dive Officer. Everyone else is forbidden.""" region = self.get_object() us...
the_stack_v2_python_sparse
clubs/views.py
sdob/sincserver
train
0
340690eca399b78b2fd53dddee0513efb6028911
[ "self.wkt = wkt\nself.zmin = zmin\nself.zmax = zmax\nself.tmin = tmin\nself.tmax = tmax", "if isinstance(other, Tesseract):\n geom1, geom2 = (self.wkt, other.wkt2D())\n relation = geom1.relate(geom2)\n if self.tmin <= other.ll.t and self.tmax >= other.ur.t:\n if not intersects.matches(relation):\n...
<|body_start_0|> self.wkt = wkt self.zmin = zmin self.zmax = zmax self.tmin = tmin self.tmax = tmax <|end_body_0|> <|body_start_1|> if isinstance(other, Tesseract): geom1, geom2 = (self.wkt, other.wkt2D()) relation = geom1.relate(geom2) ...
Polygon4D
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Polygon4D: def __init__(self, wkt, zmin, zmax, tmin, tmax): """4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to construct a 4D Polygon.""" <|body_0|> def relationship(self, other): """Relationsh...
stack_v2_sparse_classes_75kplus_train_068650
23,035
permissive
[ { "docstring": "4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to construct a 4D Polygon.", "name": "__init__", "signature": "def __init__(self, wkt, zmin, zmax, tmin, tmax)" }, { "docstring": "Relationship of a 4D polygon a...
3
null
Implement the Python class `Polygon4D` described below. Class description: Implement the Polygon4D class. Method signatures and docstrings: - def __init__(self, wkt, zmin, zmax, tmin, tmax): 4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to const...
Implement the Python class `Polygon4D` described below. Class description: Implement the Polygon4D class. Method signatures and docstrings: - def __init__(self, wkt, zmin, zmax, tmin, tmax): 4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to const...
e7ef1d1ab2118e95cfda7e98a0e952c8d1c393d0
<|skeleton|> class Polygon4D: def __init__(self, wkt, zmin, zmax, tmin, tmax): """4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to construct a 4D Polygon.""" <|body_0|> def relationship(self, other): """Relationsh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Polygon4D: def __init__(self, wkt, zmin, zmax, tmin, tmax): """4D Polygon constructor. Takes the wkt in the xy plane, the minimum and maximum height and the minimum and maximum time to construct a 4D Polygon.""" self.wkt = wkt self.zmin = zmin self.zmax = zmax self.tmin...
the_stack_v2_python_sparse
pointcloud/structures/geometry.py
stpsomad/DynamicPCDMS
train
2
5ecaf81cc76c913c6e2c2b903892b418c195511b
[ "exists = False\nchecked_details = {}\nif not self.resource_in_tf_output(tf_outputs):\n for rule in get_rule_engine_cloudwatch_rules_var():\n rule_name = rule['ruleId']\n exists = cloudwatch_event.check_rule_exists(rule_name, input.aws_access_key, input.aws_secret_key, input.aws_region)\n if...
<|body_start_0|> exists = False checked_details = {} if not self.resource_in_tf_output(tf_outputs): for rule in get_rule_engine_cloudwatch_rules_var(): rule_name = rule['ruleId'] exists = cloudwatch_event.check_rule_exists(rule_name, input.aws_access_k...
RuleEngineEventRules
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RuleEngineEventRules: def check_exists_before(self, input, tf_outputs): """This method overrides the base class method, since here we need to check the existennce of a list of CW rules""" <|body_0|> def pre_terraform_destroy(self): """Remove all targets from the coud...
stack_v2_sparse_classes_75kplus_train_068651
4,854
permissive
[ { "docstring": "This method overrides the base class method, since here we need to check the existennce of a list of CW rules", "name": "check_exists_before", "signature": "def check_exists_before(self, input, tf_outputs)" }, { "docstring": "Remove all targets from the coudwatch rules before sta...
2
null
Implement the Python class `RuleEngineEventRules` described below. Class description: Implement the RuleEngineEventRules class. Method signatures and docstrings: - def check_exists_before(self, input, tf_outputs): This method overrides the base class method, since here we need to check the existennce of a list of CW ...
Implement the Python class `RuleEngineEventRules` described below. Class description: Implement the RuleEngineEventRules class. Method signatures and docstrings: - def check_exists_before(self, input, tf_outputs): This method overrides the base class method, since here we need to check the existennce of a list of CW ...
aa9afde5072ed19fe37a04ab25b5f87342b3f5ae
<|skeleton|> class RuleEngineEventRules: def check_exists_before(self, input, tf_outputs): """This method overrides the base class method, since here we need to check the existennce of a list of CW rules""" <|body_0|> def pre_terraform_destroy(self): """Remove all targets from the coud...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RuleEngineEventRules: def check_exists_before(self, input, tf_outputs): """This method overrides the base class method, since here we need to check the existennce of a list of CW rules""" exists = False checked_details = {} if not self.resource_in_tf_output(tf_outputs): ...
the_stack_v2_python_sparse
installer/resources/lambda_rule_engine/function.py
sajeer-nooh/pacbot
train
1
ec4e5c5999395d3c5f1cc232113ab435b89bb07a
[ "total = 0\npainters = 1\nfor length in array:\n total += length\n if total > max_length:\n painters += 1\n total = length\nreturn painters", "low = max(array)\nhigh = sum(array)\nwhile low < high:\n mid = (low + high) // 2\n painters = self.count_painters(array, mid)\n if painters <=...
<|body_start_0|> total = 0 painters = 1 for length in array: total += length if total > max_length: painters += 1 total = length return painters <|end_body_0|> <|body_start_1|> low = max(array) high = sum(array) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def count_painters(self, array, max_length): """Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna paint. Time complexity: O(n). Space complexity: O(1), n is len(array).""" <|body_0|> de...
stack_v2_sparse_classes_75kplus_train_068652
1,522
no_license
[ { "docstring": "Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna paint. Time complexity: O(n). Space complexity: O(1), n is len(array).", "name": "count_painters", "signature": "def count_painters(self, array, max_length)" ...
2
stack_v2_sparse_classes_30k_train_005390
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def count_painters(self, array, max_length): Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna pai...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def count_painters(self, array, max_length): Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna pai...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def count_painters(self, array, max_length): """Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna paint. Time complexity: O(n). Space complexity: O(1), n is len(array).""" <|body_0|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def count_painters(self, array, max_length): """Returns total number of painters, that we're gonna need if we use max_length as maximum boards' length that each painter is gonna paint. Time complexity: O(n). Space complexity: O(1), n is len(array).""" total = 0 painters = 1 ...
the_stack_v2_python_sparse
Binary_Search/painter_partition.py
vladn90/Algorithms
train
0
6063c377a12a2cbc341ea507f472dbccbe1a799e
[ "n = len(T)\nans = [0] * n\nfor i in range(n):\n a = 0\n for k in range(i + 1, n):\n if T[i] < T[k]:\n a += 1\n break\n elif T[i] >= T[k]:\n a += 1\n if k == n - 1:\n a = 0\n ans[i] = a\nreturn ans", "dic = dict()\nans = [0] * len(T...
<|body_start_0|> n = len(T) ans = [0] * n for i in range(n): a = 0 for k in range(i + 1, n): if T[i] < T[k]: a += 1 break elif T[i] >= T[k]: a += 1 if k == n - ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """:type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_2(self, T): """:type T: List[int] :rtype: List[int]""" <|body_1|> def dailyTemperatures(self, T): """:type T: List[int] :rtype...
stack_v2_sparse_classes_75kplus_train_068653
3,566
no_license
[ { "docstring": ":type T: List[int] :rtype: List[int]", "name": "dailyTemperatures_1", "signature": "def dailyTemperatures_1(self, T)" }, { "docstring": ":type T: List[int] :rtype: List[int]", "name": "dailyTemperatures_2", "signature": "def dailyTemperatures_2(self, T)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_017332
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures_2(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures(self, T): ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures_2(self, T): :type T: List[int] :rtype: List[int] - def dailyTemperatures(self, T): ...
3f7b2ea959308eb80f4c65be35aaeed666570f80
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """:type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_2(self, T): """:type T: List[int] :rtype: List[int]""" <|body_1|> def dailyTemperatures(self, T): """:type T: List[int] :rtype...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def dailyTemperatures_1(self, T): """:type T: List[int] :rtype: List[int]""" n = len(T) ans = [0] * n for i in range(n): a = 0 for k in range(i + 1, n): if T[i] < T[k]: a += 1 break ...
the_stack_v2_python_sparse
739.每日温度.py
dxc19951001/Everyday_LeetCode
train
1
07ed0fc34fc7b85fd614f1d21d66ac19544d3d58
[ "super().__init__(foundGeneIdString, swScore, bitScore, identity, overlap)\nif length <= 0:\n raise ValueError('Matched sequence can not be of length <= 0.')\nself.length = length\nself.foundGeneID = GeneID(foundGeneIdString)", "preMatch.__class__ = cls\nif length <= 0:\n raise ValueError('Matched sequence ...
<|body_start_0|> super().__init__(foundGeneIdString, swScore, bitScore, identity, overlap) if length <= 0: raise ValueError('Matched sequence can not be of length <= 0.') self.length = length self.foundGeneID = GeneID(foundGeneIdString) <|end_body_0|> <|body_start_1|> ...
Match
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Match: def __init__(self, foundGeneIdString, swScore, bitScore, identity, overlap, length): """A sequence comparison match between two distinct genes, including calculated attributes. During creation, `foundGeneIdString` is used to create a GeneID object, saved as `foundGeneID` Parameter...
stack_v2_sparse_classes_75kplus_train_068654
13,123
permissive
[ { "docstring": "A sequence comparison match between two distinct genes, including calculated attributes. During creation, `foundGeneIdString` is used to create a GeneID object, saved as `foundGeneID` Parameters __________ foundGeneIdString : str ID of the gene found by SSDB to be a paralog/ortholog, e.g. syn:sl...
2
stack_v2_sparse_classes_30k_train_048614
Implement the Python class `Match` described below. Class description: Implement the Match class. Method signatures and docstrings: - def __init__(self, foundGeneIdString, swScore, bitScore, identity, overlap, length): A sequence comparison match between two distinct genes, including calculated attributes. During cre...
Implement the Python class `Match` described below. Class description: Implement the Match class. Method signatures and docstrings: - def __init__(self, foundGeneIdString, swScore, bitScore, identity, overlap, length): A sequence comparison match between two distinct genes, including calculated attributes. During cre...
8a4a461295e0fa39c91d6c7f4520bac311448836
<|skeleton|> class Match: def __init__(self, foundGeneIdString, swScore, bitScore, identity, overlap, length): """A sequence comparison match between two distinct genes, including calculated attributes. During creation, `foundGeneIdString` is used to create a GeneID object, saved as `foundGeneID` Parameter...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Match: def __init__(self, foundGeneIdString, swScore, bitScore, identity, overlap, length): """A sequence comparison match between two distinct genes, including calculated attributes. During creation, `foundGeneIdString` is used to create a GeneID object, saved as `foundGeneID` Parameters __________ f...
the_stack_v2_python_sparse
FEV_KEGG/KEGG/SSDB.py
ryhaberecht/FEV-KEGG
train
2
0fec10dbe543db399a8f78a81dcec6ce15dc74af
[ "allowed_fields = super().filter_allowed_fields\nallowed_fields.remove('assignment_id')\nreturn allowed_fields", "assignment_id = self.request.matchdict.get('assignment_id')\nif assignment_id:\n query.filter(self.model.assignment_id == assignment_id)\nreturn query" ]
<|body_start_0|> allowed_fields = super().filter_allowed_fields allowed_fields.remove('assignment_id') return allowed_fields <|end_body_0|> <|body_start_1|> assignment_id = self.request.matchdict.get('assignment_id') if assignment_id: query.filter(self.model.assignme...
Assets service.
AssetService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" <|body_0|> def default_filters(self, query) -> object: """Default filters for this Service.""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_75kplus_train_068655
2,803
no_license
[ { "docstring": "List of fields allowed in filtering and sorting.", "name": "filter_allowed_fields", "signature": "def filter_allowed_fields(self)" }, { "docstring": "Default filters for this Service.", "name": "default_filters", "signature": "def default_filters(self, query) -> object" ...
2
stack_v2_sparse_classes_30k_train_051733
Implement the Python class `AssetService` described below. Class description: Assets service. Method signatures and docstrings: - def filter_allowed_fields(self): List of fields allowed in filtering and sorting. - def default_filters(self, query) -> object: Default filters for this Service.
Implement the Python class `AssetService` described below. Class description: Assets service. Method signatures and docstrings: - def filter_allowed_fields(self): List of fields allowed in filtering and sorting. - def default_filters(self, query) -> object: Default filters for this Service. <|skeleton|> class AssetS...
e85c0ba0992bccb80878e89ec791ee64754646b0
<|skeleton|> class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" <|body_0|> def default_filters(self, query) -> object: """Default filters for this Service.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AssetService: """Assets service.""" def filter_allowed_fields(self): """List of fields allowed in filtering and sorting.""" allowed_fields = super().filter_allowed_fields allowed_fields.remove('assignment_id') return allowed_fields def default_filters(self, query) -> ...
the_stack_v2_python_sparse
src/briefy/leica/views/assets.py
BriefyHQ/briefy.leica
train
0
e480da90e2589141200075e352377c0efb3f7411
[ "mpmap = {}\nfor manpage in files:\n normalized = _os.path.normpath(manpage)\n _, ext = _os.path.splitext(normalized)\n if ext.startswith(_os.path.extsep):\n ext = ext[len(_os.path.extsep):]\n mpmap.setdefault(ext, []).append(manpage)\nreturn [cls(manpages, prefix=_posixpath.join('share', 'man', ...
<|body_start_0|> mpmap = {} for manpage in files: normalized = _os.path.normpath(manpage) _, ext = _os.path.splitext(normalized) if ext.startswith(_os.path.extsep): ext = ext[len(_os.path.extsep):] mpmap.setdefault(ext, []).append(manpage) ...
Manpages container
Manpages
[ "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Manpages: """Manpages container""" def dispatch(cls, files): """Automatically dispatch manpages to their target directories""" <|body_0|> def flatten(self, installer): """Check if manpages are suitable""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_068656
5,080
permissive
[ { "docstring": "Automatically dispatch manpages to their target directories", "name": "dispatch", "signature": "def dispatch(cls, files)" }, { "docstring": "Check if manpages are suitable", "name": "flatten", "signature": "def flatten(self, installer)" } ]
2
stack_v2_sparse_classes_30k_train_039650
Implement the Python class `Manpages` described below. Class description: Manpages container Method signatures and docstrings: - def dispatch(cls, files): Automatically dispatch manpages to their target directories - def flatten(self, installer): Check if manpages are suitable
Implement the Python class `Manpages` described below. Class description: Manpages container Method signatures and docstrings: - def dispatch(cls, files): Automatically dispatch manpages to their target directories - def flatten(self, installer): Check if manpages are suitable <|skeleton|> class Manpages: """Man...
53102de187a48ac2cfc241fef54dcbc29c453a8e
<|skeleton|> class Manpages: """Manpages container""" def dispatch(cls, files): """Automatically dispatch manpages to their target directories""" <|body_0|> def flatten(self, installer): """Check if manpages are suitable""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Manpages: """Manpages container""" def dispatch(cls, files): """Automatically dispatch manpages to their target directories""" mpmap = {} for manpage in files: normalized = _os.path.normpath(manpage) _, ext = _os.path.splitext(normalized) if ext...
the_stack_v2_python_sparse
common/py_vulcanize/third_party/rjsmin/_setup/py2/data.py
catapult-project/catapult
train
2,032
26f3a3ca0a23ec146f2a09951431c242944ff4c1
[ "try:\n if input.get('range_type', None):\n structure_type = extract_value_from_input(input, 'range_type', 'Settings', settings_model)\nexcept ObjectDoesNotExist:\n raise GraphQLError(u'Problemi durante il recupero di una struttura.')\nranges = extract_value_from_input(input, 'range_id', 'Range', range...
<|body_start_0|> try: if input.get('range_type', None): structure_type = extract_value_from_input(input, 'range_type', 'Settings', settings_model) except ObjectDoesNotExist: raise GraphQLError(u'Problemi durante il recupero di una struttura.') ranges = ext...
RangeMutationService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RangeMutationService: def updateRange(self, input): """aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range""" <|body_0|> def createRange(self, input): """creazione di un nuovo range input: inp...
stack_v2_sparse_classes_75kplus_train_068657
4,054
no_license
[ { "docstring": "aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range", "name": "updateRange", "signature": "def updateRange(self, input)" }, { "docstring": "creazione di un nuovo range input: input: dict con i parametri pe...
2
stack_v2_sparse_classes_30k_train_049930
Implement the Python class `RangeMutationService` described below. Class description: Implement the RangeMutationService class. Method signatures and docstrings: - def updateRange(self, input): aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del ran...
Implement the Python class `RangeMutationService` described below. Class description: Implement the RangeMutationService class. Method signatures and docstrings: - def updateRange(self, input): aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del ran...
7929b244a40a2faf834f55f1803d131cc6324a49
<|skeleton|> class RangeMutationService: def updateRange(self, input): """aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range""" <|body_0|> def createRange(self, input): """creazione di un nuovo range input: inp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RangeMutationService: def updateRange(self, input): """aggiornamento di un range input: input: dict con i parametri per l'aggiornamento output: ranges: istanza del modello del range""" try: if input.get('range_type', None): structure_type = extract_value_from_input(...
the_stack_v2_python_sparse
legionella/graphqlapp/range/mutationservice.py
RedTurtle/legionella-backend
train
0
c3251b806748fcfb7e6226728cb807c5e4fd2585
[ "if not email:\n raise ValueError('O usuário deve ter um endereço de email.')\nemail = self.normalize_email(email)\nuser = self.model(email=email, name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email, name, password)\nuser.is_superuser = True\nuser.is...
<|body_start_0|> if not email: raise ValueError('O usuário deve ter um endereço de email.') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_s...
O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum.
UserProfileManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserProfileManager: """O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum.""" def create_user(self, email, name, p...
stack_v2_sparse_classes_75kplus_train_068658
5,017
no_license
[ { "docstring": "Cria um usuário comum.", "name": "create_user", "signature": "def create_user(self, email, name, password=None)" }, { "docstring": "Cria um super usuário.", "name": "create_superuser", "signature": "def create_superuser(self, email, name, password)" } ]
2
null
Implement the Python class `UserProfileManager` described below. Class description: O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum. Meth...
Implement the Python class `UserProfileManager` described below. Class description: O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum. Meth...
3a8009b17518384c269dfee3c8fe44cbe2567cc0
<|skeleton|> class UserProfileManager: """O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum.""" def create_user(self, email, name, p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserProfileManager: """O gerenciador de objetos é outra classe que podemos usar para ajudar a gerenciar os perfis de usuário que nos fornecerão algumas funcionalidades extras, como a criação de um usuário administrador ou a criação de um usuário comum.""" def create_user(self, email, name, password=None)...
the_stack_v2_python_sparse
project/accounts/models.py
VWApplications/VWAlmaAPI
train
1
70f254be9b0d993aa543cbde73781969475ffeb0
[ "pygame.sprite.Sprite.__init__(self)\nself.image = pygame.Surface([70, 50])\nself.image.fill((255, 255, 255))\nself.rect = self.image.get_rect()\nself.rect.y = 40\nself.set_pos(pos)", "if pos == 1:\n self.rect.x = 67\nelif pos == 2:\n self.rect.x = 230\nelif pos == 3:\n self.rect.x = 390\nelif pos == 4:\...
<|body_start_0|> pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([70, 50]) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() self.rect.y = 40 self.set_pos(pos) <|end_body_0|> <|body_start_1|> if pos == 1: self.rect.x =...
Pygame sprite class for frog nests used for checking the win condition.
FrogNest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrogNest: """Pygame sprite class for frog nests used for checking the win condition.""" def __init__(self, pos): """- :param pos: An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.""" <|bo...
stack_v2_sparse_classes_75kplus_train_068659
2,291
permissive
[ { "docstring": "- :param pos: An int representing the \"index\" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.", "name": "__init__", "signature": "def __init__(self, pos)" }, { "docstring": "Helper method called by the constructor. Take...
3
stack_v2_sparse_classes_30k_train_033247
Implement the Python class `FrogNest` described below. Class description: Pygame sprite class for frog nests used for checking the win condition. Method signatures and docstrings: - def __init__(self, pos): - :param pos: An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nes...
Implement the Python class `FrogNest` described below. Class description: Pygame sprite class for frog nests used for checking the win condition. Method signatures and docstrings: - def __init__(self, pos): - :param pos: An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nes...
d8c6bad99ccaf10d3cca05b6fc44799e2f46ad2a
<|skeleton|> class FrogNest: """Pygame sprite class for frog nests used for checking the win condition.""" def __init__(self, pos): """- :param pos: An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FrogNest: """Pygame sprite class for frog nests used for checking the win condition.""" def __init__(self, pos): """- :param pos: An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.""" pygame.sprite.Spr...
the_stack_v2_python_sparse
src/Sprites/frog_nest.py
johnpcooke94/project-scrumger-games
train
0
0b49a51a1bee848ef572123595b2d0ed96215e60
[ "self._ns_name = ns_name\nself._vs_name = vs_name\ndevice = '/gpu:{}'.format(device) if device >= 0 else '/cpu:0'\nself._device = device", "assert input.setup_done()\nlogger.info(\"Building predictor tower '{}' on device {} ...\".format(self._ns_name, self._device))\nwith tf.device(self._device), PredictTowerCont...
<|body_start_0|> self._ns_name = ns_name self._vs_name = vs_name device = '/gpu:{}'.format(device) if device >= 0 else '/cpu:0' self._device = device <|end_body_0|> <|body_start_1|> assert input.setup_done() logger.info("Building predictor tower '{}' on device {} ...".fo...
Single-tower predictor.
SimplePredictBuilder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimplePredictBuilder: """Single-tower predictor.""" def __init__(self, ns_name='', vs_name='', device=0): """Args: ns_name (str): vs_name (str): device (int):""" <|body_0|> def build(self, input, tower_fn): """Args: input (InputSource): must have been setup tower...
stack_v2_sparse_classes_75kplus_train_068660
1,612
permissive
[ { "docstring": "Args: ns_name (str): vs_name (str): device (int):", "name": "__init__", "signature": "def __init__(self, ns_name='', vs_name='', device=0)" }, { "docstring": "Args: input (InputSource): must have been setup tower_fn ( [tf.Tensors] ->): callable that takes input tensors. Returns: ...
2
stack_v2_sparse_classes_30k_train_000702
Implement the Python class `SimplePredictBuilder` described below. Class description: Single-tower predictor. Method signatures and docstrings: - def __init__(self, ns_name='', vs_name='', device=0): Args: ns_name (str): vs_name (str): device (int): - def build(self, input, tower_fn): Args: input (InputSource): must ...
Implement the Python class `SimplePredictBuilder` described below. Class description: Single-tower predictor. Method signatures and docstrings: - def __init__(self, ns_name='', vs_name='', device=0): Args: ns_name (str): vs_name (str): device (int): - def build(self, input, tower_fn): Args: input (InputSource): must ...
a98bb06401c5c76f98ad77349218fe3f0fe17076
<|skeleton|> class SimplePredictBuilder: """Single-tower predictor.""" def __init__(self, ns_name='', vs_name='', device=0): """Args: ns_name (str): vs_name (str): device (int):""" <|body_0|> def build(self, input, tower_fn): """Args: input (InputSource): must have been setup tower...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimplePredictBuilder: """Single-tower predictor.""" def __init__(self, ns_name='', vs_name='', device=0): """Args: ns_name (str): vs_name (str): device (int):""" self._ns_name = ns_name self._vs_name = vs_name device = '/gpu:{}'.format(device) if device >= 0 else '/cpu:0' ...
the_stack_v2_python_sparse
tensorpack/graph_builder/predict.py
armandmcqueen/tensorpack-mask-rcnn
train
19
ca144ea3d06df05082c01841d48a07afe0b6a60b
[ "ref = self._ref\nif ref:\n return ref\nref = SLC(slc=self.flow.reference)\nself._ref = ref\nreturn ref", "sec = self._sec\nif sec:\n return sec\nsec = SLC(slc=self.flow.secondary)\nself._sec = sec\nreturn sec", "match = self.slcRegex.match(request.url)\nif match is None:\n channel = plexus.firewall\n ...
<|body_start_0|> ref = self._ref if ref: return ref ref = SLC(slc=self.flow.reference) self._ref = ref return ref <|end_body_0|> <|body_start_1|> sec = self._sec if sec: return sec sec = SLC(slc=self.flow.secondary) self._s...
Select application behavior that is mapped to the capabilities of the web client
Panel
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Panel: """Select application behavior that is mapped to the capabilities of the web client""" def ref(self): """Access to the raw reference SLC input data product""" <|body_0|> def sec(self): """Access to the raw secondary SLC input data product""" <|body...
stack_v2_sparse_classes_75kplus_train_068661
5,072
permissive
[ { "docstring": "Access to the raw reference SLC input data product", "name": "ref", "signature": "def ref(self)" }, { "docstring": "Access to the raw secondary SLC input data product", "name": "sec", "signature": "def sec(self)" }, { "docstring": "Render a tile from one of the in...
3
null
Implement the Python class `Panel` described below. Class description: Select application behavior that is mapped to the capabilities of the web client Method signatures and docstrings: - def ref(self): Access to the raw reference SLC input data product - def sec(self): Access to the raw secondary SLC input data prod...
Implement the Python class `Panel` described below. Class description: Select application behavior that is mapped to the capabilities of the web client Method signatures and docstrings: - def ref(self): Access to the raw reference SLC input data product - def sec(self): Access to the raw secondary SLC input data prod...
95c1e29f57b7a6eb29c61e2983c384a6eabf2e8b
<|skeleton|> class Panel: """Select application behavior that is mapped to the capabilities of the web client""" def ref(self): """Access to the raw reference SLC input data product""" <|body_0|> def sec(self): """Access to the raw secondary SLC input data product""" <|body...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Panel: """Select application behavior that is mapped to the capabilities of the web client""" def ref(self): """Access to the raw reference SLC input data product""" ref = self._ref if ref: return ref ref = SLC(slc=self.flow.reference) self._ref = ref ...
the_stack_v2_python_sparse
pkg/ampcor/ux/Panel.py
aivazis/ampcor
train
3
650e979cfbab39b3967d92e537f44eba7ae54420
[ "try:\n platform = self.get_argument('platform', 'iOS')\n username = self.get_argument('username')\nexcept Exception as e:\n logging.error(e)\n raise utils.APIError(errcode=100)\nuser = ctrl.web.get_user_info_ctl(username)\nif user:\n return self.send_json(user)\ndt_7days_after = datetime.datetime.no...
<|body_start_0|> try: platform = self.get_argument('platform', 'iOS') username = self.get_argument('username') except Exception as e: logging.error(e) raise utils.APIError(errcode=100) user = ctrl.web.get_user_info_ctl(username) if user: ...
UserHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserHandler: def post(self): """进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息""" <|body_0|> def get(self): """获取用户信息: email, timelimit, password, sim_online""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: platform = self.get_argumen...
stack_v2_sparse_classes_75kplus_train_068662
3,027
no_license
[ { "docstring": "进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息", "name": "post", "signature": "def post(self)" }, { "docstring": "获取用户信息: email, timelimit, password, sim_online", "name": "get", "signature": "def get(self)" } ]
2
stack_v2_sparse_classes_30k_train_046439
Implement the Python class `UserHandler` described below. Class description: Implement the UserHandler class. Method signatures and docstrings: - def post(self): 进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息 - def get(self): 获取用户信息: email, timelimit, password, sim_online
Implement the Python class `UserHandler` described below. Class description: Implement the UserHandler class. Method signatures and docstrings: - def post(self): 进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息 - def get(self): 获取用户信息: email, timelimit, password, sim_online <|skeleton|> class UserHandler: def post...
7fd1b320a0ed33fbe428599b432bb4d0bfeb12f4
<|skeleton|> class UserHandler: def post(self): """进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息""" <|body_0|> def get(self): """获取用户信息: email, timelimit, password, sim_online""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserHandler: def post(self): """进入app后就会掉的接口, username是设备相关的,如果没有账号则创建,返回账号信息""" try: platform = self.get_argument('platform', 'iOS') username = self.get_argument('username') except Exception as e: logging.error(e) raise utils.APIError(er...
the_stack_v2_python_sparse
apiv2/handler/user.py
onlywsx/FreeVPN
train
0
7c5c917eb18507f9d727c3832300a09dca5c7e47
[ "if root is None:\n return 'n'\nret = str(root.val)\nret += ',' + self.serialize(root.left)\nret += ',' + self.serialize(root.right)\nreturn ret", "if data == 'n':\n return None\nnode_values = data.split(',')\nroot = TreeNode(int(node_values[0]))\nstack = []\nstack.append(root)\nfor value in node_values[1:]...
<|body_start_0|> if root is None: return 'n' ret = str(root.val) ret += ',' + self.serialize(root.left) ret += ',' + self.serialize(root.right) return ret <|end_body_0|> <|body_start_1|> if data == 'n': return None node_values = data.split...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_068663
1,539
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:...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if root is None: return 'n' ret = str(root.val) ret += ',' + self.serialize(root.left) ret += ',' + self.serialize(root.right) return ret ...
the_stack_v2_python_sparse
python/leetcode/297_Serialize_and_Deserialize_Binary_Tree.py
bobcaoge/my-code
train
0
3dbf0ac49449127672d21b514c773321ffae9278
[ "self.host = host\nself.port = port\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nself.sock.bind((self.host, self.port))\nself.messagesList = []\nself.connected = []", "self.sock.listen(5)\nwhile True:\n client, address = self.s...
<|body_start_0|> self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) self.messagesList = [] self.connected = [] <|end...
ChatServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChatServer: def __init__(self, host, port): """Initialization for the server""" <|body_0|> def listen(self): """Loop for accepting clients""" <|body_1|> def listenToClient(self, client, address): """Client thread method""" <|body_2|> ...
stack_v2_sparse_classes_75kplus_train_068664
2,925
no_license
[ { "docstring": "Initialization for the server", "name": "__init__", "signature": "def __init__(self, host, port)" }, { "docstring": "Loop for accepting clients", "name": "listen", "signature": "def listen(self)" }, { "docstring": "Client thread method", "name": "listenToClien...
4
stack_v2_sparse_classes_30k_train_030781
Implement the Python class `ChatServer` described below. Class description: Implement the ChatServer class. Method signatures and docstrings: - def __init__(self, host, port): Initialization for the server - def listen(self): Loop for accepting clients - def listenToClient(self, client, address): Client thread method...
Implement the Python class `ChatServer` described below. Class description: Implement the ChatServer class. Method signatures and docstrings: - def __init__(self, host, port): Initialization for the server - def listen(self): Loop for accepting clients - def listenToClient(self, client, address): Client thread method...
0249a73062f6bef9e40d0ab792f9cf30eaa363ed
<|skeleton|> class ChatServer: def __init__(self, host, port): """Initialization for the server""" <|body_0|> def listen(self): """Loop for accepting clients""" <|body_1|> def listenToClient(self, client, address): """Client thread method""" <|body_2|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChatServer: def __init__(self, host, port): """Initialization for the server""" self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.h...
the_stack_v2_python_sparse
Bimester2/Class10/ChatServer.py
aloysiogl/CES-22_solutions
train
0
ea58319a669a2ef9fe34ede7ee8175ceffb6c6f7
[ "super(DeepAndCrossNetworkModel, self).__init__()\nself.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation)\nself.cross = CrossNetworkLayer(inputs_size=inputs_size, num_layers=cross_num_layers)\ncat_size = deep_ou...
<|body_start_0|> super(DeepAndCrossNetworkModel, self).__init__() self.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation) self.cross = CrossNetworkLayer(inputs_size=inputs_size, num_layers=cro...
Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_.
DeepAndCrossNetworkModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepAndCrossNetworkModel: """Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_.""" def __i...
stack_v2_sparse_classes_75kplus_train_068665
4,225
permissive
[ { "docstring": "Initialize DeepAndCrossNetworkModel Args: inputs_size (int): Inputs size of dense network and cross network, i.e. number of fields * embedding size. deep_output_size (int): Output size of dense network deep_layer_sizes (List[int]): Layer sizes of dense network cross_num_layers (int): Number of l...
2
stack_v2_sparse_classes_30k_train_043628
Implement the Python class `DeepAndCrossNetworkModel` described below. Class description: Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv...
Implement the Python class `DeepAndCrossNetworkModel` described below. Class description: Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv...
07a6a38c7eb44225f2b22f332081f697c3b92894
<|skeleton|> class DeepAndCrossNetworkModel: """Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_.""" def __i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeepAndCrossNetworkModel: """Model class of Deep & Cross Network (DCN), which is a concatenation of dense network (deep part) and cross network (cross part). :Reference: #. `Ruoxi Wang et al, 2017. Deep & Cross Network for Ad Click Predictions <https://arxiv.org/abs/1708.05123>`_.""" def __init__(self, i...
the_stack_v2_python_sparse
torecsys/models/ctr/deep_and_cross_network.py
zwcdp/torecsys
train
0
8af8dd684f38a5f1f5b9507f4f1d93b0c8c20210
[ "self.logger = logging.getLogger('PynealLog')\nself.settings = settings\nmask_img = nib.load(settings['maskFile'])\nif settings['maskIsWeighted'] is True:\n self.weightMask = True\n self.weights = mask_img.get_fdata().copy()\n self.mask = mask_img.get_fdata() > 0\nelse:\n self.weightMask = False\n se...
<|body_start_0|> self.logger = logging.getLogger('PynealLog') self.settings = settings mask_img = nib.load(settings['maskFile']) if settings['maskIsWeighted'] is True: self.weightMask = True self.weights = mask_img.get_fdata().copy() self.mask = mask_i...
Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the settings dictionary that gets passed in.
Analyzer
[ "MIT", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Analyzer: """Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the settings dictionary that gets passed in....
stack_v2_sparse_classes_75kplus_train_068666
6,539
permissive
[ { "docstring": "Initialize the class Parameters ---------- settings : dict dictionary that contains all of the pyneal settings for the current session. This dictionary is loaded/configured by the GUI once Pyneal is first launched", "name": "__init__", "signature": "def __init__(self, settings)" }, {...
4
stack_v2_sparse_classes_30k_train_006830
Implement the Python class `Analyzer` described below. Class description: Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the s...
Implement the Python class `Analyzer` described below. Class description: Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the s...
750f0ec5a231ccfa77aea960242de9b5019ba493
<|skeleton|> class Analyzer: """Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the settings dictionary that gets passed in....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Analyzer: """Analysis Class This is the main Analysis module that gets instantiated by Pyneal, and will handle executing the specific analyses throughout the scan. The specific analysis functions that get used will be based on the analyses specified in the settings dictionary that gets passed in.""" def ...
the_stack_v2_python_sparse
src/pynealAnalysis.py
jeffmacinnes/pyneal
train
36
1d5487b004da1dbbe0aebfca5f6155e8f3ed6fe7
[ "self.wsi_iter = None\nself.wsi_list = os.listdir(LSTMDataConfig.RESULT_PATH)\nfor i in range(len(self.wsi_list)):\n print(self.wsi_list[i])\n self.wsi_iter = i\n LSTMDataConfig.MASK_PATH = LSTMDataConfig.WSI_FOLDER_PATH + os.sep + 'Tumor' + os.sep + 'Mask_Tumor' + os.sep + self.wsi_list[self.wsi_iter] + '...
<|body_start_0|> self.wsi_iter = None self.wsi_list = os.listdir(LSTMDataConfig.RESULT_PATH) for i in range(len(self.wsi_list)): print(self.wsi_list[i]) self.wsi_iter = i LSTMDataConfig.MASK_PATH = LSTMDataConfig.WSI_FOLDER_PATH + os.sep + 'Tumor' + os.sep + '...
Saves labels for selected patches in a separate directory
TestLSTMLabelSave
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLSTMLabelSave: """Saves labels for selected patches in a separate directory""" def test(self): """Start saving labels for a list of WSIs""" <|body_0|> def test_once(self): """Saves labels for a particular WSI""" <|body_1|> def stop_call(self): ...
stack_v2_sparse_classes_75kplus_train_068667
7,352
no_license
[ { "docstring": "Start saving labels for a list of WSIs", "name": "test", "signature": "def test(self)" }, { "docstring": "Saves labels for a particular WSI", "name": "test_once", "signature": "def test_once(self)" }, { "docstring": "Stop label saving process and exit", "name"...
3
stack_v2_sparse_classes_30k_train_007700
Implement the Python class `TestLSTMLabelSave` described below. Class description: Saves labels for selected patches in a separate directory Method signatures and docstrings: - def test(self): Start saving labels for a list of WSIs - def test_once(self): Saves labels for a particular WSI - def stop_call(self): Stop l...
Implement the Python class `TestLSTMLabelSave` described below. Class description: Saves labels for selected patches in a separate directory Method signatures and docstrings: - def test(self): Start saving labels for a list of WSIs - def test_once(self): Saves labels for a particular WSI - def stop_call(self): Stop l...
13ca09855ae18288a8da215e422e42cb74a2c181
<|skeleton|> class TestLSTMLabelSave: """Saves labels for selected patches in a separate directory""" def test(self): """Start saving labels for a list of WSIs""" <|body_0|> def test_once(self): """Saves labels for a particular WSI""" <|body_1|> def stop_call(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestLSTMLabelSave: """Saves labels for selected patches in a separate directory""" def test(self): """Start saving labels for a list of WSIs""" self.wsi_iter = None self.wsi_list = os.listdir(LSTMDataConfig.RESULT_PATH) for i in range(len(self.wsi_list)): print...
the_stack_v2_python_sparse
dl_interface/lstm_data_generation.py
abhinavagarwalla/Tissue_GUI
train
1
1ea05c60d2612c9f7023a9f82d52e17347e0bf2c
[ "from enthought.tvtk.pipeline.browser import PipelineBrowser\nself.browser = PipelineBrowser()\nself.browser.show(parent=parent)\nreturn self.browser.ui.control", "map(self._remove_scene, event.removed)\nmap(self._add_scene, event.added)\nreturn", "self.browser.renwins.append(scene)\nself.browser.root_object.ap...
<|body_start_0|> from enthought.tvtk.pipeline.browser import PipelineBrowser self.browser = PipelineBrowser() self.browser.show(parent=parent) return self.browser.ui.control <|end_body_0|> <|body_start_1|> map(self._remove_scene, event.removed) map(self._add_scene, event...
The TVTK pipeline browser view.
BrowserView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BrowserView: """The TVTK pipeline browser view.""" def create_control(self, parent): """Create the toolkit-specific control that represents the view.""" <|body_0|> def _on_scenes_changed(self, event): """Dynamic trait change handler. This is called when scenes ar...
stack_v2_sparse_classes_75kplus_train_068668
3,017
no_license
[ { "docstring": "Create the toolkit-specific control that represents the view.", "name": "create_control", "signature": "def create_control(self, parent)" }, { "docstring": "Dynamic trait change handler. This is called when scenes are added/removed from the scene manager, it is used to add and re...
4
stack_v2_sparse_classes_30k_train_012488
Implement the Python class `BrowserView` described below. Class description: The TVTK pipeline browser view. Method signatures and docstrings: - def create_control(self, parent): Create the toolkit-specific control that represents the view. - def _on_scenes_changed(self, event): Dynamic trait change handler. This is ...
Implement the Python class `BrowserView` described below. Class description: The TVTK pipeline browser view. Method signatures and docstrings: - def create_control(self, parent): Create the toolkit-specific control that represents the view. - def _on_scenes_changed(self, event): Dynamic trait change handler. This is ...
5466f5858dbd2f1f082fa0d7417b57c8fb068fad
<|skeleton|> class BrowserView: """The TVTK pipeline browser view.""" def create_control(self, parent): """Create the toolkit-specific control that represents the view.""" <|body_0|> def _on_scenes_changed(self, event): """Dynamic trait change handler. This is called when scenes ar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BrowserView: """The TVTK pipeline browser view.""" def create_control(self, parent): """Create the toolkit-specific control that represents the view.""" from enthought.tvtk.pipeline.browser import PipelineBrowser self.browser = PipelineBrowser() self.browser.show(parent=pa...
the_stack_v2_python_sparse
maps/build/mayavi/enthought/tvtk/plugins/browser/browser_view.py
m-elhussieny/code
train
0
5e23c50159cb217655453245f7a577fa35986f91
[ "super().__init__()\npatch_norm = 'gn' if in_channels >= 32 else None\nself.patch_embed = ContiguousEmbed(in_channels=in_channels, patch_size=1, head_dim=head_dim, num_heads=num_heads, normalization=patch_norm, norm_kwargs={'num_features': in_channels, 'num_groups': num_groups}, **patch_embed_kwargs if patch_embed_...
<|body_start_0|> super().__init__() patch_norm = 'gn' if in_channels >= 32 else None self.patch_embed = ContiguousEmbed(in_channels=in_channels, patch_size=1, head_dim=head_dim, num_heads=num_heads, normalization=patch_norm, norm_kwargs={'num_features': in_channels, 'num_groups': num_groups}, **...
Transformer2D
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transformer2D: def __init__(self, in_channels: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ...]=(0.0, 0.0), biases: Tuple[bo...
stack_v2_sparse_classes_75kplus_train_068669
12,584
permissive
[ { "docstring": "Create a transformer for 2D-image-like (B, C, H, W) inputs. NOTE: The output shape is the same size as the input shape. Parameters ---------- in_channels : int Number of channels in the 2D-input of shape (B, in_channels, H, W). num_heads : int, default=8 Number of heads in multi-head attention. ...
2
stack_v2_sparse_classes_30k_train_009575
Implement the Python class `Transformer2D` described below. Class description: Implement the Transformer2D class. Method signatures and docstrings: - def __init__(self, in_channels: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact')...
Implement the Python class `Transformer2D` described below. Class description: Implement the Transformer2D class. Method signatures and docstrings: - def __init__(self, in_channels: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact')...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class Transformer2D: def __init__(self, in_channels: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ...]=(0.0, 0.0), biases: Tuple[bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Transformer2D: def __init__(self, in_channels: int, num_heads: int=8, head_dim: int=64, cross_attention_dim: int=None, n_blocks: int=2, block_types: Tuple[str, ...]=('exact', 'exact'), computation_types: Tuple[str, ...]=('basic', 'basic'), dropouts: Tuple[float, ...]=(0.0, 0.0), biases: Tuple[bool, ...]=(Fals...
the_stack_v2_python_sparse
cellseg_models_pytorch/modules/transformers.py
okunator/cellseg_models.pytorch
train
43
a45bd42e3b29a6af758443782d1d7d411982823b
[ "super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(...
<|body_start_0|> super(EncoderBlock, self).__init__() self.mha = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu') self.dense_output = tf.keras.layers.Dense(dm) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06) ...
[summary] Args: tf ([type]): [description]
EncoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderBlock: """[summary] Args: tf ([type]): [description]""" def __init__(self, dm, h, hidden, drop_rate=0.1): """[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.""" ...
stack_v2_sparse_classes_75kplus_train_068670
12,086
no_license
[ { "docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.", "name": "__init__", "signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)" }, { "docstring": "[summary] Args...
2
stack_v2_sparse_classes_30k_train_033584
Implement the Python class `EncoderBlock` described below. Class description: [summary] Args: tf ([type]): [description] Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (...
Implement the Python class `EncoderBlock` described below. Class description: [summary] Args: tf ([type]): [description] Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (...
5f86dee95f4d1c32014d0d74a368f342ff3ce6f7
<|skeleton|> class EncoderBlock: """[summary] Args: tf ([type]): [description]""" def __init__(self, dm, h, hidden, drop_rate=0.1): """[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EncoderBlock: """[summary] Args: tf ([type]): [description]""" def __init__(self, dm, h, hidden, drop_rate=0.1): """[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.""" super(Enc...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
d1sd41n/holbertonschool-machine_learning
train
0
e55aafdf52b7b9982b0f5674e70b860239166da0
[ "self.max_batch_size = max_batch_size\nself.device = device\nself.distribution_cls = Categorical if distribution_cls is None else distribution_cls", "num_samples, max_seq_length = actions.size()\nnumber_batches = (num_samples + self.max_batch_size - 1) // self.max_batch_size\nremaining_samples = num_samples\nlog_...
<|body_start_0|> self.max_batch_size = max_batch_size self.device = device self.distribution_cls = Categorical if distribution_cls is None else distribution_cls <|end_body_0|> <|body_start_1|> num_samples, max_seq_length = actions.size() number_batches = (num_samples + self.max_...
Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.
ActionReplay
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActionReplay: """Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.""" def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None: """Args: max_batch_size: Max...
stack_v2_sparse_classes_75kplus_train_068671
5,211
permissive
[ { "docstring": "Args: max_batch_size: Max. batch size device: cuda | cpu distribution_cls: distribution type to sample from. If None, will be a multinomial distribution.", "name": "__init__", "signature": "def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None" }...
3
stack_v2_sparse_classes_30k_val_000717
Implement the Python class `ActionReplay` described below. Class description: Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy. Method signatures and docstrings: - def __init__(self, max_batch_size, device, distribution_cls: Ty...
Implement the Python class `ActionReplay` described below. Class description: Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy. Method signatures and docstrings: - def __init__(self, max_batch_size, device, distribution_cls: Ty...
44d24c53f3acf9266eb2fb06dbff909836549291
<|skeleton|> class ActionReplay: """Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.""" def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None: """Args: max_batch_size: Max...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ActionReplay: """Action replay for policy-based RL algorithms. Given some actions sampled from a RNN model, will calculate the log probabilities and entropy.""" def __init__(self, max_batch_size, device, distribution_cls: Type[Distribution]=None) -> None: """Args: max_batch_size: Max. batch size ...
the_stack_v2_python_sparse
smiles_lstm_ppo/action_replay.py
BenevolentAI/guacamol_baselines
train
108
10a99c45ff439865eda09df35df7b5fef493f86a
[ "if not isinstance(samples_info_sets, pd.Series):\n raise ValueError('The samples_info_sets param must be a pd.Series.')\nsuper().__init__(n_splits, shuffle=False, random_state=None)\nself.samples_info_sets = samples_info_sets\nself.pct_embargo = pct_embargo", "if X.shape[0] != self.samples_info_sets.shape[0]:...
<|body_start_0|> if not isinstance(samples_info_sets, pd.Series): raise ValueError('The samples_info_sets param must be a pd.Series.') super().__init__(n_splits, shuffle=False, random_state=None) self.samples_info_sets = samples_info_sets self.pct_embargo = pct_embargo <|end_...
Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.
PurgedKFold
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Seri...
stack_v2_sparse_classes_75kplus_train_068672
19,555
permissive
[ { "docstring": "Initialize. :param n_splits: (int) The number of splits. Default to 3 :param samples_info_sets: (pd.Series) The information range on which each record is constructed from *samples_info_sets.index*: Time when the information extraction started. *samples_info_sets.value*: Time when the information...
2
stack_v2_sparse_classes_30k_train_050265
Implement the Python class `PurgedKFold` described below. Class description: Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between. Method signatures and docstrin...
Implement the Python class `PurgedKFold` described below. Class description: Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between. Method signatures and docstrin...
046c47d995da08b1003bba3f9c07d5bfb73d9c1f
<|skeleton|> class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Seri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PurgedKFold: """Extend KFold class to work with labels that span intervals. The train is purged of observations overlapping test-label intervals. Test set is assumed contiguous (shuffle=False), w/o training samples in between.""" def __init__(self, n_splits: int=3, samples_info_sets: pd.Series=None, pct_...
the_stack_v2_python_sparse
src/collection/mlfinlab/cross_validation/cross_validation.py
Ta-nu-ki/dissertacao
train
0
924777cf8997a822e805f5615368868aa5185096
[ "if not self.port.attr['options'] or env.flags['config'] == 'none':\n return True\nelif env.flags['config'] == 'all':\n return False\noptionfile = env.flags['chroot'] + self.port.attr['optionsfile']\npkgname = self.port.attr['pkgname']\nconfig_pkgname = ''\noptions = set()\nif os.path.isfile(optionfile):\n ...
<|body_start_0|> if not self.port.attr['options'] or env.flags['config'] == 'none': return True elif env.flags['config'] == 'all': return False optionfile = env.flags['chroot'] + self.port.attr['optionsfile'] pkgname = self.port.attr['pkgname'] config_pkgn...
Configure a port.
Config
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Configure a port.""" def complete(self): """Check the options file to see if it is up-to-date.""" <|body_0|> def _pre_make(self): """Issue a make.target() to configure the port.""" <|body_1|> def _post_make(self, status): """Refetc...
stack_v2_sparse_classes_75kplus_train_068673
5,139
permissive
[ { "docstring": "Check the options file to see if it is up-to-date.", "name": "complete", "signature": "def complete(self)" }, { "docstring": "Issue a make.target() to configure the port.", "name": "_pre_make", "signature": "def _pre_make(self)" }, { "docstring": "Refetch attr dat...
4
stack_v2_sparse_classes_30k_train_027815
Implement the Python class `Config` described below. Class description: Configure a port. Method signatures and docstrings: - def complete(self): Check the options file to see if it is up-to-date. - def _pre_make(self): Issue a make.target() to configure the port. - def _post_make(self, status): Refetch attr data if ...
Implement the Python class `Config` described below. Class description: Configure a port. Method signatures and docstrings: - def complete(self): Check the options file to see if it is up-to-date. - def _pre_make(self): Issue a make.target() to configure the port. - def _post_make(self, status): Refetch attr data if ...
1d0041382dc68738018401cdda2e69836a534e1d
<|skeleton|> class Config: """Configure a port.""" def complete(self): """Check the options file to see if it is up-to-date.""" <|body_0|> def _pre_make(self): """Issue a make.target() to configure the port.""" <|body_1|> def _post_make(self, status): """Refetc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Config: """Configure a port.""" def complete(self): """Check the options file to see if it is up-to-date.""" if not self.port.attr['options'] or env.flags['config'] == 'none': return True elif env.flags['config'] == 'all': return False optionfile = ...
the_stack_v2_python_sparse
libpb/stacks/common.py
DragonSA/portbuilder
train
10
3466ab049432e59f75c1c160b957b7d03b8e3ffd
[ "if isinstance(s, str) and re.match('^([0-9a-f]){24}$', s):\n return True\nreturn False", "if cls.is_valid(s):\n return datetime.fromtimestamp(int(s[:8], 16))\nreturn False" ]
<|body_start_0|> if isinstance(s, str) and re.match('^([0-9a-f]){24}$', s): return True return False <|end_body_0|> <|body_start_1|> if cls.is_valid(s): return datetime.fromtimestamp(int(s[:8], 16)) return False <|end_body_1|>
Mongo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mongo: def is_valid(cls, s): """returns True if s is a valid MongoID; otherwise False""" <|body_0|> def get_timestamp(cls, s): """if s is a MongoID, returns a datetime object for the timestamp; otherwise False""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_75kplus_train_068674
1,205
no_license
[ { "docstring": "returns True if s is a valid MongoID; otherwise False", "name": "is_valid", "signature": "def is_valid(cls, s)" }, { "docstring": "if s is a MongoID, returns a datetime object for the timestamp; otherwise False", "name": "get_timestamp", "signature": "def get_timestamp(cl...
2
null
Implement the Python class `Mongo` described below. Class description: Implement the Mongo class. Method signatures and docstrings: - def is_valid(cls, s): returns True if s is a valid MongoID; otherwise False - def get_timestamp(cls, s): if s is a MongoID, returns a datetime object for the timestamp; otherwise False
Implement the Python class `Mongo` described below. Class description: Implement the Mongo class. Method signatures and docstrings: - def is_valid(cls, s): returns True if s is a valid MongoID; otherwise False - def get_timestamp(cls, s): if s is a MongoID, returns a datetime object for the timestamp; otherwise False...
216957fe84ba76cab2eb603234ece08c97b9ac1f
<|skeleton|> class Mongo: def is_valid(cls, s): """returns True if s is a valid MongoID; otherwise False""" <|body_0|> def get_timestamp(cls, s): """if s is a MongoID, returns a datetime object for the timestamp; otherwise False""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Mongo: def is_valid(cls, s): """returns True if s is a valid MongoID; otherwise False""" if isinstance(s, str) and re.match('^([0-9a-f]){24}$', s): return True return False def get_timestamp(cls, s): """if s is a MongoID, returns a datetime object for the times...
the_stack_v2_python_sparse
challenges_5kyu/mongodb_objectid.py
tvrt0001/CodeWars-Python
train
0
2b896966bd93afb60e6662b5400c54aa3edef7ff
[ "full_layer_specs = []\nfor i, layer_spec in enumerate(layer_specs):\n full_layer_spec = [3, layer_spec[0], layer_spec[1], 1]\n full_layer_specs.append(full_layer_spec)\nsuper().__init__(name=name, layer_specs=full_layer_specs, activation_fn=activation_fn, last_activation_fn=None, regularizer=regularizer, pad...
<|body_start_0|> full_layer_specs = [] for i, layer_spec in enumerate(layer_specs): full_layer_spec = [3, layer_spec[0], layer_spec[1], 1] full_layer_specs.append(full_layer_spec) super().__init__(name=name, layer_specs=full_layer_specs, activation_fn=activation_fn, last_...
LateralConnection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LateralConnection: def __init__(self, name, layer_specs, activation_fn=leaky_relu, total_dropout_rate=0.0, regularizer=None): """:param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimens...
stack_v2_sparse_classes_75kplus_train_068675
6,555
no_license
[ { "docstring": ":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_output_features, dilation]. :param activation_fn: Tensorflow activation function. This will not be applied on the la...
2
stack_v2_sparse_classes_30k_train_042368
Implement the Python class `LateralConnection` described below. Class description: Implement the LateralConnection class. Method signatures and docstrings: - def __init__(self, name, layer_specs, activation_fn=leaky_relu, total_dropout_rate=0.0, regularizer=None): :param name: Str. For variable scoping. :param layer_...
Implement the Python class `LateralConnection` described below. Class description: Implement the LateralConnection class. Method signatures and docstrings: - def __init__(self, name, layer_specs, activation_fn=leaky_relu, total_dropout_rate=0.0, regularizer=None): :param name: Str. For variable scoping. :param layer_...
494d503c729ba018614fc742f1aee1e48d37127e
<|skeleton|> class LateralConnection: def __init__(self, name, layer_specs, activation_fn=leaky_relu, total_dropout_rate=0.0, regularizer=None): """:param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimens...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LateralConnection: def __init__(self, name, layer_specs, activation_fn=leaky_relu, total_dropout_rate=0.0, regularizer=None): """:param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists o...
the_stack_v2_python_sparse
context_interp/gridnet/connections/connections.py
NeedsMorePie/interpolator
train
2
c7525a3ef8a75ec06e9c27d6d176304b3539ec44
[ "super().__init__()\nself.generator = generator_cls(img_shape, num_res_blocks, c_dim)\nself.discriminator = discriminator_cls(img_shape, c_dim, num_strided)\nself._c_dim = c_dim\nself.lambda_cls = lambda_cls\nself.lambda_rec = lambda_rec\nself.lambda_gp = lambda_gp\nself._gen_update_freq = gen_update_freq\nself._ge...
<|body_start_0|> super().__init__() self.generator = generator_cls(img_shape, num_res_blocks, c_dim) self.discriminator = discriminator_cls(img_shape, c_dim, num_strided) self._c_dim = c_dim self.lambda_cls = lambda_cls self.lambda_rec = lambda_rec self.lambda_gp ...
Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it might be best, to spl...
StarGAN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StarGAN: """Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already traine...
stack_v2_sparse_classes_75kplus_train_068676
7,061
permissive
[ { "docstring": "Parameters ---------- img_shape : tuple the shape of the generated/input images; should contain channels, but not the batch dimension c_dim : int size of the latent code dimension num_res_blocks : int number of residual blocks inside the generator num_strided : int number of strided convolutions...
3
stack_v2_sparse_classes_30k_train_017459
Implement the Python class `StarGAN` described below. Class description: Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you...
Implement the Python class `StarGAN` described below. Class description: Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class StarGAN: """Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already traine...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StarGAN: """Class implementing StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation References ---------- `Paper <https://arxiv.org/abs/1711.09020>`_ Warnings -------- This Network is designed for training only; if you want to predict from an already trained network, it...
the_stack_v2_python_sparse
dlutils/models/gans/star/stargan.py
justusschock/dl-utils
train
15
0176add48d35c59dabfb58db02fccea7eb604be8
[ "inv.Inventory.__init__(self, item_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage", "outputdict = {}\noutputdict['item_code'] = self.item_code\noutputdict['description'] = self.description\noutputdict['market_price'] = self.market_price\noutputdict['rental_price'] = sel...
<|body_start_0|> inv.Inventory.__init__(self, item_code, description, market_price, rental_price) self.brand = brand self.voltage = voltage <|end_body_0|> <|body_start_1|> outputdict = {} outputdict['item_code'] = self.item_code outputdict['description'] = self.descripti...
some stuff2
ElectricAppliances
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElectricAppliances: """some stuff2""" def __init__(self, item_code, description, market_price, rental_price, brand, voltage): """some stuff3""" <|body_0|> def return_as_dictionary(self): """some stuff4""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_068677
931
no_license
[ { "docstring": "some stuff3", "name": "__init__", "signature": "def __init__(self, item_code, description, market_price, rental_price, brand, voltage)" }, { "docstring": "some stuff4", "name": "return_as_dictionary", "signature": "def return_as_dictionary(self)" } ]
2
null
Implement the Python class `ElectricAppliances` described below. Class description: some stuff2 Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price, brand, voltage): some stuff3 - def return_as_dictionary(self): some stuff4
Implement the Python class `ElectricAppliances` described below. Class description: some stuff2 Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price, brand, voltage): some stuff3 - def return_as_dictionary(self): some stuff4 <|skeleton|> class ElectricAppliances: ...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class ElectricAppliances: """some stuff2""" def __init__(self, item_code, description, market_price, rental_price, brand, voltage): """some stuff3""" <|body_0|> def return_as_dictionary(self): """some stuff4""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ElectricAppliances: """some stuff2""" def __init__(self, item_code, description, market_price, rental_price, brand, voltage): """some stuff3""" inv.Inventory.__init__(self, item_code, description, market_price, rental_price) self.brand = brand self.voltage = voltage d...
the_stack_v2_python_sparse
students/ScotchWSplenda/lesson01/assignment/inventory_management/electric_appliances_class.py
JavaRod/SP_Python220B_2019
train
1
713b8427f8e6c60ab2470f8515a03ae8dd3eb73e
[ "context = super().get_context_data(**kwargs)\ncontext['category'] = self.category\nreturn context", "if self.category:\n return models.Manufacturer.objects.exclude(description__isnull=True).filter(category_id__gte=self.category.gte).filter(category_id__lt=self.category.lt)\nreturn models.Manufacturer.objects....
<|body_start_0|> context = super().get_context_data(**kwargs) context['category'] = self.category return context <|end_body_0|> <|body_start_1|> if self.category: return models.Manufacturer.objects.exclude(description__isnull=True).filter(category_id__gte=self.category.gte)....
List of manufacturers.
Manufacturers
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Manufacturers: """List of manufacturers.""" def get_context_data(self, **kwargs): """Add category to the context.""" <|body_0|> def get_queryset(self): """Show list of manufacturers inside one category.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_068678
5,601
permissive
[ { "docstring": "Add category to the context.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Show list of manufacturers inside one category.", "name": "get_queryset", "signature": "def get_queryset(self)" } ]
2
stack_v2_sparse_classes_30k_train_001352
Implement the Python class `Manufacturers` described below. Class description: List of manufacturers. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add category to the context. - def get_queryset(self): Show list of manufacturers inside one category.
Implement the Python class `Manufacturers` described below. Class description: List of manufacturers. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add category to the context. - def get_queryset(self): Show list of manufacturers inside one category. <|skeleton|> class Manufacturers: ...
84c4fa10aefbd792a956cef3d727623ca78cb5fd
<|skeleton|> class Manufacturers: """List of manufacturers.""" def get_context_data(self, **kwargs): """Add category to the context.""" <|body_0|> def get_queryset(self): """Show list of manufacturers inside one category.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Manufacturers: """List of manufacturers.""" def get_context_data(self, **kwargs): """Add category to the context.""" context = super().get_context_data(**kwargs) context['category'] = self.category return context def get_queryset(self): """Show list of manufac...
the_stack_v2_python_sparse
market/core/views/base.py
katomaso/django-market
train
0
d9b117f5dffc3f5f23455b27694753d795673c4f
[ "if 'length' not in net_params.additional_params:\n raise ValueError('length of circle not supplied')\nself.length = net_params.additional_params['length']\nif 'lanes' not in net_params.additional_params:\n raise ValueError('lanes of circle not supplied')\nself.lanes = net_params.additional_params['lanes']\ni...
<|body_start_0|> if 'length' not in net_params.additional_params: raise ValueError('length of circle not supplied') self.length = net_params.additional_params['length'] if 'lanes' not in net_params.additional_params: raise ValueError('lanes of circle not supplied') ...
LoopScenario
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoopScenario: def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): """Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params.""" <|body_0|> def specify_edge_starts(s...
stack_v2_sparse_classes_75kplus_train_068679
1,524
permissive
[ { "docstring": "Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params.", "name": "__init__", "signature": "def __init__(self, name, generator_class, vehicles, net_params, initial_config=None)" }, { "docstring": "See pa...
2
stack_v2_sparse_classes_30k_train_011237
Implement the Python class `LoopScenario` described below. Class description: Implement the LoopScenario class. Method signatures and docstrings: - def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolu...
Implement the Python class `LoopScenario` described below. Class description: Implement the LoopScenario class. Method signatures and docstrings: - def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolu...
f3f6d7e9c64f6b641a464a716c7f38ca00388805
<|skeleton|> class LoopScenario: def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): """Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params.""" <|body_0|> def specify_edge_starts(s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoopScenario: def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): """Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params.""" if 'length' not in net_params.additional_params: ...
the_stack_v2_python_sparse
flow/scenarios/loop/loop_scenario.py
mark-koren/flow
train
0
298ca184f3e67ac7cfdd44e60f88ee1ca299386f
[ "wx.Panel.__init__(self, parent)\nself.SetBackgroundColour('3399FF')\nself.father = manipulador\nself.lbldesc = wx.StaticText(self, label='Descripcion Tipo de Pregunta :', pos=(100, 35))\nself.editdesc = wx.TextCtrl(self, value='', pos=(0, 35), size=(140, -1))\nself.button = wx.Button(self, wx.ID_OK, label='Siguien...
<|body_start_0|> wx.Panel.__init__(self, parent) self.SetBackgroundColour('3399FF') self.father = manipulador self.lbldesc = wx.StaticText(self, label='Descripcion Tipo de Pregunta :', pos=(100, 35)) self.editdesc = wx.TextCtrl(self, value='', pos=(0, 35), size=(140, -1)) ...
Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra.
paneltipopregunta
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class paneltipopregunta: """Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra.""" def __init__(self, p...
stack_v2_sparse_classes_75kplus_train_068680
10,739
no_license
[ { "docstring": "contructor requiere de parent como interfaz contenedor y manipulador como clase que accedera a la informacion", "name": "__init__", "signature": "def __init__(self, parent, manipulador, accion)" }, { "docstring": "metodo que atendera el boton siguiente y registrara la informacion...
2
stack_v2_sparse_classes_30k_test_002246
Implement the Python class `paneltipopregunta` described below. Class description: Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que es...
Implement the Python class `paneltipopregunta` described below. Class description: Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que es...
b7fa1939056baa01b48d310d981a5fb1493d6698
<|skeleton|> class paneltipopregunta: """Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra.""" def __init__(self, p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class paneltipopregunta: """Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen podra ingresar datos como el nombre del examen, la fecha del examen, el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra.""" def __init__(self, parent, manipu...
the_stack_v2_python_sparse
NewPythonProject/src/administrador Interfaz/admparametros.py
wahello/gesdatos
train
0
3a851b212c1154b6d2372f44e52493b61b497e10
[ "header = FormatCBFMiniPilatus.get_cbf_header(image_file)\nyear = 0\nfor record in header.split('\\n'):\n if '# 20' in record:\n year = int(record.replace('-', ' ').replace('/', ' ').split()[1])\n break\nif year <= 0:\n return False\nfor record in header.split('\\n'):\n if '# Detector' in rec...
<|body_start_0|> header = FormatCBFMiniPilatus.get_cbf_header(image_file) year = 0 for record in header.split('\n'): if '# 20' in record: year = int(record.replace('-', ' ').replace('/', ' ').split()[1]) break if year <= 0: return F...
A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS.
FormatCBFMiniPilatusDLS6MSN119
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FormatCBFMiniPilatusDLS6MSN119: """A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS.""" def understand(image_file): """Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sense of it.""" <|body_0|> def _goniometer(self...
stack_v2_sparse_classes_75kplus_train_068681
2,060
permissive
[ { "docstring": "Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sense of it.", "name": "understand", "signature": "def understand(image_file)" }, { "docstring": "Return a model for a simple single-axis goniometer. This should probably be checked against the ima...
2
stack_v2_sparse_classes_30k_train_048449
Implement the Python class `FormatCBFMiniPilatusDLS6MSN119` described below. Class description: A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS. Method signatures and docstrings: - def understand(image_file): Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sen...
Implement the Python class `FormatCBFMiniPilatusDLS6MSN119` described below. Class description: A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS. Method signatures and docstrings: - def understand(image_file): Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sen...
2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f
<|skeleton|> class FormatCBFMiniPilatusDLS6MSN119: """A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS.""" def understand(image_file): """Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sense of it.""" <|body_0|> def _goniometer(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FormatCBFMiniPilatusDLS6MSN119: """A class for reading mini CBF format Pilatus images for 6M SN 119 @ DLS.""" def understand(image_file): """Check to see if this looks like an Pilatus mini CBF format image, i.e. we can make sense of it.""" header = FormatCBFMiniPilatus.get_cbf_header(imag...
the_stack_v2_python_sparse
src/dxtbx/format/FormatCBFMiniPilatusDLS6MSN119.py
cctbx/dxtbx
train
2
90a8560e68210f05645872a3614e8aeea3b75853
[ "try:\n parser = DocumentParser.post_parser()\n request_data = parser.parse_args()\n size_in_limit = DocumentHandler.max_document_size(request_data['documents'][0])\n if not size_in_limit:\n return ('File size limit exceeds the max size', 413)\n result = DocumentHandler.upload_document(request...
<|body_start_0|> try: parser = DocumentParser.post_parser() request_data = parser.parse_args() size_in_limit = DocumentHandler.max_document_size(request_data['documents'][0]) if not size_in_limit: return ('File size limit exceeds the max size', 413...
Documents
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Documents: def post(self): """The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document details in Json Format""" <|body_0|> def get(self): """This GET request will fe...
stack_v2_sparse_classes_75kplus_train_068682
7,627
no_license
[ { "docstring": "The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document details in Json Format", "name": "post", "signature": "def post(self)" }, { "docstring": "This GET request will fetch the ...
3
stack_v2_sparse_classes_30k_train_032547
Implement the Python class `Documents` described below. Class description: Implement the Documents class. Method signatures and docstrings: - def post(self): The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document de...
Implement the Python class `Documents` described below. Class description: Implement the Documents class. Method signatures and docstrings: - def post(self): The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document de...
17b93889c6945db15ed8b57147def2ae89a07de5
<|skeleton|> class Documents: def post(self): """The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document details in Json Format""" <|body_0|> def get(self): """This GET request will fe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Documents: def post(self): """The POST request will upload the document on the S3 bucket, If the upload is successful then we will save the Details in the database @return: Saved Document details in Json Format""" try: parser = DocumentParser.post_parser() request_data ...
the_stack_v2_python_sparse
FiledInfluencer/Api/routers.py
jssellars/aniket_filed
train
0
45bcd679555a4a2476e9db8c8d79c7bbdc392435
[ "lst = []\nself.travel(root, lst)\nreturn lst", "if not root:\n return\nself.travel(root.left, lst)\nlst.append(root.val)\nself.travel(root.right, lst)", "if not root:\n return []\nresult = []\nst = []\nnode = root\nwhile node or len(st) > 0:\n if node:\n st.append(node)\n node = node.lef...
<|body_start_0|> lst = [] self.travel(root, lst) return lst <|end_body_0|> <|body_start_1|> if not root: return self.travel(root.left, lst) lst.append(root.val) self.travel(root.right, lst) <|end_body_1|> <|body_start_2|> if not root: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def travel(self, root, lst): """:param root: :param lst: :return:""" <|body_1|> def in_order_no_dfs(self, root): """中序遍历非递归 :param root: :return:"...
stack_v2_sparse_classes_75kplus_train_068683
1,316
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "inorderTraversal", "signature": "def inorderTraversal(self, root)" }, { "docstring": ":param root: :param lst: :return:", "name": "travel", "signature": "def travel(self, root, lst)" }, { "docstring": "中序遍历非递归 :par...
3
stack_v2_sparse_classes_30k_test_001304
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def travel(self, root, lst): :param root: :param lst: :return: - def in_order_no_dfs(self, root): 中序遍历非...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def travel(self, root, lst): :param root: :param lst: :return: - def in_order_no_dfs(self, root): 中序遍历非...
a75310a96d2b165b15d5ee10ec409a17cdc880ba
<|skeleton|> class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def travel(self, root, lst): """:param root: :param lst: :return:""" <|body_1|> def in_order_no_dfs(self, root): """中序遍历非递归 :param root: :return:"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" lst = [] self.travel(root, lst) return lst def travel(self, root, lst): """:param root: :param lst: :return:""" if not root: return self.travel(root...
the_stack_v2_python_sparse
leetcode/tree/code/mid.py
skyxyz-lang/CS_Note
train
0
f0580ac2ec2b128a6cafef59db7a81c469e7786d
[ "list_of_column_names = remove_duplicate_column_names(plot_options[DATA])\ntable_dict = {HEADER_INFO: plot_options[DATA], DATA: json.dumps(data[list_of_column_names].to_dict('records')), OPTIONS: plot_options.get(OPTIONS, {})}\nreturn table_dict", "set_of_column_names = set()\nfor dict_of_data_for_each_column in ...
<|body_start_0|> list_of_column_names = remove_duplicate_column_names(plot_options[DATA]) table_dict = {HEADER_INFO: plot_options[DATA], DATA: json.dumps(data[list_of_column_names].to_dict('records')), OPTIONS: plot_options.get(OPTIONS, {})} return table_dict <|end_body_0|> <|body_start_1|> ...
BootstrapTable
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BootstrapTable: def make_dict_for_html_plot(data, plot_options, visualization_options=None): """Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_table are currently not implemented. based on https://bootstrap-table.com/ :param data: a pandas dataframe...
stack_v2_sparse_classes_75kplus_train_068684
2,143
permissive
[ { "docstring": "Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_table are currently not implemented. based on https://bootstrap-table.com/ :param data: a pandas dataframe :param plot_options: :param visualization_options: not used :return:", "name": "make_dict_for_html_...
2
stack_v2_sparse_classes_30k_train_030865
Implement the Python class `BootstrapTable` described below. Class description: Implement the BootstrapTable class. Method signatures and docstrings: - def make_dict_for_html_plot(data, plot_options, visualization_options=None): Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_tab...
Implement the Python class `BootstrapTable` described below. Class description: Implement the BootstrapTable class. Method signatures and docstrings: - def make_dict_for_html_plot(data, plot_options, visualization_options=None): Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_tab...
8da4dc69eec5976a87dc250361ff1ec35f53a739
<|skeleton|> class BootstrapTable: def make_dict_for_html_plot(data, plot_options, visualization_options=None): """Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_table are currently not implemented. based on https://bootstrap-table.com/ :param data: a pandas dataframe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BootstrapTable: def make_dict_for_html_plot(data, plot_options, visualization_options=None): """Makes the dictionary that bootstrap_table.html takes in. layout options for bootstrap_table are currently not implemented. based on https://bootstrap-table.com/ :param data: a pandas dataframe :param plot_o...
the_stack_v2_python_sparse
escalation/graphics/bootstrap_table.py
twosixlabs/Escalation
train
42
e4b0a2a7e3b9bb95b11a5fdeb9169d7eed891d3d
[ "if len(nums) == 1:\n return False\nfor i in range(0, len(nums)):\n for j in range(1, k + 1):\n if i + j >= len(nums):\n break\n if nums[i] == nums[i + j]:\n return True\nreturn False", "nums_dictionary = {}\nfor i, v in enumerate(nums):\n if v in nums_dictionary and i...
<|body_start_0|> if len(nums) == 1: return False for i in range(0, len(nums)): for j in range(1, k + 1): if i + j >= len(nums): break if nums[i] == nums[i + j]: return True return False <|end_body_0|>...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_75kplus_train_068685
1,186
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def containsNearbyDuplicate(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: bool", "name": "containsNearbyDuplicate", "signature": "def contain...
2
stack_v2_sparse_classes_30k_train_034314
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool - def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtyp...
6de551327f96ec4d4b63d0045281b65bbb4f5d0f
<|skeleton|> class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_0|> def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def containsNearbyDuplicate(self, nums, k): """:type nums: List[int] :type k: int :rtype: bool""" if len(nums) == 1: return False for i in range(0, len(nums)): for j in range(1, k + 1): if i + j >= len(nums): break ...
the_stack_v2_python_sparse
containsNearbyDuplicate.py
JingweiTu/leetcode
train
0
5ea9cadb6252c364917095031b5ad575fd5b9728
[ "data = dj_serializers.serialize('json', obj.children())\njson_data = json.loads(data)\nfor item in json_data:\n item['fields']['content_type'] = obj.content_type.name\nreturn json_data", "if timesince.timesince(obj.datetime_created) == timesince.timesince(obj.datetime_modified):\n created_value = timesince...
<|body_start_0|> data = dj_serializers.serialize('json', obj.children()) json_data = json.loads(data) for item in json_data: item['fields']['content_type'] = obj.content_type.name return json_data <|end_body_0|> <|body_start_1|> if timesince.timesince(obj.datetime_cr...
Serializer for Comment model.
CommentSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentSerializer: """Serializer for Comment model.""" def get_children(self, obj): """Return `children` serialized objects.""" <|body_0|> def get_date_to_display(self, obj): """Return timesince formatted date.""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_75kplus_train_068686
2,149
no_license
[ { "docstring": "Return `children` serialized objects.", "name": "get_children", "signature": "def get_children(self, obj)" }, { "docstring": "Return timesince formatted date.", "name": "get_date_to_display", "signature": "def get_date_to_display(self, obj)" } ]
2
stack_v2_sparse_classes_30k_train_038036
Implement the Python class `CommentSerializer` described below. Class description: Serializer for Comment model. Method signatures and docstrings: - def get_children(self, obj): Return `children` serialized objects. - def get_date_to_display(self, obj): Return timesince formatted date.
Implement the Python class `CommentSerializer` described below. Class description: Serializer for Comment model. Method signatures and docstrings: - def get_children(self, obj): Return `children` serialized objects. - def get_date_to_display(self, obj): Return timesince formatted date. <|skeleton|> class CommentSeri...
faee901943371ed85f8ecde456b342efdb07e865
<|skeleton|> class CommentSerializer: """Serializer for Comment model.""" def get_children(self, obj): """Return `children` serialized objects.""" <|body_0|> def get_date_to_display(self, obj): """Return timesince formatted date.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CommentSerializer: """Serializer for Comment model.""" def get_children(self, obj): """Return `children` serialized objects.""" data = dj_serializers.serialize('json', obj.children()) json_data = json.loads(data) for item in json_data: item['fields']['content_t...
the_stack_v2_python_sparse
comments/serializers.py
arviesan24/social_media
train
0
4316dd648a836b67fd26c58b4a557df4bfffc03e
[ "self.continue_on_error = continue_on_error\nself.is_active = is_active\nself.script_params = script_params\nself.script_path = script_path\nself.timeout_secs = timeout_secs", "if dictionary is None:\n return None\ncontinue_on_error = dictionary.get('continueOnError')\nis_active = dictionary.get('isActive')\ns...
<|body_start_0|> self.continue_on_error = continue_on_error self.is_active = is_active self.script_params = script_params self.script_path = script_path self.timeout_secs = timeout_secs <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre backup script fails. is_active (bool):...
ScriptPathAndParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if...
stack_v2_sparse_classes_75kplus_train_068687
3,226
permissive
[ { "docstring": "Constructor for the ScriptPathAndParams class", "name": "__init__", "signature": "def __init__(self, continue_on_error=None, is_active=None, script_params=None, script_path=None, timeout_secs=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dict...
2
stack_v2_sparse_classes_30k_train_003771
Implement the Python class `ScriptPathAndParams` described below. Class description: Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t...
Implement the Python class `ScriptPathAndParams` described below. Class description: Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre back...
the_stack_v2_python_sparse
cohesity_management_sdk/models/script_path_and_params.py
cohesity/management-sdk-python
train
24
3b3db13651e78609688a33e3532655c59b7abf38
[ "\"\"\"The states\"\"\"\nstates = ['Welcome state', 'Pure comment', 'Hybrid comment', 'Lulls comment']\nself.states = states\n'Dict states to index'\nself.states2idx = {k: i for i, k in enumerate(states)}\n'Dict index to state'\nself.id2st = {self.states2idx[k]: k for k in self.states2idx.keys()}\nself.n_states = l...
<|body_start_0|> """The states""" states = ['Welcome state', 'Pure comment', 'Hybrid comment', 'Lulls comment'] self.states = states 'Dict states to index' self.states2idx = {k: i for i, k in enumerate(states)} 'Dict index to state' self.id2st = {self.states2idx[k...
CommentAutomata
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentAutomata: def __init__(self): """Initialize the automata""" <|body_0|> def NextState(self): """Returns the next state""" <|body_1|> def DrawAutomata(self, fn='Commentator Automata.gv'): """Writes on file fn (default 'Commentator Automata.g...
stack_v2_sparse_classes_75kplus_train_068688
3,627
no_license
[ { "docstring": "Initialize the automata", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Returns the next state", "name": "NextState", "signature": "def NextState(self)" }, { "docstring": "Writes on file fn (default 'Commentator Automata.gv') representat...
3
stack_v2_sparse_classes_30k_train_019129
Implement the Python class `CommentAutomata` described below. Class description: Implement the CommentAutomata class. Method signatures and docstrings: - def __init__(self): Initialize the automata - def NextState(self): Returns the next state - def DrawAutomata(self, fn='Commentator Automata.gv'): Writes on file fn ...
Implement the Python class `CommentAutomata` described below. Class description: Implement the CommentAutomata class. Method signatures and docstrings: - def __init__(self): Initialize the automata - def NextState(self): Returns the next state - def DrawAutomata(self, fn='Commentator Automata.gv'): Writes on file fn ...
e2f42e511b42d82e4330d2afb7ecb172a3b5f7f5
<|skeleton|> class CommentAutomata: def __init__(self): """Initialize the automata""" <|body_0|> def NextState(self): """Returns the next state""" <|body_1|> def DrawAutomata(self, fn='Commentator Automata.gv'): """Writes on file fn (default 'Commentator Automata.g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CommentAutomata: def __init__(self): """Initialize the automata""" """The states""" states = ['Welcome state', 'Pure comment', 'Hybrid comment', 'Lulls comment'] self.states = states 'Dict states to index' self.states2idx = {k: i for i, k in enumerate(states)} ...
the_stack_v2_python_sparse
CommentGenerator/src/Automaton.py
SmartAppUnipi/RoboComment
train
4
a1389f1fbf319aa1d32f5c14781987aa8aac9afb
[ "super(VAE, self).__init__()\nself.encoder = self.EncoderRNN(input_size, hidden_size)\nself.decoder = self.DecoderRNN(input_size, hidden_size)\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.latent_size = latent_size\nself.conditional_size = conditional_size\nself.max_length = max_length\nself.t...
<|body_start_0|> super(VAE, self).__init__() self.encoder = self.EncoderRNN(input_size, hidden_size) self.decoder = self.DecoderRNN(input_size, hidden_size) self.input_size = input_size self.hidden_size = hidden_size self.latent_size = latent_size self.conditional...
VAE
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VAE: def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length): """:param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size: 8""" <|body_0|> def forward(self, input_tensor, encoder_hidden_state, encoder_...
stack_v2_sparse_classes_75kplus_train_068689
9,452
no_license
[ { "docstring": ":param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size: 8", "name": "__init__", "signature": "def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length)" }, { "docstring": "forwarding a word in VAE (This is ...
5
stack_v2_sparse_classes_30k_train_053546
Implement the Python class `VAE` described below. Class description: Implement the VAE class. Method signatures and docstrings: - def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length): :param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size:...
Implement the Python class `VAE` described below. Class description: Implement the VAE class. Method signatures and docstrings: - def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length): :param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size:...
de439e62928f1fe8daec7665946ce9133b3d8d7a
<|skeleton|> class VAE: def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length): """:param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size: 8""" <|body_0|> def forward(self, input_tensor, encoder_hidden_state, encoder_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VAE: def __init__(self, input_size, hidden_size, latent_size, conditional_size, max_length): """:param input_size: 28 :param hidden_size: 256 or 512 :param latent_size: 32 :param conditional_size: 8""" super(VAE, self).__init__() self.encoder = self.EncoderRNN(input_size, hidden_size) ...
the_stack_v2_python_sparse
Lab5/model.py
Louis5228/DLP-lab
train
1
0b437f1d9490256469d57263bcc0185705fa5d89
[ "u = Group.objects.create(name='ADMINISTRACION')\nself.assertTrue(isinstance(u, Group))\nprint('Test de crear perfil, exitoso')", "c = Client()\nc.login(username='nabil', password='123')\nresp = c.get('/perfil/listar_perfiles/', follow=True)\nself.assertEqual(resp.status_code, 200)\nprint('Test de listado de perf...
<|body_start_0|> u = Group.objects.create(name='ADMINISTRACION') self.assertTrue(isinstance(u, Group)) print('Test de crear perfil, exitoso') <|end_body_0|> <|body_start_1|> c = Client() c.login(username='nabil', password='123') resp = c.get('/perfil/listar_perfiles/', f...
PerfilTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerfilTestCase: def test_crea_perfil(self): """Test para verificar la correcta creacion de un rol""" <|body_0|> def test_listar_perfiles(self): """Test para ver si se listan correctamente los usuarios""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_068690
799
no_license
[ { "docstring": "Test para verificar la correcta creacion de un rol", "name": "test_crea_perfil", "signature": "def test_crea_perfil(self)" }, { "docstring": "Test para ver si se listan correctamente los usuarios", "name": "test_listar_perfiles", "signature": "def test_listar_perfiles(sel...
2
stack_v2_sparse_classes_30k_train_023641
Implement the Python class `PerfilTestCase` described below. Class description: Implement the PerfilTestCase class. Method signatures and docstrings: - def test_crea_perfil(self): Test para verificar la correcta creacion de un rol - def test_listar_perfiles(self): Test para ver si se listan correctamente los usuarios
Implement the Python class `PerfilTestCase` described below. Class description: Implement the PerfilTestCase class. Method signatures and docstrings: - def test_crea_perfil(self): Test para verificar la correcta creacion de un rol - def test_listar_perfiles(self): Test para ver si se listan correctamente los usuarios...
bd4e55661f7897d2294a27ce240c044192385102
<|skeleton|> class PerfilTestCase: def test_crea_perfil(self): """Test para verificar la correcta creacion de un rol""" <|body_0|> def test_listar_perfiles(self): """Test para ver si se listan correctamente los usuarios""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PerfilTestCase: def test_crea_perfil(self): """Test para verificar la correcta creacion de un rol""" u = Group.objects.create(name='ADMINISTRACION') self.assertTrue(isinstance(u, Group)) print('Test de crear perfil, exitoso') def test_listar_perfiles(self): """Test...
the_stack_v2_python_sparse
apps/perfil/tests.py
nabilchamas/is2
train
0
9e091423a24d47f6182a097bbf65e22221b80083
[ "super(SimplePatchShadow, self).__init__(offset)\nif shadow_rgbFace is None:\n self._shadow_rgbFace = shadow_rgbFace\nelse:\n self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)\nif alpha is None:\n alpha = 0.3\nself._alpha = alpha\nself._rho = rho\nself._gc = kwargs\nself._offset_tran = mtransforms.Aff...
<|body_start_0|> super(SimplePatchShadow, self).__init__(offset) if shadow_rgbFace is None: self._shadow_rgbFace = shadow_rgbFace else: self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace) if alpha is None: alpha = 0.3 self._alpha = alpha ...
A simple shadow via a filled patch.
SimplePatchShadow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimplePatchShadow: """A simple shadow via a filled patch.""" def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): """Parameters ---------- offset : pair of floats The offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : f...
stack_v2_sparse_classes_75kplus_train_068691
14,346
permissive
[ { "docstring": "Parameters ---------- offset : pair of floats The offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : float The alpha transparency of the created shadow patch. Default is 0.3. http://matplotlib.1069221.n5.nabble.com/path-effects-question-td27630.html rho : float A sc...
2
stack_v2_sparse_classes_30k_val_000067
Implement the Python class `SimplePatchShadow` described below. Class description: A simple shadow via a filled patch. Method signatures and docstrings: - def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): Parameters ---------- offset : pair of floats The offset of the shadow in p...
Implement the Python class `SimplePatchShadow` described below. Class description: A simple shadow via a filled patch. Method signatures and docstrings: - def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): Parameters ---------- offset : pair of floats The offset of the shadow in p...
f5042e35b945aded77b23470ead62d7eacefde92
<|skeleton|> class SimplePatchShadow: """A simple shadow via a filled patch.""" def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): """Parameters ---------- offset : pair of floats The offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : f...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimplePatchShadow: """A simple shadow via a filled patch.""" def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): """Parameters ---------- offset : pair of floats The offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : float The alph...
the_stack_v2_python_sparse
contrib/python/matplotlib/py2/matplotlib/patheffects.py
catboost/catboost
train
8,012
ed41bfc5515008d62eee2b4e11ec55f39c8710c4
[ "query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Server.objects.filter(id=kwargs['id']).first()\nform = ServerEditForm(instance=asearch)\nlist_server = None\nif query:\n list_server = Server.objects.filter(Q(name__icontains=query))\nelse:\n list_server = Server.objects.all()\np...
<|body_start_0|> query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Server.objects.filter(id=kwargs['id']).first() form = ServerEditForm(instance=asearch) list_server = None if query: list_server = Server.objects.filter(Q(name__icont...
Clase para editar los servidores
ServerEditView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|> <|body_start_0|> query = request....
stack_v2_sparse_classes_75kplus_train_068692
22,221
no_license
[ { "docstring": "Método get", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Método post", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_024820
Implement the Python class `ServerEditView` described below. Class description: Clase para editar los servidores Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post
Implement the Python class `ServerEditView` described below. Class description: Clase para editar los servidores Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post <|skeleton|> class ServerEditView: """Clase para editar ...
e28e2d968372609ad396c42fb572a00c2410a117
<|skeleton|> class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Server.objects.filter(id=kwargs['id']).first() form = ServerEditForm(insta...
the_stack_v2_python_sparse
list/views.py
damaos/server_list2
train
0
82678b581f2e4d50cda3152633fcc27489cde60d
[ "self.A = mat_params['A']\nself.B = mat_params['B']\nself.C = mat_params['C']\nself.thickness = thickness\nself.name = name", "n = np.sqrt(self.A + self.B * w ** 2 / (w ** 2 - self.C))\nk = 2 * PI * n / w\ntheta = k * self.thickness\nM = np.array([[np.cos(theta), 1j * np.sin(theta) / n], [1j * n * np.sin(theta), ...
<|body_start_0|> self.A = mat_params['A'] self.B = mat_params['B'] self.C = mat_params['C'] self.thickness = thickness self.name = name <|end_body_0|> <|body_start_1|> n = np.sqrt(self.A + self.B * w ** 2 / (w ** 2 - self.C)) k = 2 * PI * n / w theta = k ...
SellmeierLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SellmeierLayer: def __init__(self, mat_params, thickness, name=None): """SellmeierLayer(mat_params, thickness, name=None)""" <|body_0|> def matrix(self, w): """matrix(w) Generate transmission matrix for layer for wavelength w""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_068693
13,406
no_license
[ { "docstring": "SellmeierLayer(mat_params, thickness, name=None)", "name": "__init__", "signature": "def __init__(self, mat_params, thickness, name=None)" }, { "docstring": "matrix(w) Generate transmission matrix for layer for wavelength w", "name": "matrix", "signature": "def matrix(sel...
2
stack_v2_sparse_classes_30k_train_037089
Implement the Python class `SellmeierLayer` described below. Class description: Implement the SellmeierLayer class. Method signatures and docstrings: - def __init__(self, mat_params, thickness, name=None): SellmeierLayer(mat_params, thickness, name=None) - def matrix(self, w): matrix(w) Generate transmission matrix f...
Implement the Python class `SellmeierLayer` described below. Class description: Implement the SellmeierLayer class. Method signatures and docstrings: - def __init__(self, mat_params, thickness, name=None): SellmeierLayer(mat_params, thickness, name=None) - def matrix(self, w): matrix(w) Generate transmission matrix f...
dff2309d3b6809066526d67695a6744e7c4234ff
<|skeleton|> class SellmeierLayer: def __init__(self, mat_params, thickness, name=None): """SellmeierLayer(mat_params, thickness, name=None)""" <|body_0|> def matrix(self, w): """matrix(w) Generate transmission matrix for layer for wavelength w""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SellmeierLayer: def __init__(self, mat_params, thickness, name=None): """SellmeierLayer(mat_params, thickness, name=None)""" self.A = mat_params['A'] self.B = mat_params['B'] self.C = mat_params['C'] self.thickness = thickness self.name = name def matrix(se...
the_stack_v2_python_sparse
AGTools/Optics/BraggStackModel.py
ahgibbons/AGTools
train
0
6d86cb4dea10bbdeda6d0ec1638b00c21f5eb51b
[ "tag_dict = dict()\nmi = MonitoracaoInterfaces(ix=self.ix)\nv4_vlan_regex = compile('as\\\\d+-tr(\\\\s|\\\\-\\\\d+)')\nv6_vlan_regex = compile('as\\\\d+-tr-v6(\\\\s|\\\\-\\\\d+)')\ntag_id_regex = compile('\\\\((\\\\d+)\\\\)')\nsw_list = self.get_all_switches()\nfor switch in sw_list:\n for port in switch.port_se...
<|body_start_0|> tag_dict = dict() mi = MonitoracaoInterfaces(ix=self.ix) v4_vlan_regex = compile('as\\d+-tr(\\s|\\-\\d+)') v6_vlan_regex = compile('as\\d+-tr-v6(\\s|\\-\\d+)') tag_id_regex = compile('\\((\\d+)\\)') sw_list = self.get_all_switches() for switch in ...
This class defines queries relates to VLAN Allocation
AlocacaoDeVlans
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlocacaoDeVlans: """This class defines queries relates to VLAN Allocation""" def get_production_vlans_name(self): """This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in MonitoracaoInterfaces class. Returns: A dict with vlan name and the...
stack_v2_sparse_classes_75kplus_train_068694
17,741
permissive
[ { "docstring": "This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in MonitoracaoInterfaces class. Returns: A dict with vlan name and the tag id. tag_dict = { 'as1234-tr': '2010', 'as4321-tr-v6': '2011' ... }", "name": "get_production_vlans_name", "signature...
2
stack_v2_sparse_classes_30k_train_028254
Implement the Python class `AlocacaoDeVlans` described below. Class description: This class defines queries relates to VLAN Allocation Method signatures and docstrings: - def get_production_vlans_name(self): This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in Monitoraca...
Implement the Python class `AlocacaoDeVlans` described below. Class description: This class defines queries relates to VLAN Allocation Method signatures and docstrings: - def get_production_vlans_name(self): This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in Monitoraca...
6ed8cec23b06bccb1edf57e6b67af017f9a162d3
<|skeleton|> class AlocacaoDeVlans: """This class defines queries relates to VLAN Allocation""" def get_production_vlans_name(self): """This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in MonitoracaoInterfaces class. Returns: A dict with vlan name and the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlocacaoDeVlans: """This class defines queries relates to VLAN Allocation""" def get_production_vlans_name(self): """This method gets the vlan names used by nikiti, generated by method get_port_status, implemented in MonitoracaoInterfaces class. Returns: A dict with vlan name and the tag id. tag_...
the_stack_v2_python_sparse
ipaxi/ixbr_api/core/utils/nikiti/queries.py
tatubola/xpto
train
0
471c02e0b1c3c61658bf1b20b8b9e89c69aba3a2
[ "driver = obj.driver\nif self.locator[0] != 'css selector':\n raise 'Using a locator other than css'\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1]))\ndriver.find_element_by_css_selector(self.locator[1]).send_keys(value)", "driver = obj.driver\nif self.loca...
<|body_start_0|> driver = obj.driver if self.locator[0] != 'css selector': raise 'Using a locator other than css' WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1])) driver.find_element_by_css_selector(self.locator[1]).send_ke...
Base page class that is initialized on every page object class.
BasePageElement
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasePageElement: """Base page class that is initialized on every page object class.""" def __set__(self, obj, value): """Sets the text to the value supplied""" <|body_0|> def __get__(self, obj, owner): """Gets the text of the specified object""" <|body_1|...
stack_v2_sparse_classes_75kplus_train_068695
1,105
no_license
[ { "docstring": "Sets the text to the value supplied", "name": "__set__", "signature": "def __set__(self, obj, value)" }, { "docstring": "Gets the text of the specified object", "name": "__get__", "signature": "def __get__(self, obj, owner)" } ]
2
stack_v2_sparse_classes_30k_train_027080
Implement the Python class `BasePageElement` described below. Class description: Base page class that is initialized on every page object class. Method signatures and docstrings: - def __set__(self, obj, value): Sets the text to the value supplied - def __get__(self, obj, owner): Gets the text of the specified object
Implement the Python class `BasePageElement` described below. Class description: Base page class that is initialized on every page object class. Method signatures and docstrings: - def __set__(self, obj, value): Sets the text to the value supplied - def __get__(self, obj, owner): Gets the text of the specified object...
43ab187a9bca4c56d6005a46725c56f39949fceb
<|skeleton|> class BasePageElement: """Base page class that is initialized on every page object class.""" def __set__(self, obj, value): """Sets the text to the value supplied""" <|body_0|> def __get__(self, obj, owner): """Gets the text of the specified object""" <|body_1|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasePageElement: """Base page class that is initialized on every page object class.""" def __set__(self, obj, value): """Sets the text to the value supplied""" driver = obj.driver if self.locator[0] != 'css selector': raise 'Using a locator other than css' WebD...
the_stack_v2_python_sparse
skynet/driver/base_page_element.py
bsterrett/ye_olde_skynet
train
3
e2ec6d150340e21b649ad4809de0016aed15358a
[ "self.HumiditySensor = HumiditySensorAdapterTask.HumiditySensorAdapterTask()\nself.HI2CSensor = HI2CSensorAdapterTask.HI2CSensorAdapterTask()\nself.dataManager = SensorDataManager.SensorDataManager()\nself.loop_limit = loop_param\nself.sleep_time = sleep_param", "i = 0\ntry:\n while i < self.loop_limit or self...
<|body_start_0|> self.HumiditySensor = HumiditySensorAdapterTask.HumiditySensorAdapterTask() self.HI2CSensor = HI2CSensorAdapterTask.HI2CSensorAdapterTask() self.dataManager = SensorDataManager.SensorDataManager() self.loop_limit = loop_param self.sleep_time = sleep_param <|end_b...
Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with
MultiSensorAdapter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiSensorAdapter: """Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with""" def __init__(self, loop_param=10, sleep_param=1): """Constructor Initializing both the sensor tasks and a dat...
stack_v2_sparse_classes_75kplus_train_068696
4,517
no_license
[ { "docstring": "Constructor Initializing both the sensor tasks and a data manager.", "name": "__init__", "signature": "def __init__(self, loop_param=10, sleep_param=1)" }, { "docstring": "Initialize threads", "name": "__init_threads__", "signature": "def __init_threads__(self)" }, { ...
3
stack_v2_sparse_classes_30k_val_001768
Implement the Python class `MultiSensorAdapter` described below. Class description: Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with Method signatures and docstrings: - def __init__(self, loop_param=10, sleep_param=1):...
Implement the Python class `MultiSensorAdapter` described below. Class description: Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with Method signatures and docstrings: - def __init__(self, loop_param=10, sleep_param=1):...
dfd5fd8c757cae8b1306ae3e4eb2cfc9bf124fee
<|skeleton|> class MultiSensorAdapter: """Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with""" def __init__(self, loop_param=10, sleep_param=1): """Constructor Initializing both the sensor tasks and a dat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiSensorAdapter: """Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with""" def __init__(self, loop_param=10, sleep_param=1): """Constructor Initializing both the sensor tasks and a data manager."""...
the_stack_v2_python_sparse
apps/labs/module04/MultiSensorAdapter.py
mnk400/iot-device
train
0
d57c5662e9afd6e663b4739cae0d3f0615af79e1
[ "if not root:\n return False\nself.target = sum\nself.exists = False\n\ndef dfs(node):\n print(node.val)\n if self.exists:\n return\n self.target -= node.val\n if node.left or node.right:\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n ...
<|body_start_0|> if not root: return False self.target = sum self.exists = False def dfs(node): print(node.val) if self.exists: return self.target -= node.val if node.left or node.right: if node....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasPathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_0|> def hasPathSum2(self, root, sum): """Recursively check sub trees. :type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_75kplus_train_068697
2,744
no_license
[ { "docstring": ":type root: TreeNode :type sum: int :rtype: bool", "name": "hasPathSum", "signature": "def hasPathSum(self, root, sum)" }, { "docstring": "Recursively check sub trees. :type root: TreeNode :type sum: int :rtype: bool", "name": "hasPathSum2", "signature": "def hasPathSum2(...
2
stack_v2_sparse_classes_30k_train_017065
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: bool - def hasPathSum2(self, root, sum): Recursively check sub trees. :type root: TreeNode :type sum:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: bool - def hasPathSum2(self, root, sum): Recursively check sub trees. :type root: TreeNode :type sum:...
dbdb227e12f329e4ca064b338f1fbdca42f3a848
<|skeleton|> class Solution: def hasPathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_0|> def hasPathSum2(self, root, sum): """Recursively check sub trees. :type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def hasPathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: bool""" if not root: return False self.target = sum self.exists = False def dfs(node): print(node.val) if self.exists: return ...
the_stack_v2_python_sparse
LC112.py
Qiao-Liang/LeetCode
train
0
f46ae16d0f24258c72eb83c697dab4b5e2aecb0d
[ "def _item_to_string(key, value):\n return '%s=\"%s\"' % (key, value)\nv = [_item_to_string(key, value) for key, value in ce.items()]\nreturn ' '.join(v)", "if build_target.system == build_system.ANDROID:\n from ._toolchain_android_standalone import _toolchain_android_standalone as _toolchain_android\n r...
<|body_start_0|> def _item_to_string(key, value): return '%s="%s"' % (key, value) v = [_item_to_string(key, value) for key, value in ce.items()] return ' '.join(v) <|end_body_0|> <|body_start_1|> if build_target.system == build_system.ANDROID: from ._toolchain_an...
Foo.
toolchain
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class toolchain: """Foo.""" def flatten_for_shell(clazz, ce): """Return the compiler environment flattened and escaped for usage with shell commands.""" <|body_0|> def get_toolchain(clazz, build_target): """Return the toolchain for this particular build target.""" ...
stack_v2_sparse_classes_75kplus_train_068698
1,352
permissive
[ { "docstring": "Return the compiler environment flattened and escaped for usage with shell commands.", "name": "flatten_for_shell", "signature": "def flatten_for_shell(clazz, ce)" }, { "docstring": "Return the toolchain for this particular build target.", "name": "get_toolchain", "signat...
2
stack_v2_sparse_classes_30k_train_050079
Implement the Python class `toolchain` described below. Class description: Foo. Method signatures and docstrings: - def flatten_for_shell(clazz, ce): Return the compiler environment flattened and escaped for usage with shell commands. - def get_toolchain(clazz, build_target): Return the toolchain for this particular ...
Implement the Python class `toolchain` described below. Class description: Foo. Method signatures and docstrings: - def flatten_for_shell(clazz, ce): Return the compiler environment flattened and escaped for usage with shell commands. - def get_toolchain(clazz, build_target): Return the toolchain for this particular ...
501e0897962297c5ce745784bfcba3889508e927
<|skeleton|> class toolchain: """Foo.""" def flatten_for_shell(clazz, ce): """Return the compiler environment flattened and escaped for usage with shell commands.""" <|body_0|> def get_toolchain(clazz, build_target): """Return the toolchain for this particular build target.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class toolchain: """Foo.""" def flatten_for_shell(clazz, ce): """Return the compiler environment flattened and escaped for usage with shell commands.""" def _item_to_string(key, value): return '%s="%s"' % (key, value) v = [_item_to_string(key, value) for key, value in ce.ite...
the_stack_v2_python_sparse
lib/rebuild/toolchain/toolchain.py
reconstruir/rebuild
train
0
ff6868c40b4bd30e0e3d2654f6f0ff7f5eb29cda
[ "try:\n dhcpController = DhcpController()\n json_data = json.dumps(dhcpController.get_dhcp_server_configuration_section_end_ip(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype...
<|body_start_0|> try: dhcpController = DhcpController() json_data = json.dumps(dhcpController.get_dhcp_server_configuration_section_end_ip(id)) resp = Response(json_data, status=200, mimetype='application/json') return resp except ValueError as ve: ...
DhcpServer_Configuration_Section_EndIP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DhcpServer_Configuration_Section_EndIP: def get(self, id): """Gets the section end ip parameter""" <|body_0|> def put(self, id): """Update the section end ip parameter""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: dhcpController =...
stack_v2_sparse_classes_75kplus_train_068699
20,424
no_license
[ { "docstring": "Gets the section end ip parameter", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update the section end ip parameter", "name": "put", "signature": "def put(self, id)" } ]
2
null
Implement the Python class `DhcpServer_Configuration_Section_EndIP` described below. Class description: Implement the DhcpServer_Configuration_Section_EndIP class. Method signatures and docstrings: - def get(self, id): Gets the section end ip parameter - def put(self, id): Update the section end ip parameter
Implement the Python class `DhcpServer_Configuration_Section_EndIP` described below. Class description: Implement the DhcpServer_Configuration_Section_EndIP class. Method signatures and docstrings: - def get(self, id): Gets the section end ip parameter - def put(self, id): Update the section end ip parameter <|skele...
6070e3cb6bf957e04f5d8267db11f3296410e18e
<|skeleton|> class DhcpServer_Configuration_Section_EndIP: def get(self, id): """Gets the section end ip parameter""" <|body_0|> def put(self, id): """Update the section end ip parameter""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DhcpServer_Configuration_Section_EndIP: def get(self, id): """Gets the section end ip parameter""" try: dhcpController = DhcpController() json_data = json.dumps(dhcpController.get_dhcp_server_configuration_section_end_ip(id)) resp = Response(json_data, statu...
the_stack_v2_python_sparse
configuration-agent/dhcp/rest_api/resources/dhcp_server.py
ReliableLion/frog4-configurable-vnf
train
0