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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1eb95a009f4d506cbd75b37128a125311eba62c1 | [
"opt_logfile_name = self.DEFAULT_LOGFILE\nopt_interval = self.DEFAULT_INTERVAL\nopt_functions = self.DEFAULT_FUNCTIONS\nif 'logfile' in opt:\n opt_logfile_name = opt['logfile']\nif 'interval' in opt:\n opt_interval = opt['interval']\nif 'functions' in opt:\n opt_functions = opt['functions']\nself.functions... | <|body_start_0|>
opt_logfile_name = self.DEFAULT_LOGFILE
opt_interval = self.DEFAULT_INTERVAL
opt_functions = self.DEFAULT_FUNCTIONS
if 'logfile' in opt:
opt_logfile_name = opt['logfile']
if 'interval' in opt:
opt_interval = opt['interval']
if 'fun... | Check some function's statistics in the DPM logfile | check_dpns_perf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any o... | stack_v2_sparse_classes_75kplus_train_068200 | 4,886 | no_license | [
{
"docstring": "Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any option",
"name": "__init__",
"signature": "def __init__(self, opt={}, args=[])"
},
{
"docstring": "Test code its... | 2 | stack_v2_sparse_classes_30k_train_039216 | Implement the Python class `check_dpns_perf` described below.
Class description:
Check some function's statistics in the DPM logfile
Method signatures and docstrings:
- def __init__(self, opt={}, args=[]): Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @pa... | Implement the Python class `check_dpns_perf` described below.
Class description:
Check some function's statistics in the DPM logfile
Method signatures and docstrings:
- def __init__(self, opt={}, args=[]): Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @pa... | 270b7d2fff4ae56735d53fa99bb1613c07f1f9a3 | <|skeleton|>
class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class check_dpns_perf:
"""Check some function's statistics in the DPM logfile"""
def __init__(self, opt={}, args=[]):
"""Constructor @param opt Contains a dictionary with the long option name as the key, and the argument as value @param args Contains the arguments not associated with any option"""
... | the_stack_v2_python_sparse | cambox-package/plugins/lcgdm/check_dpm_perf | usuporte/install.issabel | train | 1 |
a1452bb04e99ef839c88685e6a77e3733388b772 | [
"mols = [Chem.MolFromSmiles(s) for s in smiles]\nscores = SmilesChecker.checkSmiles(smiles, frags=frags, no_multifrag_smiles=no_multifrag_smiles)\nfor scorer in self.scorers:\n scores.loc[:, scorer.getKey()] = scorer(mols)\nscores.loc[scores['Valid'] == 0, self.getScorerKeys()] = 0.0\nundesire = scores[self.getS... | <|body_start_0|>
mols = [Chem.MolFromSmiles(s) for s in smiles]
scores = SmilesChecker.checkSmiles(smiles, frags=frags, no_multifrag_smiles=no_multifrag_smiles)
for scorer in self.scorers:
scores.loc[:, scorer.getKey()] = scorer(mols)
scores.loc[scores['Valid'] == 0, self.get... | Original implementation of the environment scoring strategy for DrugEx v3. | DrugExEnvironment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrugExEnvironment:
"""Original implementation of the environment scoring strategy for DrugEx v3."""
def getScores(self, smiles, frags=None, no_multifrag_smiles=True):
"""This method is used to get the scores from the scorers and to check molecule validity and desireability. Parameter... | stack_v2_sparse_classes_75kplus_train_068201 | 2,544 | permissive | [
{
"docstring": "This method is used to get the scores from the scorers and to check molecule validity and desireability. Parameters ---------- smiles : list of str List of SMILES strings to score. frags : list of str, optional List of SMILES strings of fragments to check for. no_multifrag_smiles : bool, optiona... | 2 | stack_v2_sparse_classes_30k_train_045919 | Implement the Python class `DrugExEnvironment` described below.
Class description:
Original implementation of the environment scoring strategy for DrugEx v3.
Method signatures and docstrings:
- def getScores(self, smiles, frags=None, no_multifrag_smiles=True): This method is used to get the scores from the scorers an... | Implement the Python class `DrugExEnvironment` described below.
Class description:
Original implementation of the environment scoring strategy for DrugEx v3.
Method signatures and docstrings:
- def getScores(self, smiles, frags=None, no_multifrag_smiles=True): This method is used to get the scores from the scorers an... | b61d31a4b98b6d600184e52ca24640d3e64fd425 | <|skeleton|>
class DrugExEnvironment:
"""Original implementation of the environment scoring strategy for DrugEx v3."""
def getScores(self, smiles, frags=None, no_multifrag_smiles=True):
"""This method is used to get the scores from the scorers and to check molecule validity and desireability. Parameter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DrugExEnvironment:
"""Original implementation of the environment scoring strategy for DrugEx v3."""
def getScores(self, smiles, frags=None, no_multifrag_smiles=True):
"""This method is used to get the scores from the scorers and to check molecule validity and desireability. Parameters ---------- ... | the_stack_v2_python_sparse | drugex/training/environment.py | CDDLeiden/DrugEx | train | 70 |
45c282e5451e9b9c2e4ffd94629784853dfa1c92 | [
"log.debug('POST request from user %s to create a new work item' % request.user)\nproj = Project.objects.get(project_number=project_number)\nif not check_project_write_acl(proj, request.user):\n log.debug('Refusing POST request for project %s from user %s' % (project_number, request.user))\n return rc.FORBIDD... | <|body_start_0|>
log.debug('POST request from user %s to create a new work item' % request.user)
proj = Project.objects.get(project_number=project_number)
if not check_project_write_acl(proj, request.user):
log.debug('Refusing POST request for project %s from user %s' % (project_numb... | URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project | WBSListHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WBSListHandler:
"""URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project"""
def create(self, request, project_number):
"""Create a new Work Item"""
<|body_0|>
def read(self, request, project_number):
"""Get a list... | stack_v2_sparse_classes_75kplus_train_068202 | 19,350 | no_license | [
{
"docstring": "Create a new Work Item",
"name": "create",
"signature": "def create(self, request, project_number)"
},
{
"docstring": "Get a list of all Work Items for the project",
"name": "read",
"signature": "def read(self, request, project_number)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030649 | Implement the Python class `WBSListHandler` described below.
Class description:
URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project
Method signatures and docstrings:
- def create(self, request, project_number): Create a new Work Item
- def read(self, request, projec... | Implement the Python class `WBSListHandler` described below.
Class description:
URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project
Method signatures and docstrings:
- def create(self, request, project_number): Create a new Work Item
- def read(self, request, projec... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class WBSListHandler:
"""URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project"""
def create(self, request, project_number):
"""Create a new Work Item"""
<|body_0|>
def read(self, request, project_number):
"""Get a list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WBSListHandler:
"""URI: /api/wbs/%project_number%/ VERBS: GET, POST Returns a list of work items associated with a project"""
def create(self, request, project_number):
"""Create a new Work Item"""
log.debug('POST request from user %s to create a new work item' % request.user)
pro... | the_stack_v2_python_sparse | branches/rest-api-branch/django-project-management/wbs/api_views.py | NhaTrang/django-project-management | train | 0 |
2ec081459688116921fdaf8fccab8274c26377bd | [
"self.root = Node()\nfor word in words:\n insert(self.root, word)\nself.node_list = []",
"complete_found = False\nfor i in range(len(self.node_list) - 1, -1, -1):\n if letter in self.node_list[i].d:\n self.node_list[i] = self.node_list[i].d[letter]\n if self.node_list[i].complete:\n ... | <|body_start_0|>
self.root = Node()
for word in words:
insert(self.root, word)
self.node_list = []
<|end_body_0|>
<|body_start_1|>
complete_found = False
for i in range(len(self.node_list) - 1, -1, -1):
if letter in self.node_list[i].d:
se... | StreamChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.root = Node()
for word in words:
in... | stack_v2_sparse_classes_75kplus_train_068203 | 5,756 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030945 | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | 3a2e75238a333843987c6413ab674a7e985c8c01 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.root = Node()
for word in words:
insert(self.root, word)
self.node_list = []
def query(self, letter):
""":type letter: str :rtype: bool"""
complete_found = False
... | the_stack_v2_python_sparse | coding_practice/tries/stream_of_characters.py | daveboat/interview_prep | train | 2 | |
4964eb35309f007839db58a757a265390428f46c | [
"if compile:\n regex = re.compile(regex)\nmm = regex.findall(line)\nif mm:\n return mm\nelse:\n return 0",
"if compile:\n regex = re.compile(regex)\nmm = regex.match(line)\nif mm != None:\n return mm.groups()\nelse:\n return 0",
"if compile:\n regex = re.compile(regex)\nline = regex.sub(s, ... | <|body_start_0|>
if compile:
regex = re.compile(regex)
mm = regex.findall(line)
if mm:
return mm
else:
return 0
<|end_body_0|>
<|body_start_1|>
if compile:
regex = re.compile(regex)
mm = regex.match(line)
if mm != N... | regular expression functions | Lib | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lib:
"""regular expression functions"""
def FindAll(self, line, regex, compile=0):
"""find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?"""
<|body_0|>
def Match(self, line, regex, compile=0):
"""find regex 'regex' ... | stack_v2_sparse_classes_75kplus_train_068204 | 1,115 | no_license | [
{
"docstring": "find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?",
"name": "FindAll",
"signature": "def FindAll(self, line, regex, compile=0)"
},
{
"docstring": "find regex 'regex' in string 'line' compile: must we compile a regex before, or is ... | 3 | stack_v2_sparse_classes_30k_train_044430 | Implement the Python class `Lib` described below.
Class description:
regular expression functions
Method signatures and docstrings:
- def FindAll(self, line, regex, compile=0): find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?
- def Match(self, line, regex, compile=0)... | Implement the Python class `Lib` described below.
Class description:
regular expression functions
Method signatures and docstrings:
- def FindAll(self, line, regex, compile=0): find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?
- def Match(self, line, regex, compile=0)... | 3cfcae894c165189cc3ff61e27ca284f09e87871 | <|skeleton|>
class Lib:
"""regular expression functions"""
def FindAll(self, line, regex, compile=0):
"""find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?"""
<|body_0|>
def Match(self, line, regex, compile=0):
"""find regex 'regex' ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lib:
"""regular expression functions"""
def FindAll(self, line, regex, compile=0):
"""find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?"""
if compile:
regex = re.compile(regex)
mm = regex.findall(line)
if mm:
... | the_stack_v2_python_sparse | dmerce2/Core/RegExp.py | rbe/dmerce | train | 0 |
3bc45551d5a20eab724921b3ab7f59fbe254264e | [
"self.driver.find_element_by_xpath('//p[text() = \"全部产品\"]').click()\nlogger.info('点击全部产品')\nsleep(1)\nself.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div/div[2]/div[3]/ul/li[2]').click()\nlogger.info('对价格进行升序排序')\nsleep(2)\nself.driver.find_element_by_class_name('shop-logo').click()\nlogger.info('点击0元套餐')\... | <|body_start_0|>
self.driver.find_element_by_xpath('//p[text() = "全部产品"]').click()
logger.info('点击全部产品')
sleep(1)
self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[3]/ul/li[2]').click()
logger.info('对价格进行升序排序')
sleep(2)
self.driver.find_element_... | Test_MobileZhifu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_MobileZhifu:
def test_case01(self):
"""官网移动在微店购买0元产品 :return:"""
<|body_0|>
def test_case02(self):
"""官网移动在微店加入购物车购买0元产品 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver.find_element_by_xpath('//p[text() = "全部产品"]').click()
... | stack_v2_sparse_classes_75kplus_train_068205 | 4,794 | no_license | [
{
"docstring": "官网移动在微店购买0元产品 :return:",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "官网移动在微店加入购物车购买0元产品 :return:",
"name": "test_case02",
"signature": "def test_case02(self)"
}
] | 2 | null | Implement the Python class `Test_MobileZhifu` described below.
Class description:
Implement the Test_MobileZhifu class.
Method signatures and docstrings:
- def test_case01(self): 官网移动在微店购买0元产品 :return:
- def test_case02(self): 官网移动在微店加入购物车购买0元产品 :return: | Implement the Python class `Test_MobileZhifu` described below.
Class description:
Implement the Test_MobileZhifu class.
Method signatures and docstrings:
- def test_case01(self): 官网移动在微店购买0元产品 :return:
- def test_case02(self): 官网移动在微店加入购物车购买0元产品 :return:
<|skeleton|>
class Test_MobileZhifu:
def test_case01(self... | cf92e8e81ceb5cb67217bf36993cf94fe470fd0b | <|skeleton|>
class Test_MobileZhifu:
def test_case01(self):
"""官网移动在微店购买0元产品 :return:"""
<|body_0|>
def test_case02(self):
"""官网移动在微店加入购物车购买0元产品 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_MobileZhifu:
def test_case01(self):
"""官网移动在微店购买0元产品 :return:"""
self.driver.find_element_by_xpath('//p[text() = "全部产品"]').click()
logger.info('点击全部产品')
sleep(1)
self.driver.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[3]/ul/li[2]').click()
logg... | the_stack_v2_python_sparse | hhr/case/mobile_qiantai/test_mobileweidain.py | aixin2000/Test_Scripts | train | 0 | |
9f93c780de2c717e71480575681c32389e263806 | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_neighbor_v4_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_neighbor_v4_by_ids(ids)\n only_main_property = True\n obj_model = Non... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_neighbor_v4_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_neighbor_v4_b... | NeighborV4DBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighborV4DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of NeighborV4's by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new NeighborV4."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_068206 | 12,495 | permissive | [
{
"docstring": "Returns a list of NeighborV4's by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new NeighborV4.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update Nei... | 4 | stack_v2_sparse_classes_30k_train_000683 | Implement the Python class `NeighborV4DBView` described below.
Class description:
Implement the NeighborV4DBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of NeighborV4's by ids ou dict.
- def post(self, request, *args, **kwargs): Create new NeighborV4.
- def p... | Implement the Python class `NeighborV4DBView` described below.
Class description:
Implement the NeighborV4DBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of NeighborV4's by ids ou dict.
- def post(self, request, *args, **kwargs): Create new NeighborV4.
- def p... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class NeighborV4DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of NeighborV4's by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new NeighborV4."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeighborV4DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of NeighborV4's by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_neighbor_v4_by_search(self.search)
objects = obj_model['query_set']
only_main_property = Fals... | the_stack_v2_python_sparse | networkapi/api_neighbor/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
1130bf8e9c89ba311e35e727e60abb9f905eb3d3 | [
"self._gpu_index = gpu_index\nif self._gpu_index is not None:\n if not isinstance(self._gpu_index, str):\n self._gpu_index = str(self._gpu_index)\n os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_index\nprint('Creating session and loading parameters')\nwith tf.Graph().as_default():\n config = tf.Conf... | <|body_start_0|>
self._gpu_index = gpu_index
if self._gpu_index is not None:
if not isinstance(self._gpu_index, str):
self._gpu_index = str(self._gpu_index)
os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_index
print('Creating session and loading parameters... | Classify images to predifined classes. | Predictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Classify images to predifined classes."""
def __init__(self, checkpoint_path, gpu_index=None):
"""Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used. Default None."""
<|body_0|>
def predict(se... | stack_v2_sparse_classes_75kplus_train_068207 | 3,302 | permissive | [
{
"docstring": "Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used. Default None.",
"name": "__init__",
"signature": "def __init__(self, checkpoint_path, gpu_index=None)"
},
{
"docstring": "Predict prediction tensors from inputs te... | 2 | stack_v2_sparse_classes_30k_train_039054 | Implement the Python class `Predictor` described below.
Class description:
Classify images to predifined classes.
Method signatures and docstrings:
- def __init__(self, checkpoint_path, gpu_index=None): Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used... | Implement the Python class `Predictor` described below.
Class description:
Classify images to predifined classes.
Method signatures and docstrings:
- def __init__(self, checkpoint_path, gpu_index=None): Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used... | 02e81961e0a710f2c82db70c06b505e608db61cc | <|skeleton|>
class Predictor:
"""Classify images to predifined classes."""
def __init__(self, checkpoint_path, gpu_index=None):
"""Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used. Default None."""
<|body_0|>
def predict(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
"""Classify images to predifined classes."""
def __init__(self, checkpoint_path, gpu_index=None):
"""Constructor. Args: frozen_inference_graph_path: Path to frozen inference graph. gpu_index: The GPU index to be used. Default None."""
self._gpu_index = gpu_index
if self... | the_stack_v2_python_sparse | Python/AI-ToolBox/computer_vision/image_classification_tf/resnet50_slim_demo1/src/predictor_ckpt.py | Lornatang/DayHR | train | 7 |
9aaaac180142af446bacd842649be82a7963827e | [
"if vals.get('tax_ids'):\n if len(vals.get('tax_ids')[0][2]) > 1:\n raise UserError('A product can only have one tax')\nreturn super(InheritAccountInvoiceLine, self).create(vals)",
"if vals.get('tax_ids'):\n if len(vals.get('tax_ids')[0][2]) > 1:\n raise UserError('A product can only have one ... | <|body_start_0|>
if vals.get('tax_ids'):
if len(vals.get('tax_ids')[0][2]) > 1:
raise UserError('A product can only have one tax')
return super(InheritAccountInvoiceLine, self).create(vals)
<|end_body_0|>
<|body_start_1|>
if vals.get('tax_ids'):
if len(va... | InheritAccountInvoiceLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InheritAccountInvoiceLine:
def create(self, vals):
"""Inheriting the core function, create to validate to stop adding two or more taxes to the product"""
<|body_0|>
def write(self, vals):
"""Inheriting the core function, write to validate to stop adding two or more t... | stack_v2_sparse_classes_75kplus_train_068208 | 1,589 | no_license | [
{
"docstring": "Inheriting the core function, create to validate to stop adding two or more taxes to the product",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "Inheriting the core function, write to validate to stop adding two or more taxes to the product",
"nam... | 2 | stack_v2_sparse_classes_30k_test_001010 | Implement the Python class `InheritAccountInvoiceLine` described below.
Class description:
Implement the InheritAccountInvoiceLine class.
Method signatures and docstrings:
- def create(self, vals): Inheriting the core function, create to validate to stop adding two or more taxes to the product
- def write(self, vals)... | Implement the Python class `InheritAccountInvoiceLine` described below.
Class description:
Implement the InheritAccountInvoiceLine class.
Method signatures and docstrings:
- def create(self, vals): Inheriting the core function, create to validate to stop adding two or more taxes to the product
- def write(self, vals)... | 9de7a2ce6a17d43107ee08085c9f83a525382798 | <|skeleton|>
class InheritAccountInvoiceLine:
def create(self, vals):
"""Inheriting the core function, create to validate to stop adding two or more taxes to the product"""
<|body_0|>
def write(self, vals):
"""Inheriting the core function, write to validate to stop adding two or more t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InheritAccountInvoiceLine:
def create(self, vals):
"""Inheriting the core function, create to validate to stop adding two or more taxes to the product"""
if vals.get('tax_ids'):
if len(vals.get('tax_ids')[0][2]) > 1:
raise UserError('A product can only have one tax'... | the_stack_v2_python_sparse | custom_taxes/models/custom_invoice.py | EshangAllion/cenmetrix_v12 | train | 0 | |
82f5119d049704c2ba64e174c09d482c84228d18 | [
"super(TextCNN, self).__init__()\nself.emb = nn.Embedding(vocab_size, emb_size)\nself.conv = nn.Sequential(nn.Conv2d(in_channels, out_channels, conv_size), nn.ReLU(), nn.MaxPool2d(kernel_size))\nself.fc = nn.Linear(out_channels, num_classes)",
"batch_size = x.shape[0]\nx_emb = self.emb(x)\nx_emb = x_emb.unsqueeze... | <|body_start_0|>
super(TextCNN, self).__init__()
self.emb = nn.Embedding(vocab_size, emb_size)
self.conv = nn.Sequential(nn.Conv2d(in_channels, out_channels, conv_size), nn.ReLU(), nn.MaxPool2d(kernel_size))
self.fc = nn.Linear(out_channels, num_classes)
<|end_body_0|>
<|body_start_1|>
... | TextCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextCNN:
def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_channels=in_channels, out_channels=out_channels, conv_size=conv_size, kernel_size=kernel_size):
"""@doc: TextCNN 模型细节 @author: Alpaca-Man @date: 2021/2/9 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 in_channels: 输入通道 ... | stack_v2_sparse_classes_75kplus_train_068209 | 2,672 | no_license | [
{
"docstring": "@doc: TextCNN 模型细节 @author: Alpaca-Man @date: 2021/2/9 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 in_channels: 输入通道 out_channels: 输出通道 conv_size: 卷积核大小 kernel_size: 池化层核大小 } @return: { }",
"name": "__init__",
"signature": "def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_c... | 2 | stack_v2_sparse_classes_30k_train_016351 | Implement the Python class `TextCNN` described below.
Class description:
Implement the TextCNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_channels=in_channels, out_channels=out_channels, conv_size=conv_size, kernel_size=kernel_size): @doc: TextCNN 模型细节 @... | Implement the Python class `TextCNN` described below.
Class description:
Implement the TextCNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_channels=in_channels, out_channels=out_channels, conv_size=conv_size, kernel_size=kernel_size): @doc: TextCNN 模型细节 @... | 49824925970f0439634dc66a7f19edc512f18a5f | <|skeleton|>
class TextCNN:
def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_channels=in_channels, out_channels=out_channels, conv_size=conv_size, kernel_size=kernel_size):
"""@doc: TextCNN 模型细节 @author: Alpaca-Man @date: 2021/2/9 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 in_channels: 输入通道 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextCNN:
def __init__(self, vocab_size=vocab_size, emb_size=emb_size, in_channels=in_channels, out_channels=out_channels, conv_size=conv_size, kernel_size=kernel_size):
"""@doc: TextCNN 模型细节 @author: Alpaca-Man @date: 2021/2/9 @param: { vocab_size: 单词个数 emb_size: 词嵌入维度 in_channels: 输入通道 out_channels: ... | the_stack_v2_python_sparse | TextCNN/standard/TextCNN.py | Alpaca-Man/NLP-Newcomer | train | 1 | |
8c277ed3f544b4020fc19eb5199408b1f3fa16b8 | [
"db_name = 'student'\nprint('-----学员注册:-----')\nname = input('姓名:').strip()\nschool_id = Util.choose_school()\nif not school_id:\n return\nclass_id = Util.choose_class(school_id)\nif not class_id:\n return\nid = Util.getid(db_name)\nobj = Student(id, name, school_id, class_id)\nUtil.save(db_name, obj)",
"db... | <|body_start_0|>
db_name = 'student'
print('-----学员注册:-----')
name = input('姓名:').strip()
school_id = Util.choose_school()
if not school_id:
return
class_id = Util.choose_class(school_id)
if not class_id:
return
id = Util.getid(db_n... | StudentCtrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentCtrl:
def create_student(mark):
"""5. 创建学员时,选择学校,关联班级 :return:"""
<|body_0|>
def pay_fee(student_id):
"""交学费 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
db_name = 'student'
print('-----学员注册:-----')
name = input('姓... | stack_v2_sparse_classes_75kplus_train_068210 | 1,056 | no_license | [
{
"docstring": "5. 创建学员时,选择学校,关联班级 :return:",
"name": "create_student",
"signature": "def create_student(mark)"
},
{
"docstring": "交学费 :return:",
"name": "pay_fee",
"signature": "def pay_fee(student_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006256 | Implement the Python class `StudentCtrl` described below.
Class description:
Implement the StudentCtrl class.
Method signatures and docstrings:
- def create_student(mark): 5. 创建学员时,选择学校,关联班级 :return:
- def pay_fee(student_id): 交学费 :return: | Implement the Python class `StudentCtrl` described below.
Class description:
Implement the StudentCtrl class.
Method signatures and docstrings:
- def create_student(mark): 5. 创建学员时,选择学校,关联班级 :return:
- def pay_fee(student_id): 交学费 :return:
<|skeleton|>
class StudentCtrl:
def create_student(mark):
"""5. ... | 9ba62048a78dcbf0364aff17bba080954ecd87d6 | <|skeleton|>
class StudentCtrl:
def create_student(mark):
"""5. 创建学员时,选择学校,关联班级 :return:"""
<|body_0|>
def pay_fee(student_id):
"""交学费 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudentCtrl:
def create_student(mark):
"""5. 创建学员时,选择学校,关联班级 :return:"""
db_name = 'student'
print('-----学员注册:-----')
name = input('姓名:').strip()
school_id = Util.choose_school()
if not school_id:
return
class_id = Util.choose_class(school_id... | the_stack_v2_python_sparse | course/ctrl/StudentCtrl.py | leach/python-demo | train | 0 | |
e42279d86caaec807eea2c51576edc1818618277 | [
"if len(s) <= 1:\n return True\nfor i in range(len(s) / 2):\n if s[i] != s[len(s) - i - 1]:\n return False\nreturn True",
"m, n = (len(word1), len(word2))\nif m == 0 or n == 0:\n return 0\ndp = [0] * n\nres = 0\nfor i, a in enumerate(word1):\n cur_max = 1\n for j, b in enumerate(word2):\n ... | <|body_start_0|>
if len(s) <= 1:
return True
for i in range(len(s) / 2):
if s[i] != s[len(s) - i - 1]:
return False
return True
<|end_body_0|>
<|body_start_1|>
m, n = (len(word1), len(word2))
if m == 0 or n == 0:
return 0
... | XString | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XString:
def is_p(self, s):
"""is palindrome type s: string rtype : boolean"""
<|body_0|>
def lcslen(self, word1, word2):
"""longest common substring :type word1: str :type word2: str :rtype: int :return the length of longest common substring, e.g, m('1a2b3c4d', 'a5b... | stack_v2_sparse_classes_75kplus_train_068211 | 6,377 | no_license | [
{
"docstring": "is palindrome type s: string rtype : boolean",
"name": "is_p",
"signature": "def is_p(self, s)"
},
{
"docstring": "longest common substring :type word1: str :type word2: str :rtype: int :return the length of longest common substring, e.g, m('1a2b3c4d', 'a5b6c777d88') return 4 (le... | 4 | stack_v2_sparse_classes_30k_train_016228 | Implement the Python class `XString` described below.
Class description:
Implement the XString class.
Method signatures and docstrings:
- def is_p(self, s): is palindrome type s: string rtype : boolean
- def lcslen(self, word1, word2): longest common substring :type word1: str :type word2: str :rtype: int :return the... | Implement the Python class `XString` described below.
Class description:
Implement the XString class.
Method signatures and docstrings:
- def is_p(self, s): is palindrome type s: string rtype : boolean
- def lcslen(self, word1, word2): longest common substring :type word1: str :type word2: str :rtype: int :return the... | 9e4f6f1a2830bd9aab1bba374c98f0464825d435 | <|skeleton|>
class XString:
def is_p(self, s):
"""is palindrome type s: string rtype : boolean"""
<|body_0|>
def lcslen(self, word1, word2):
"""longest common substring :type word1: str :type word2: str :rtype: int :return the length of longest common substring, e.g, m('1a2b3c4d', 'a5b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XString:
def is_p(self, s):
"""is palindrome type s: string rtype : boolean"""
if len(s) <= 1:
return True
for i in range(len(s) / 2):
if s[i] != s[len(s) - i - 1]:
return False
return True
def lcslen(self, word1, word2):
"""... | the_stack_v2_python_sparse | python_solutions/712.minimum-ascii-delete-sum-for-two-strings.py | h4hany/leetcode | train | 0 | |
fc27b726778212c860cc251142374e17c8da52cd | [
"host = '127.0.0.1'\nuser = 'root'\npassword = '123456'\ndatabase = 'notebook'\nself.db = pymysql.connect(host=host, user=user, password=password, db=database)\nself.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)",
"try:\n self.cursor.execute(sql)\n self.db.commit()\nexcept Exception:\n print... | <|body_start_0|>
host = '127.0.0.1'
user = 'root'
password = '123456'
database = 'notebook'
self.db = pymysql.connect(host=host, user=user, password=password, db=database)
self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)
<|end_body_0|>
<|body_start_1|>
... | MysqlUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MysqlUtil:
def __init__(self):
"""初始化方法,连接数据库"""
<|body_0|>
def insert(self, sql):
"""插入数据库 sql:插入数据库的sql语句"""
<|body_1|>
def fetchone(self, sql):
"""查询数据库:单个结果集 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象"""
<|body_2|>
def fetchall(self, sql... | stack_v2_sparse_classes_75kplus_train_068212 | 3,579 | no_license | [
{
"docstring": "初始化方法,连接数据库",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "插入数据库 sql:插入数据库的sql语句",
"name": "insert",
"signature": "def insert(self, sql)"
},
{
"docstring": "查询数据库:单个结果集 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象",
"name": "fetchone",
"s... | 6 | stack_v2_sparse_classes_30k_train_046461 | Implement the Python class `MysqlUtil` described below.
Class description:
Implement the MysqlUtil class.
Method signatures and docstrings:
- def __init__(self): 初始化方法,连接数据库
- def insert(self, sql): 插入数据库 sql:插入数据库的sql语句
- def fetchone(self, sql): 查询数据库:单个结果集 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- def fetchall(self, sq... | Implement the Python class `MysqlUtil` described below.
Class description:
Implement the MysqlUtil class.
Method signatures and docstrings:
- def __init__(self): 初始化方法,连接数据库
- def insert(self, sql): 插入数据库 sql:插入数据库的sql语句
- def fetchone(self, sql): 查询数据库:单个结果集 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- def fetchall(self, sq... | 77ed974e08b3d6240b591b1d99a23883eab9b8fb | <|skeleton|>
class MysqlUtil:
def __init__(self):
"""初始化方法,连接数据库"""
<|body_0|>
def insert(self, sql):
"""插入数据库 sql:插入数据库的sql语句"""
<|body_1|>
def fetchone(self, sql):
"""查询数据库:单个结果集 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象"""
<|body_2|>
def fetchall(self, sql... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MysqlUtil:
def __init__(self):
"""初始化方法,连接数据库"""
host = '127.0.0.1'
user = 'root'
password = '123456'
database = 'notebook'
self.db = pymysql.connect(host=host, user=user, password=password, db=database)
self.cursor = self.db.cursor(cursor=pymysql.cursor... | the_stack_v2_python_sparse | my_project/notebook/mysql_util.py | wangleiliugang/myproject | train | 0 | |
869f8308c3186062559c250212df88ecd969d574 | [
"first = second = float('inf')\nfor n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\nreturn False",
"ln = len(nums)\nif ln < 3:\n return False\nminr = nums[0]\nmintemp = nums[0]\nmax1 = -2147483648\nmax2 = -2147483648\nfor i in nums:\... | <|body_start_0|>
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False
<|end_body_0|>
<|body_start_1|>
ln = len(nums)
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
first = second = float('inf')
... | stack_v2_sparse_classes_75kplus_train_068213 | 1,801 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet2",
"signature": "def increasingTriplet2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet2(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet2(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True... | the_stack_v2_python_sparse | 中级算法/increasingTriplet.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
a7b25973013730ad3e99ad9bc22ef843e64cb1c7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosVppEBook()",
"from .managed_e_book import ManagedEBook\nfrom .managed_e_book import ManagedEBook\nfields: Dict[str, Callable[[Any], None]] = {'appleId': lambda n: setattr(self, 'apple_id', n.get_str_value()), 'genres': lambda n: set... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosVppEBook()
<|end_body_0|>
<|body_start_1|>
from .managed_e_book import ManagedEBook
from .managed_e_book import ManagedEBook
fields: Dict[str, Callable[[Any], None]] = {'apple... | A class containing the properties for iOS Vpp eBook. | IosVppEBook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosVppEBook:
"""A class containing the properties for iOS Vpp eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosVppEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_75kplus_train_068214 | 3,718 | 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: IosVppEBook",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | stack_v2_sparse_classes_30k_train_034046 | Implement the Python class `IosVppEBook` described below.
Class description:
A class containing the properties for iOS Vpp eBook.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosVppEBook: Creates a new instance of the appropriate class based on discr... | Implement the Python class `IosVppEBook` described below.
Class description:
A class containing the properties for iOS Vpp eBook.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosVppEBook: Creates a new instance of the appropriate class based on discr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosVppEBook:
"""A class containing the properties for iOS Vpp eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosVppEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IosVppEBook:
"""A class containing the properties for iOS Vpp eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosVppEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the dis... | the_stack_v2_python_sparse | msgraph/generated/models/ios_vpp_e_book.py | microsoftgraph/msgraph-sdk-python | train | 135 |
9fde606ade16252bad5d05584853b2c887c4def4 | [
"data = {'model_id': self._id, 'queries_dataset_id': queries_dataset_id, 'queries_dataset_content_column': queries_dataset_content_column, 'top_k': top_k}\nif matching_id_description_column:\n data['queries_dataset_matching_id_description_column'] = matching_id_description_column\nendpoint = '/usecase-versions/{... | <|body_start_0|>
data = {'model_id': self._id, 'queries_dataset_id': queries_dataset_id, 'queries_dataset_content_column': queries_dataset_content_column, 'top_k': top_k}
if matching_id_description_column:
data['queries_dataset_matching_id_description_column'] = matching_id_description_colum... | TextSimilarityModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSimilarityModel:
def _predict_bulk(self, queries_dataset_id: str, queries_dataset_content_column: str, top_k: int, matching_id_description_column: str=None):
"""(Util method) Private method used to handle bulk predict. .. note:: This function should not be used directly. Use predict_... | stack_v2_sparse_classes_75kplus_train_068215 | 22,476 | permissive | [
{
"docstring": "(Util method) Private method used to handle bulk predict. .. note:: This function should not be used directly. Use predict_from_* methods instead. Args: queries_dataset_id (str): Unique id of the quries dataset to predict with queries_dataset_content_column (str): Content queries column name que... | 2 | stack_v2_sparse_classes_30k_train_048887 | Implement the Python class `TextSimilarityModel` described below.
Class description:
Implement the TextSimilarityModel class.
Method signatures and docstrings:
- def _predict_bulk(self, queries_dataset_id: str, queries_dataset_content_column: str, top_k: int, matching_id_description_column: str=None): (Util method) P... | Implement the Python class `TextSimilarityModel` described below.
Class description:
Implement the TextSimilarityModel class.
Method signatures and docstrings:
- def _predict_bulk(self, queries_dataset_id: str, queries_dataset_content_column: str, top_k: int, matching_id_description_column: str=None): (Util method) P... | 0860c931e2b466ac4be910350890085111ae32ce | <|skeleton|>
class TextSimilarityModel:
def _predict_bulk(self, queries_dataset_id: str, queries_dataset_content_column: str, top_k: int, matching_id_description_column: str=None):
"""(Util method) Private method used to handle bulk predict. .. note:: This function should not be used directly. Use predict_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextSimilarityModel:
def _predict_bulk(self, queries_dataset_id: str, queries_dataset_content_column: str, top_k: int, matching_id_description_column: str=None):
"""(Util method) Private method used to handle bulk predict. .. note:: This function should not be used directly. Use predict_from_* methods... | the_stack_v2_python_sparse | previsionio/model.py | FrancoisA-prevision/prevision-python | train | 0 | |
91022a097e5beb93b508dc20e2867e685242402f | [
"country_id = request.get('id', None)\nname = request.get('name', None)\nreturn Countries.get(country_id, name)",
"city_id = request.get('id', None)\nname = request.get('name', None)\ncountry_id = request.get('country_id', None)\nreturn Cities.get(country_id, city_id, name)"
] | <|body_start_0|>
country_id = request.get('id', None)
name = request.get('name', None)
return Countries.get(country_id, name)
<|end_body_0|>
<|body_start_1|>
city_id = request.get('id', None)
name = request.get('name', None)
country_id = request.get('country_id', None)
... | DefaultController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultController:
def get_country(cls, request: Request, **kwargs):
"""Retreiving country"""
<|body_0|>
def get_city(cls, request: Request, **kwargs):
"""Retreiving city"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
country_id = request.get('id',... | stack_v2_sparse_classes_75kplus_train_068216 | 734 | no_license | [
{
"docstring": "Retreiving country",
"name": "get_country",
"signature": "def get_country(cls, request: Request, **kwargs)"
},
{
"docstring": "Retreiving city",
"name": "get_city",
"signature": "def get_city(cls, request: Request, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007857 | Implement the Python class `DefaultController` described below.
Class description:
Implement the DefaultController class.
Method signatures and docstrings:
- def get_country(cls, request: Request, **kwargs): Retreiving country
- def get_city(cls, request: Request, **kwargs): Retreiving city | Implement the Python class `DefaultController` described below.
Class description:
Implement the DefaultController class.
Method signatures and docstrings:
- def get_country(cls, request: Request, **kwargs): Retreiving country
- def get_city(cls, request: Request, **kwargs): Retreiving city
<|skeleton|>
class Defaul... | 973418f5a4e161d9ac35a09ec094ff024d079310 | <|skeleton|>
class DefaultController:
def get_country(cls, request: Request, **kwargs):
"""Retreiving country"""
<|body_0|>
def get_city(cls, request: Request, **kwargs):
"""Retreiving city"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultController:
def get_country(cls, request: Request, **kwargs):
"""Retreiving country"""
country_id = request.get('id', None)
name = request.get('name', None)
return Countries.get(country_id, name)
def get_city(cls, request: Request, **kwargs):
"""Retreiving c... | the_stack_v2_python_sparse | geo/controllers.py | ayurjev/esblng | train | 0 | |
54994d641d096e07f05a7aa1dc762501eb13518a | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or list_dictionaries == []:\n return '[]'\nreturn json.dumps(list_dictionaries)",
"if list_objs is None or list_objs == []:\n new_list = []\nelse:\n new_list = [item... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or list_dictionaries == []:
return '[]'
return json.dumps(list_dictionar... | Class Base | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Class Base"""
def __init__(self, id=None):
"""Class constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""json to string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save to file"""
<|body_2|>
def fro... | stack_v2_sparse_classes_75kplus_train_068217 | 1,802 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "json to string",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "save to file",
"name": "save_to_file",
... | 6 | stack_v2_sparse_classes_30k_train_014475 | Implement the Python class `Base` described below.
Class description:
Class Base
Method signatures and docstrings:
- def __init__(self, id=None): Class constructor
- def to_json_string(list_dictionaries): json to string
- def save_to_file(cls, list_objs): save to file
- def from_json_string(json_string): from json st... | Implement the Python class `Base` described below.
Class description:
Class Base
Method signatures and docstrings:
- def __init__(self, id=None): Class constructor
- def to_json_string(list_dictionaries): json to string
- def save_to_file(cls, list_objs): save to file
- def from_json_string(json_string): from json st... | 8e6bb4505f7fecee8fdc9e3d29b04fd7c7abc044 | <|skeleton|>
class Base:
"""Class Base"""
def __init__(self, id=None):
"""Class constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""json to string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save to file"""
<|body_2|>
def fro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Class Base"""
def __init__(self, id=None):
"""Class constructor"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
"""json to string"""
... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | nicolastobon09/holbertonschool-higher_level_programming | train | 0 |
357b28eae8cfa979a6300fda9aa56c6aedf9d4a9 | [
"super().__init__()\nn_blocks = len(channels) - 1\nif type(kernel_size) is not list:\n kernel_size = [kernel_size] * n_blocks\nif stride is None:\n stride = kernel_size\nelif type(stride) is not list:\n stride = [stride] * n_blocks\nif type(nonlinear) is not list:\n nonlinear = [nonlinear] * n_blocks\ns... | <|body_start_0|>
super().__init__()
n_blocks = len(channels) - 1
if type(kernel_size) is not list:
kernel_size = [kernel_size] * n_blocks
if stride is None:
stride = kernel_size
elif type(stride) is not list:
stride = [stride] * n_blocks
... | Decoder2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder2d:
def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> dilated <bool> ... | stack_v2_sparse_classes_75kplus_train_068218 | 38,203 | no_license | [
{
"docstring": "Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> dilated <bool> nonlinear <str> or <list<str>>",
"name": "__init__",
"signature": "def __init__(self, channels, kernel_size, stride=None, dilated=False, sepa... | 2 | null | Implement the Python class `Decoder2d` described below.
Class description:
Implement the Decoder2d class.
Method signatures and docstrings:
- def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, bias=False, nonlinear='relu', eps=EPS): Args: channels <list<int>> kernel_size <tuple<int... | Implement the Python class `Decoder2d` described below.
Class description:
Implement the Decoder2d class.
Method signatures and docstrings:
- def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, bias=False, nonlinear='relu', eps=EPS): Args: channels <list<int>> kernel_size <tuple<int... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class Decoder2d:
def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> dilated <bool> ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder2d:
def __init__(self, channels, kernel_size, stride=None, dilated=False, separable=False, bias=False, nonlinear='relu', eps=EPS):
"""Args: channels <list<int>> kernel_size <tuple<int,int>> or <list<tuple<int,int>>> stride <tuple<int,int>> or <list<tuple<int,int>>> dilated <bool> nonlinear <str... | the_stack_v2_python_sparse | src/models/cunet.py | shelly-tang/DNN-based_source_separation | train | 0 | |
d2ee2110825937d5f5ba7031954c137f235f8100 | [
"if net is None:\n raise ValueError('Please provide input value for net. Currently set to None.')\nself.net = net\nself.nets = {'net': self.net}\nself.opt = Adam(self.net.parameters(), lr=lr)",
"_, actions = self.net.get_action(state)\nif self.device == 'gpu':\n actions = actions.cpu().numpy()\nelse:\n a... | <|body_start_0|>
if net is None:
raise ValueError('Please provide input value for net. Currently set to None.')
self.net = net
self.nets = {'net': self.net}
self.opt = Adam(self.net.parameters(), lr=lr)
<|end_body_0|>
<|body_start_1|>
_, actions = self.net.get_action... | ImitationAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `ne... | stack_v2_sparse_classes_75kplus_train_068219 | 3,103 | permissive | [
{
"docstring": "Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `net` is not specified",
"name": "initialize",
"signature": "def initialize(self, net: Union[BaseNetwork,... | 3 | stack_v2_sparse_classes_30k_val_000646 | Implement the Python class `ImitationAgent` described below.
Class description:
Implement the ImitationAgent class.
Method signatures and docstrings:
- def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None: Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwo... | Implement the Python class `ImitationAgent` described below.
Class description:
Implement the ImitationAgent class.
Method signatures and docstrings:
- def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None: Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwo... | 6aecbe414f0032514ffb4206200596b8c3860b58 | <|skeleton|>
class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImitationAgent:
def initialize(self, net: Union[BaseNetwork, None]=None, lr: float=0.001) -> None:
"""Initialization function for a simple BC agent. Parameters ---------- net: BaseNetwork, default=None policy network lr: float, default=0.001 learning rate Raises ------ ValueError: if `net` is not spec... | the_stack_v2_python_sparse | ilpyt/agents/imitation_agent.py | mitre/ilpyt | train | 11 | |
74ba213d4fab33b0a7cfabe35671d93818512ca4 | [
"self.s_g = s_g\nself.s_s = s_s\nself.h = h\nself.alpha = alpha\nself.ratio_s_g = ratio_s_g",
"assert len(f1.shape) == 1, 'input must be 1d ndarray'\nassert len(f2.shape) == 1, 'input must be 1d ndarray'\nassert f1.shape == f2.shape\nn_trial = len(f1)\nf1_ = np.tile(f1, (n_samp, 1)) + self.s_s * np.random.randn(n... | <|body_start_0|>
self.s_g = s_g
self.s_s = s_s
self.h = h
self.alpha = alpha
self.ratio_s_g = ratio_s_g
<|end_body_0|>
<|body_start_1|>
assert len(f1.shape) == 1, 'input must be 1d ndarray'
assert len(f2.shape) == 1, 'input must be 1d ndarray'
assert f1.s... | RecencyModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecencyModel:
def __init__(self, s_g, s_s, alpha=0.0, h=0.0, ratio_s_g=1):
"""Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussians sharing the same variance :param s_s: std of likelihood :param alpha: ... | stack_v2_sparse_classes_75kplus_train_068220 | 11,426 | no_license | [
{
"docstring": "Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussians sharing the same variance :param s_s: std of likelihood :param alpha: ratio between gaussians",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_039838 | Implement the Python class `RecencyModel` described below.
Class description:
Implement the RecencyModel class.
Method signatures and docstrings:
- def __init__(self, s_g, s_s, alpha=0.0, h=0.0, ratio_s_g=1): Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture a... | Implement the Python class `RecencyModel` described below.
Class description:
Implement the RecencyModel class.
Method signatures and docstrings:
- def __init__(self, s_g, s_s, alpha=0.0, h=0.0, ratio_s_g=1): Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture a... | 2a05aa98b501c8633e1fe2baf611d137740709de | <|skeleton|>
class RecencyModel:
def __init__(self, s_g, s_s, alpha=0.0, h=0.0, ratio_s_g=1):
"""Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussians sharing the same variance :param s_s: std of likelihood :param alpha: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecencyModel:
def __init__(self, s_g, s_s, alpha=0.0, h=0.0, ratio_s_g=1):
"""Constructor :param s_g: std of gaussian part of unigauss :param h: weight of flat prior in unigauss mixture assuming unnormalized gaussians sharing the same variance :param s_s: std of likelihood :param alpha: ratio between ... | the_stack_v2_python_sparse | model/simple_model.py | ItayLieder/GMM_simulations | train | 0 | |
df51ff3770f8f8efb69a2c494e756367345ae5c9 | [
"self.rel = ini_relevance(case_path, 'relevance')\nself.relevance = ini_request(case_dict, case_path, self.rel)\nreturn (self.relevance, self.rel)",
"self.relevance = setupTest.setupTest(relevance_path, case_data, setupClass)\napi_send_check(case_data, case_dict, case_path, self.relevance)\ntime.sleep(10)"
] | <|body_start_0|>
self.rel = ini_relevance(case_path, 'relevance')
self.relevance = ini_request(case_dict, case_path, self.rel)
return (self.relevance, self.rel)
<|end_body_0|>
<|body_start_1|>
self.relevance = setupTest.setupTest(relevance_path, case_data, setupClass)
api_send_c... | TestProject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProject:
def setupClass(self):
""":rel: 获取关联文件得到的字典 :return:"""
<|body_0|>
def test_project(self, case_data, setupClass):
"""测试接口为:parkinside :param case_data: 测试用例 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rel = ini_relevanc... | stack_v2_sparse_classes_75kplus_train_068221 | 2,423 | no_license | [
{
"docstring": ":rel: 获取关联文件得到的字典 :return:",
"name": "setupClass",
"signature": "def setupClass(self)"
},
{
"docstring": "测试接口为:parkinside :param case_data: 测试用例 :return:",
"name": "test_project",
"signature": "def test_project(self, case_data, setupClass)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031632 | Implement the Python class `TestProject` described below.
Class description:
Implement the TestProject class.
Method signatures and docstrings:
- def setupClass(self): :rel: 获取关联文件得到的字典 :return:
- def test_project(self, case_data, setupClass): 测试接口为:parkinside :param case_data: 测试用例 :return: | Implement the Python class `TestProject` described below.
Class description:
Implement the TestProject class.
Method signatures and docstrings:
- def setupClass(self): :rel: 获取关联文件得到的字典 :return:
- def test_project(self, case_data, setupClass): 测试接口为:parkinside :param case_data: 测试用例 :return:
<|skeleton|>
class TestP... | 7a2f5b2292b73fed5e27cfdfb6e866896f1e7dc1 | <|skeleton|>
class TestProject:
def setupClass(self):
""":rel: 获取关联文件得到的字典 :return:"""
<|body_0|>
def test_project(self, case_data, setupClass):
"""测试接口为:parkinside :param case_data: 测试用例 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProject:
def setupClass(self):
""":rel: 获取关联文件得到的字典 :return:"""
self.rel = ini_relevance(case_path, 'relevance')
self.relevance = ini_request(case_dict, case_path, self.rel)
return (self.relevance, self.rel)
def test_project(self, case_data, setupClass):
"""测试接... | the_stack_v2_python_sparse | practice/testcases/test_case.py | anqianqi5227/apiAutoTest | train | 0 | |
427a77aab7bee7ca1fc1aa9d8b5126cc4d11d290 | [
"parser.add_argument('--player', nargs=1, help='Player')\nparser.add_argument('--contest', nargs=1, help='Contest ID', type=int)\nparser.add_argument('--after-date', nargs=1, help='After date', type=convert_to_date)",
"players = Player.objects.all()\ncontest_id = None\nafter_date = None\nif 'player' in opts and o... | <|body_start_0|>
parser.add_argument('--player', nargs=1, help='Player')
parser.add_argument('--contest', nargs=1, help='Contest ID', type=int)
parser.add_argument('--after-date', nargs=1, help='After date', type=convert_to_date)
<|end_body_0|>
<|body_start_1|>
players = Player.objects.... | A command which loads checkins for a player or many players for a given contest. | Command | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which t... | stack_v2_sparse_classes_75kplus_train_068222 | 2,490 | permissive | [
{
"docstring": "There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which to filter the results",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Primarily call... | 2 | stack_v2_sparse_classes_30k_train_033907 | Implement the Python class `Command` described below.
Class description:
A command which loads checkins for a player or many players for a given contest.
Method signatures and docstrings:
- def add_arguments(self, parser): There are three optional arguments for the command: --player: the user name of the player --con... | Implement the Python class `Command` described below.
Class description:
A command which loads checkins for a player or many players for a given contest.
Method signatures and docstrings:
- def add_arguments(self, parser): There are three optional arguments for the command: --player: the user name of the player --con... | 96af46ad946e63736f9924cb3b966b0d597254f5 | <|skeleton|>
class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""A command which loads checkins for a player or many players for a given contest."""
def add_arguments(self, parser):
"""There are three optional arguments for the command: --player: the user name of the player --contest: the Contest ID --after-date: The date after which to filter the ... | the_stack_v2_python_sparse | beers/management/commands/load_checkins.py | nvembar/onehundredbeers | train | 1 |
d59b7a5f85c6a06f0deaf1343ac2b35a3fdd1997 | [
"self.num_units = num_units\nself.kernel_size = kernel_size\nself.dilation_rate = dilation_rate",
"with tf.variable_scope(scope or type(self).__name__):\n input_dim = int(inputs.get_shape()[2])\n stddev = 1 / input_dim ** 0.5\n w = tf.get_variable('filter', [self.kernel_size, input_dim, self.num_units], ... | <|body_start_0|>
self.num_units = num_units
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(scope or type(self).__name__):
input_dim = int(inputs.get_shape()[2])
stddev = 1 / input_dim ** 0.... | a 1-D atrous convolutional layer | AConv1dLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_75kplus_train_068223 | 11,183 | permissive | [
{
"docstring": "constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation",
"name": "__init__",
"signature": "def __init__(self, num_units, kernel_size, dilation_rate)"
},
{
"docstring": "Create the variables and do the forward co... | 2 | stack_v2_sparse_classes_30k_train_003655 | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | fb530cf617ff86fe8a249d4582dfe90a303da295 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
self.num_units = num_units
self.kernel_... | the_stack_v2_python_sparse | nabu/neuralnetworks/classifiers/layer.py | DavidKarlas/nabu | train | 1 |
14f73d5150c56664f4dbad550b85e2903b6401db | [
"super(GAN, self).__init__(name=name, **kwargs)\nself.add_module('G', generator)\nself.add_module('D', discriminator)",
"y_hat = self.G(x)\nc = self.D(y, y_hat)\nreturn (c, y_hat)"
] | <|body_start_0|>
super(GAN, self).__init__(name=name, **kwargs)
self.add_module('G', generator)
self.add_module('D', discriminator)
<|end_body_0|>
<|body_start_1|>
y_hat = self.G(x)
c = self.D(y, y_hat)
return (c, y_hat)
<|end_body_1|>
| A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Methods ------- forward(x, y) returns the discriminator results for a a ... | GAN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAN:
"""A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Methods ------- forward(x, y) returns the... | stack_v2_sparse_classes_75kplus_train_068224 | 3,966 | permissive | [
{
"docstring": "Parameters ---------- generator : torch.nn.Module the generator network discriminator : torch.nn.Module the discriminator network name : str (optional) the name of the module (default is 'GAN') kwargs : ... the other parameters of the Model class",
"name": "__init__",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_003069 | Implement the Python class `GAN` described below.
Class description:
A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Me... | Implement the Python class `GAN` described below.
Class description:
A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Me... | 2615b66dd4addfd5c03d9d91a24c7da414294308 | <|skeleton|>
class GAN:
"""A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Methods ------- forward(x, y) returns the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GAN:
"""A class representing a generic GAN model Attributes ---------- G : torch.nn.Module the generator network D : torch.nn.Module the discriminator network name : str the name of the model device : str or torch.device the device to store the tensors to Methods ------- forward(x, y) returns the discriminato... | the_stack_v2_python_sparse | ACME/model/gan.py | mauriziokovacic/ACME | train | 3 |
94bd415afe599bc22a4a19bd7514cd9c2b5e8c83 | [
"if not root:\n return 0\nqueue = collections.deque()\nqueue.append(root)\ncount = 1\nwhile queue:\n for _ in range(len(queue)):\n root = queue.popleft()\n if not root.left and (not root.right):\n return count\n if root.left:\n queue.append(root.left)\n if roo... | <|body_start_0|>
if not root:
return 0
queue = collections.deque()
queue.append(root)
count = 1
while queue:
for _ in range(len(queue)):
root = queue.popleft()
if not root.left and (not root.right):
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历,遇到叶子节点则返回高度"""
<|body_0|>
def minDepth2(self, root: TreeNode) -> int:
"""思路... | stack_v2_sparse_classes_75kplus_train_068225 | 2,229 | no_license | [
{
"docstring": "执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历,遇到叶子节点则返回高度",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "思路:递归 1、如果节点空,返回深度为0 2、如果左子树为空,则遍历... | 2 | stack_v2_sparse_classes_30k_train_020975 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历,遇到叶子节点则返回高度"""
<|body_0|>
def minDepth2(self, root: TreeNode) -> int:
"""思路... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""执行用时 :52 ms, 在所有 Python3 提交中击败了80.43%的用户 内存消耗 :14.9 MB, 在所有 Python3 提交中击败了12.50%的用户 思路: 1、树的最小深度指的是,从根节点到叶子节点的高度 2、叶子节点即左右子节点都为空 3、层次遍历,遇到叶子节点则返回高度"""
if not root:
return 0
queue = collections.deque()
queue.app... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/111. Minimum Depth of Binary Tree.py | yiming1012/MyLeetCode | train | 2 | |
b7df4131a6e3d10a4db93c4f6f4e75ae1f4f2577 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | ClusterManagerServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetCluster(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def UpdateClusterConfig(self, request, context):
"""Missing as... | stack_v2_sparse_classes_75kplus_train_068226 | 7,158 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetCluster",
"signature": "def GetCluster(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "UpdateClusterConfig",
"signature": "def UpdateClus... | 3 | null | Implement the Python class `ClusterManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetCluster(self, request, context): Missing associated documentation comment in .proto file.
- def UpdateClusterConfig(self, request,... | Implement the Python class `ClusterManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetCluster(self, request, context): Missing associated documentation comment in .proto file.
- def UpdateClusterConfig(self, request,... | 148c65ff1f8c04e36416cb378f924bb904cdbe92 | <|skeleton|>
class ClusterManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetCluster(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def UpdateClusterConfig(self, request, context):
"""Missing as... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetCluster(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented... | the_stack_v2_python_sparse | src/api/public/cloudapipb/cloudapi_pb2_grpc.py | alejandrodnm/pixie | train | 0 |
97f609308acef6f319d15ca528eb04389b2f4d44 | [
"s = ''\nqueue = [root]\nwhile queue:\n node = queue.pop(0)\n if node:\n s += str(node.val)\n queue.append(node.left)\n queue.append(node.right)\n else:\n s += '#'\n s += ' '\nreturn s",
"s = data.split(',')\nif s[0] == '#':\n return None\nroot = TreeNode(int(s[0]))\nque... | <|body_start_0|>
s = ''
queue = [root]
while queue:
node = queue.pop(0)
if node:
s += str(node.val)
queue.append(node.left)
queue.append(node.right)
else:
s += '#'
s += ' '
ret... | 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_068227 | 4,066 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_040927 | 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:... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|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"""
s = ''
queue = [root]
while queue:
node = queue.pop(0)
if node:
s += str(node.val)
queue.append(node.left)
... | the_stack_v2_python_sparse | leetcode/4_二叉树专题/10_二叉树的序列化与反序列化.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
204263753ff0358624717b3da38a0ffed11c2464 | [
"try:\n return check_single_linear_var(delta.expr, not_ctx)\nexcept AssertionError:\n return False",
"affine_list = extract_coefficients_from_affine(delta.expr, {(var.name, var.uid) for var in not_ctx})\nconstant = affine_list.get(('__const__', -1), Const(0))\nonly_var = [(name, uid) for name, uid in affine... | <|body_start_0|>
try:
return check_single_linear_var(delta.expr, not_ctx)
except AssertionError:
return False
<|end_body_0|>
<|body_start_1|>
affine_list = extract_coefficients_from_affine(delta.expr, {(var.name, var.uid) for var in not_ctx})
constant = affine_li... | Handles expressons of the form Delta(x + c). | ConstantAxisHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstantAxisHandler:
"""Handles expressons of the form Delta(x + c)."""
def can_rewrite(delta, not_ctx=set()):
"""Checks the delta expression is a TegVar and a constant."""
<|body_0|>
def rewrite(delta, not_ctx=set()):
"""Define a change of varibles so that Delta... | stack_v2_sparse_classes_75kplus_train_068228 | 2,004 | no_license | [
{
"docstring": "Checks the delta expression is a TegVar and a constant.",
"name": "can_rewrite",
"signature": "def can_rewrite(delta, not_ctx=set())"
},
{
"docstring": "Define a change of varibles so that Delta(x + c) becomes Delta(y).",
"name": "rewrite",
"signature": "def rewrite(delta... | 2 | null | Implement the Python class `ConstantAxisHandler` described below.
Class description:
Handles expressons of the form Delta(x + c).
Method signatures and docstrings:
- def can_rewrite(delta, not_ctx=set()): Checks the delta expression is a TegVar and a constant.
- def rewrite(delta, not_ctx=set()): Define a change of v... | Implement the Python class `ConstantAxisHandler` described below.
Class description:
Handles expressons of the form Delta(x + c).
Method signatures and docstrings:
- def can_rewrite(delta, not_ctx=set()): Checks the delta expression is a TegVar and a constant.
- def rewrite(delta, not_ctx=set()): Define a change of v... | d9b302ed4d0b07dfa880f504275f92e6803641a8 | <|skeleton|>
class ConstantAxisHandler:
"""Handles expressons of the form Delta(x + c)."""
def can_rewrite(delta, not_ctx=set()):
"""Checks the delta expression is a TegVar and a constant."""
<|body_0|>
def rewrite(delta, not_ctx=set()):
"""Define a change of varibles so that Delta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstantAxisHandler:
"""Handles expressons of the form Delta(x + c)."""
def can_rewrite(delta, not_ctx=set()):
"""Checks the delta expression is a TegVar and a constant."""
try:
return check_single_linear_var(delta.expr, not_ctx)
except AssertionError:
retu... | the_stack_v2_python_sparse | teg/derivs/edge/handlers/single_axis.py | WWYiii/Teg | train | 0 |
c006e85e62c03a211bdaa96972474d60a7560077 | [
"privilege = win32security.LookupPrivilegeValue(None, 'SeSystemEnvironmentPrivilege')\ntoken = win32security.OpenProcessToken(win32process.GetCurrentProcess(), win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES)\nwin32security.AdjustTokenPrivileges(token, False, [(privilege, win32security.SE_PRIVILEGE... | <|body_start_0|>
privilege = win32security.LookupPrivilegeValue(None, 'SeSystemEnvironmentPrivilege')
token = win32security.OpenProcessToken(win32process.GetCurrentProcess(), win32security.TOKEN_READ | win32security.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(token, False, [(pri... | Class to interact with firmware variables. | FirmwareVariables | [
"BSD-2-Clause-Patent"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirmwareVariables:
"""Class to interact with firmware variables."""
def __init__(self):
"""Constructor."""
<|body_0|>
def get_variable(self, name, guid):
"""Gets a firmware variable. Args: name (str): Name of the variable to get guid (str): GUID of the variable t... | stack_v2_sparse_classes_75kplus_train_068229 | 19,788 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Gets a firmware variable. Args: name (str): Name of the variable to get guid (str): GUID of the variable to get Returns: The value of the variable",
"name": "get_variable",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_012166 | Implement the Python class `FirmwareVariables` described below.
Class description:
Class to interact with firmware variables.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def get_variable(self, name, guid): Gets a firmware variable. Args: name (str): Name of the variable to get guid (str): G... | Implement the Python class `FirmwareVariables` described below.
Class description:
Class to interact with firmware variables.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def get_variable(self, name, guid): Gets a firmware variable. Args: name (str): Name of the variable to get guid (str): G... | 1c397b5ad9ced5820cdcfa63dfea941bf9dabab6 | <|skeleton|>
class FirmwareVariables:
"""Class to interact with firmware variables."""
def __init__(self):
"""Constructor."""
<|body_0|>
def get_variable(self, name, guid):
"""Gets a firmware variable. Args: name (str): Name of the variable to get guid (str): GUID of the variable t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirmwareVariables:
"""Class to interact with firmware variables."""
def __init__(self):
"""Constructor."""
privilege = win32security.LookupPrivilegeValue(None, 'SeSystemEnvironmentPrivilege')
token = win32security.OpenProcessToken(win32process.GetCurrentProcess(), win32security.TO... | the_stack_v2_python_sparse | edk2toolext/windows/secureboot/secureboot_audit.py | tianocore/edk2-pytool-extensions | train | 48 |
3bd0351821970c475d87327494d672eeaa24358b | [
"if sys.version_info.major >= 3:\n if isinstance(recipients, abc.KeysView):\n recipients = [x for x in recipients]\nif isinstance(recipients, dict):\n recipients = [x for x in recipients]\nif not isinstance(recipients, list):\n recipients = recipients.split(',')\nif not len(recipients):\n raise V... | <|body_start_0|>
if sys.version_info.major >= 3:
if isinstance(recipients, abc.KeysView):
recipients = [x for x in recipients]
if isinstance(recipients, dict):
recipients = [x for x in recipients]
if not isinstance(recipients, list):
recipients... | ToolsOSD | [
"EFL-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_75kplus_train_068230 | 12,939 | permissive | [
{
"docstring": "Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())",
"name": "get_message_recipientgroups",
"signature": "def get_message_recipientgroups(bot... | 3 | stack_v2_sparse_classes_30k_train_028014 | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | Implement the Python class `ToolsOSD` described below.
Class description:
Implement the ToolsOSD class.
Method signatures and docstrings:
- def get_message_recipientgroups(bot, recipients, text_method): Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a com... | 816dddc88943b9194f3f0aa6558759eedd585343 | <|skeleton|>
class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ToolsOSD:
def get_message_recipientgroups(bot, recipients, text_method):
"""Split recipients into groups based on server capabilities. This defaults to 4 Input can be * unicode string * a comma-seperated unicode string * list * dict_keys handy for list(bot.channels.keys())"""
if sys.version_in... | the_stack_v2_python_sparse | sopel_modules/SpiceBot/osd.py | SpiceBot/SpiceBot | train | 1 | |
6d002536f47944e1e102818008de788c339f2e37 | [
"with open(filename, 'rb') as reader:\n logger.info('Importing file %s', filename)\n timer = Timer()\n reader = csv.reader(reader)\n titles = reader.next()\n all_records = []\n for row in reader:\n row = self.uniform(row, titles)\n if row:\n all_records.append(row)\n se... | <|body_start_0|>
with open(filename, 'rb') as reader:
logger.info('Importing file %s', filename)
timer = Timer()
reader = csv.reader(reader)
titles = reader.next()
all_records = []
for row in reader:
row = self.uniform(row, ... | Original data was saved in CSV file. | MixinFromCSV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
<|body_0|>
def init_db(self, folder):
"""Refresh the source folder to check in new data"""
<|body_1|>
def refresh(self, folder):
... | stack_v2_sparse_classes_75kplus_train_068231 | 24,895 | no_license | [
{
"docstring": "Import a csv file",
"name": "import_csv",
"signature": "def import_csv(self, filename)"
},
{
"docstring": "Refresh the source folder to check in new data",
"name": "init_db",
"signature": "def init_db(self, folder)"
},
{
"docstring": "Refresh the source folder to ... | 3 | stack_v2_sparse_classes_30k_train_037214 | Implement the Python class `MixinFromCSV` described below.
Class description:
Original data was saved in CSV file.
Method signatures and docstrings:
- def import_csv(self, filename): Import a csv file
- def init_db(self, folder): Refresh the source folder to check in new data
- def refresh(self, folder): Refresh the ... | Implement the Python class `MixinFromCSV` described below.
Class description:
Original data was saved in CSV file.
Method signatures and docstrings:
- def import_csv(self, filename): Import a csv file
- def init_db(self, folder): Refresh the source folder to check in new data
- def refresh(self, folder): Refresh the ... | 07bca1d199565cea0bf1917cb8d8a2e242f24f26 | <|skeleton|>
class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
<|body_0|>
def init_db(self, folder):
"""Refresh the source folder to check in new data"""
<|body_1|>
def refresh(self, folder):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
with open(filename, 'rb') as reader:
logger.info('Importing file %s', filename)
timer = Timer()
reader = csv.reader(reader)
titl... | the_stack_v2_python_sparse | orca/ocean.py | HopHill/orca | train | 0 |
90b0591e2e85cf3178305ca2c9d3808f4cde2104 | [
"start_date = product.properties.get('startTimeFromAscendingNode')\nif not start_date:\n epoch = time.gmtime(0)[:-3]\n start_date = datetime.datetime(*epoch).isoformat()\nreturn dateutil.parser.parse(start_date)",
"logger.debug('Start filtering for latest products')\nif not products:\n return []\nproduct... | <|body_start_0|>
start_date = product.properties.get('startTimeFromAscendingNode')
if not start_date:
epoch = time.gmtime(0)[:-3]
start_date = datetime.datetime(*epoch).isoformat()
return dateutil.parser.parse(start_date)
<|end_body_0|>
<|body_start_1|>
logger.de... | FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent | FilterLatestIntersect | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Python-2.0",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterLatestIntersect:
"""FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent"""
def sort_product_by_start_date(product):
"""Get product start date"""
<|body_0|>
def proceed(self, products, **search_... | stack_v2_sparse_classes_75kplus_train_068232 | 4,164 | permissive | [
{
"docstring": "Get product start date",
"name": "sort_product_by_start_date",
"signature": "def sort_product_by_start_date(product)"
},
{
"docstring": "Execute crunch: Filter latest products (the ones with a the highest start date) that intersect search extent. :param products: A list of produc... | 2 | null | Implement the Python class `FilterLatestIntersect` described below.
Class description:
FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent
Method signatures and docstrings:
- def sort_product_by_start_date(product): Get product start date
- def p... | Implement the Python class `FilterLatestIntersect` described below.
Class description:
FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent
Method signatures and docstrings:
- def sort_product_by_start_date(product): Get product start date
- def p... | f2ac36ba14d3b9b6a09daf0b0b7323dca59766ac | <|skeleton|>
class FilterLatestIntersect:
"""FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent"""
def sort_product_by_start_date(product):
"""Get product start date"""
<|body_0|>
def proceed(self, products, **search_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilterLatestIntersect:
"""FilterLatestIntersect cruncher Filter latest products (the ones with a the highest start date) that intersect search extent"""
def sort_product_by_start_date(product):
"""Get product start date"""
start_date = product.properties.get('startTimeFromAscendingNode')
... | the_stack_v2_python_sparse | eodag/plugins/crunch/filter_latest_intersect.py | CS-SI/eodag | train | 257 |
bbb0f81c1103e86170245510a53e5ffb89748964 | [
"pick = dict(self.__dict__)\npick.pop('handlers')\nreturn pick",
"state['handlers'] = []\nlog_format = logging.Formatter('%(asctime)-15s [%(levelname)s] %(module)s: %(message)s')\nconsole_logging = logging.StreamHandler()\nconsole_logging.setFormatter(log_format)\nstate['handlers'].append(console_logging)\nself._... | <|body_start_0|>
pick = dict(self.__dict__)
pick.pop('handlers')
return pick
<|end_body_0|>
<|body_start_1|>
state['handlers'] = []
log_format = logging.Formatter('%(asctime)-15s [%(levelname)s] %(module)s: %(message)s')
console_logging = logging.StreamHandler()
... | PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module. | PickleLog | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickleLog:
"""PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module."""
def __getstate__(self):
"""Serializing state of the logger. Removes the stream logging handlers when pickling :Returns: - The... | stack_v2_sparse_classes_75kplus_train_068233 | 2,729 | permissive | [
{
"docstring": "Serializing state of the logger. Removes the stream logging handlers when pickling :Returns: - The Logger dict with the 'handlers' key removed.",
"name": "__getstate__",
"signature": "def __getstate__(self)"
},
{
"docstring": "De-serialization state of the logger. Reinstates the ... | 2 | stack_v2_sparse_classes_30k_train_016515 | Implement the Python class `PickleLog` described below.
Class description:
PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module.
Method signatures and docstrings:
- def __getstate__(self): Serializing state of the logger. Removes ... | Implement the Python class `PickleLog` described below.
Class description:
PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module.
Method signatures and docstrings:
- def __getstate__(self): Serializing state of the logger. Removes ... | 10ddf082b992e2d45f18239ccf469d3dbd47d2d6 | <|skeleton|>
class PickleLog:
"""PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module."""
def __getstate__(self):
"""Serializing state of the logger. Removes the stream logging handlers when pickling :Returns: - The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickleLog:
"""PickleLog Logging extension to facilitate pickling of the logging streams during the launching of subprocesses in the multiprocessing module."""
def __getstate__(self):
"""Serializing state of the logger. Removes the stream logging handlers when pickling :Returns: - The Logger dict ... | the_stack_v2_python_sparse | batchapps/log.py | Azure/azure-batch-apps-python | train | 17 |
ea9286e90618c585ee1c81c06b28ccfa8b84b3fd | [
"if isinstance(start, int) and isinstance(end, int):\n pass\nelse:\n print('numbers should be int!')\nself.start = start\nself.end = end",
"@wraps(func)\ndef wrapper(*args, **kwargs):\n gener = self.__iter__()\n return func(gener, *args, **kwargs)\nreturn wrapper",
"try:\n for k in range(self.sta... | <|body_start_0|>
if isinstance(start, int) and isinstance(end, int):
pass
else:
print('numbers should be int!')
self.start = start
self.end = end
<|end_body_0|>
<|body_start_1|>
@wraps(func)
def wrapper(*args, **kwargs):
gener = self._... | Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using | Prime_Filtration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Prime_Filtration:
"""Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using"""
def __init__(self, start, end):
""... | stack_v2_sparse_classes_75kplus_train_068234 | 3,273 | no_license | [
{
"docstring": "Introduction ------------ constructor Parameters ---------- start: the start number of the range end : the end number of the range ----------",
"name": "__init__",
"signature": "def __init__(self, start, end)"
},
{
"docstring": "Introduction ------------ Rewrite __call__ function... | 4 | stack_v2_sparse_classes_30k_train_051117 | Implement the Python class `Prime_Filtration` described below.
Class description:
Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using
Method sig... | Implement the Python class `Prime_Filtration` described below.
Class description:
Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using
Method sig... | 661dba7ea846859056fd6ee7a310d352ca178e98 | <|skeleton|>
class Prime_Filtration:
"""Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using"""
def __init__(self, start, end):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Prime_Filtration:
"""Attentions: This is a decorated class, you should using it by '@', examples please look at Prime_Filtration_TEST.py at the same dictionary. Please check all the using details below and in Prime_Filtration_TEST.py before using"""
def __init__(self, start, end):
"""Introduction... | the_stack_v2_python_sparse | 包亦航2018011890/Regular_homework/Prime_Filtration(second_homework)/Prime_Filtration.py | wanghan79/2020_Python | train | 4 |
3cee1ada90cf533f45f9eef7811d9e01bff09a09 | [
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post(*args, **kwargs)",
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post_with_view(*args, **kwargs)",
"if self._context.get('tracking_disable'):\n return\nreturn super().message_post_with_templat... | <|body_start_0|>
if self._context.get('tracking_disable'):
return
return super().message_post(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self._context.get('tracking_disable'):
return
return super().message_post_with_view(*args, **kwargs)
<|end_body_1|>
... | Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set. | MailThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
<|body_0|>
def message_post_with_view(self, *args, **kwargs):
"""Post message using ... | stack_v2_sparse_classes_75kplus_train_068235 | 966 | no_license | [
{
"docstring": "Post message",
"name": "message_post",
"signature": "def message_post(self, *args, **kwargs)"
},
{
"docstring": "Post message using a view",
"name": "message_post_with_view",
"signature": "def message_post_with_view(self, *args, **kwargs)"
},
{
"docstring": "Post ... | 3 | stack_v2_sparse_classes_30k_train_043842 | Implement the Python class `MailThread` described below.
Class description:
Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set.
Method signatures and docstrings:
- def message_post(self, *args, **kwargs): Post message
- def message_post_with_view(self, *args, **kwargs)... | Implement the Python class `MailThread` described below.
Class description:
Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set.
Method signatures and docstrings:
- def message_post(self, *args, **kwargs): Post message
- def message_post_with_view(self, *args, **kwargs)... | d6d55fbf8abecb0b8201384921833868ae849920 | <|skeleton|>
class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
<|body_0|>
def message_post_with_view(self, *args, **kwargs):
"""Post message using ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MailThread:
"""Mail threads Disable mail thread posting whenever the context parameter ``tracking_disable`` is set."""
def message_post(self, *args, **kwargs):
"""Post message"""
if self._context.get('tracking_disable'):
return
return super().message_post(*args, **kwar... | the_stack_v2_python_sparse | addons/edi/models/mail_thread.py | unipartdigital/odoo-edi | train | 9 |
ea50b8248744cd7efa23d29e2546e9cfedf20037 | [
"self.marker_id = self._id.next()\nname = 'Marker' + str(self.marker_id)\nsuper(Marker, self).__init__(name, parent=parent)\nself._parent = parent\nself.node_id = node_id\nself.body_id = body_id\nself.rP = rP\nself.uP = uP\nself.SetConeRadius(0.0)\nself.AxisLabelsOff()\nself._size = 0.002\nself.SetTotalLength(self.... | <|body_start_0|>
self.marker_id = self._id.next()
name = 'Marker' + str(self.marker_id)
super(Marker, self).__init__(name, parent=parent)
self._parent = parent
self.node_id = node_id
self.body_id = body_id
self.rP = rP
self.uP = uP
self.SetConeRadi... | classdocs | Marker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Marker:
"""classdocs"""
def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None):
""":return:"""
<|body_0|>
def update_vtk_data(self, q, rP=np.zeros(3), theta=np.zeros(3)):
""":return:"""
<|bod... | stack_v2_sparse_classes_75kplus_train_068236 | 3,323 | no_license | [
{
"docstring": ":return:",
"name": "__init__",
"signature": "def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None)"
},
{
"docstring": ":return:",
"name": "update_vtk_data",
"signature": "def update_vtk_data(self, q, rP=np.z... | 5 | stack_v2_sparse_classes_30k_train_004845 | Implement the Python class `Marker` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None): :return:
- def update_vtk_data(self, q, rP=np.zeros(3), theta=np.zeros(3)): :ret... | Implement the Python class `Marker` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None): :return:
- def update_vtk_data(self, q, rP=np.zeros(3), theta=np.zeros(3)): :ret... | 5e6a54dee662206664dde022ccca372f966b1789 | <|skeleton|>
class Marker:
"""classdocs"""
def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None):
""":return:"""
<|body_0|>
def update_vtk_data(self, q, rP=np.zeros(3), theta=np.zeros(3)):
""":return:"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Marker:
"""classdocs"""
def __init__(self, rP, uP=None, theta0=np.zeros(3), body_id=None, node_id=None, body=None, MBD_item=None, parent=None):
""":return:"""
self.marker_id = self._id.next()
name = 'Marker' + str(self.marker_id)
super(Marker, self).__init__(name, parent=p... | the_stack_v2_python_sparse | simulation_control_widget/vtk_widget/marker/marker.py | xupeiwust/DyS | train | 0 |
6862042ea7709d986b271d2a30ace5d10f560a58 | [
"server = self.create_test_server(wait_until='ACTIVE')\nself.client.remove_security_group(server['id'], name=server['security_groups'][0]['name'])\nserver = self.client.show_server(server['id'])['server']\nself.assertNotIn('security_groups', server)",
"tenant_network = self.get_tenant_network()\n_, servers = comp... | <|body_start_0|>
server = self.create_test_server(wait_until='ACTIVE')
self.client.remove_security_group(server['id'], name=server['security_groups'][0]['name'])
server = self.client.show_server(server['id'])['server']
self.assertNotIn('security_groups', server)
<|end_body_0|>
<|body_st... | ServerActionsTestOtherA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerActionsTestOtherA:
def test_remove_server_all_security_groups(self):
"""Test removing all security groups from server"""
<|body_0|>
def test_rebuild_server_in_stop_state(self):
"""Test rebuilding server in stop state The server in stop state should be rebuilt u... | stack_v2_sparse_classes_75kplus_train_068237 | 42,147 | permissive | [
{
"docstring": "Test removing all security groups from server",
"name": "test_remove_server_all_security_groups",
"signature": "def test_remove_server_all_security_groups(self)"
},
{
"docstring": "Test rebuilding server in stop state The server in stop state should be rebuilt using the provided ... | 4 | stack_v2_sparse_classes_30k_train_011046 | Implement the Python class `ServerActionsTestOtherA` described below.
Class description:
Implement the ServerActionsTestOtherA class.
Method signatures and docstrings:
- def test_remove_server_all_security_groups(self): Test removing all security groups from server
- def test_rebuild_server_in_stop_state(self): Test ... | Implement the Python class `ServerActionsTestOtherA` described below.
Class description:
Implement the ServerActionsTestOtherA class.
Method signatures and docstrings:
- def test_remove_server_all_security_groups(self): Test removing all security groups from server
- def test_rebuild_server_in_stop_state(self): Test ... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class ServerActionsTestOtherA:
def test_remove_server_all_security_groups(self):
"""Test removing all security groups from server"""
<|body_0|>
def test_rebuild_server_in_stop_state(self):
"""Test rebuilding server in stop state The server in stop state should be rebuilt u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerActionsTestOtherA:
def test_remove_server_all_security_groups(self):
"""Test removing all security groups from server"""
server = self.create_test_server(wait_until='ACTIVE')
self.client.remove_security_group(server['id'], name=server['security_groups'][0]['name'])
server... | the_stack_v2_python_sparse | tempest/api/compute/servers/test_server_actions.py | openstack/tempest | train | 270 | |
5170b1cd5e706e01684a23760d574769852e3fae | [
"def buildList(root, lst):\n if not root:\n lst.append('N')\n else:\n lst.append(str(root.val))\n buildList(root.left, lst)\n buildList(root.right, lst)\nlst = []\nbuildList(root, lst)\nreturn ','.join(lst)",
"def buildTree(it):\n val = next(it)\n if val == 'N':\n ro... | <|body_start_0|>
def buildList(root, lst):
if not root:
lst.append('N')
else:
lst.append(str(root.val))
buildList(root.left, lst)
buildList(root.right, lst)
lst = []
buildList(root, lst)
return ','.jo... | 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_068238 | 1,719 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_039522 | 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:... | 672816c504e56a1d2dfea72f96312f27cd9a3133 | <|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"""
def buildList(root, lst):
if not root:
lst.append('N')
else:
lst.append(str(root.val))
buildList(root.left, lst)
... | the_stack_v2_python_sparse | 297.Serialize_and_Deserialize_Binary_Tree.py | mikehung/leetcode | train | 3 | |
348afe50ba07b9f802e44f46d330c6f51a4e6e62 | [
"try:\n return neuron.rate(trange=self.trange, **kwargs)\nexcept AttributeError:\n return self.r.n[neuron].rate(trange=self.trange, **kwargs)",
"try:\n return neuron.ratepdf(trange=self.trange, **kwargs)\nexcept AttributeError:\n return self.r.n[neuron].ratepdf(trange=self.trange, **kwargs)"
] | <|body_start_0|>
try:
return neuron.rate(trange=self.trange, **kwargs)
except AttributeError:
return self.r.n[neuron].rate(trange=self.trange, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
return neuron.ratepdf(trange=self.trange, **kwargs)
except At... | Mix-in class that defines the spike rate related experiment methods | ExperimentRate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperimentRate:
"""Mix-in class that defines the spike rate related experiment methods"""
def rate(self, neuron, **kwargs):
"""Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a neuron object or just a neuron id"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_068239 | 45,008 | permissive | [
{
"docstring": "Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a neuron object or just a neuron id",
"name": "rate",
"signature": "def rate(self, neuron, **kwargs)"
},
{
"docstring": "Returns a Neuron.RatePDF object, constraining it to the time r... | 2 | stack_v2_sparse_classes_30k_train_025859 | Implement the Python class `ExperimentRate` described below.
Class description:
Mix-in class that defines the spike rate related experiment methods
Method signatures and docstrings:
- def rate(self, neuron, **kwargs): Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a n... | Implement the Python class `ExperimentRate` described below.
Class description:
Mix-in class that defines the spike rate related experiment methods
Method signatures and docstrings:
- def rate(self, neuron, **kwargs): Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a n... | ab576a41ec00e3c126bca45c2504dd61bd1cda56 | <|skeleton|>
class ExperimentRate:
"""Mix-in class that defines the spike rate related experiment methods"""
def rate(self, neuron, **kwargs):
"""Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a neuron object or just a neuron id"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperimentRate:
"""Mix-in class that defines the spike rate related experiment methods"""
def rate(self, neuron, **kwargs):
"""Returns a Neuron.Rate object, constraining it to the time range of this experiment. Takes either a neuron object or just a neuron id"""
try:
return ne... | the_stack_v2_python_sparse | neuropy/experiment.py | node2319/neuropy-1 | train | 0 |
5b438eb08862e916099a0a789fa411f3c93badb8 | [
"def preorder(root):\n res = []\n if root:\n res += [str(root.val)]\n res += preorder(root.left)\n res += preorder(root.right)\n return res\nreturn ','.join(preorder(root))",
"if not data:\n return None\n\ndef build_tree(pre_o, in_o):\n if not pre_o:\n return None\n m... | <|body_start_0|>
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
return res
return ','.join(preorder(root))
<|end_body_0|>
<|body_start_1|>
if ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def preorder(r... | stack_v2_sparse_classes_75kplus_train_068240 | 1,118 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_053019 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 33eb204b1c7229ecb42651b17287d39164967e44 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
re... | the_stack_v2_python_sparse | Binary_tree/449. Serialize and Deserialize BST.py | WujiaShi/Leetcode | train | 0 | |
96c970e45e25902152dcf6a1e4eb27ce9b081897 | [
"N = len(nums) + 1\nfor i in range(0, len(nums)):\n if nums[i] < 0 or nums[i] >= N:\n nums[i] = 0\nnums.append(0)\nfor i in range(len(nums)):\n nums[nums[i] % N] += N\nfor i in range(1, len(nums)):\n if nums[i] < N:\n return i\nreturn N",
"N = len(nums)\nif N == 0:\n return 1\nfor s in r... | <|body_start_0|>
N = len(nums) + 1
for i in range(0, len(nums)):
if nums[i] < 0 or nums[i] >= N:
nums[i] = 0
nums.append(0)
for i in range(len(nums)):
nums[nums[i] % N] += N
for i in range(1, len(nums)):
if nums[i] < N:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
"""Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a new array that is used as a hash table The solution is the first element of such table that has not... | stack_v2_sparse_classes_75kplus_train_068241 | 2,584 | no_license | [
{
"docstring": "Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a new array that is used as a hash table The solution is the first element of such table that has not been filled",
"name": "firstMissingPositive",
"sig... | 2 | stack_v2_sparse_classes_30k_train_045252 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a ne... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a ne... | f4ac2609f8809ee543074a11dafc08726046f6a2 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
"""Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a new array that is used as a hash table The solution is the first element of such table that has not... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstMissingPositive(self, nums):
"""Storage is very limited so we do 3 tricks: - Remove elements that are <= 0 - Remove elements above N+1 - The remaining we re-arrange in a new array that is used as a hash table The solution is the first element of such table that has not been filled""... | the_stack_v2_python_sparse | LeetCode/41_first-missing-positive.py | curiousTauseef/Algorithms_and_solutions | train | 0 | |
2ccc503f8a9efd4aa08f95ef77e3b4988adb1420 | [
"comments = CommentsPhotos.query.order_by(asc(CommentsPhotos.PhotoID), asc(CommentsPhotos.Created)).all()\ncontents = jsonify({'comments': [{'commentID': comment.CommentID, 'photoID': comment.PhotoID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'createdAt': get_iso_fo... | <|body_start_0|>
comments = CommentsPhotos.query.order_by(asc(CommentsPhotos.PhotoID), asc(CommentsPhotos.Created)).all()
contents = jsonify({'comments': [{'commentID': comment.CommentID, 'photoID': comment.PhotoID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comme... | PhotoCommentsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoCommentsView:
def index(self):
"""Return all comments for all photos."""
<|body_0|>
def get(self, photo_id):
"""Return the comments for a specific photo."""
<|body_1|>
def post(self):
"""Add a comment to a photo specified in the payload."""
... | stack_v2_sparse_classes_75kplus_train_068242 | 26,847 | permissive | [
{
"docstring": "Return all comments for all photos.",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Return the comments for a specific photo.",
"name": "get",
"signature": "def get(self, photo_id)"
},
{
"docstring": "Add a comment to a photo specified in the ... | 5 | stack_v2_sparse_classes_30k_test_000146 | Implement the Python class `PhotoCommentsView` described below.
Class description:
Implement the PhotoCommentsView class.
Method signatures and docstrings:
- def index(self): Return all comments for all photos.
- def get(self, photo_id): Return the comments for a specific photo.
- def post(self): Add a comment to a p... | Implement the Python class `PhotoCommentsView` described below.
Class description:
Implement the PhotoCommentsView class.
Method signatures and docstrings:
- def index(self): Return all comments for all photos.
- def get(self, photo_id): Return the comments for a specific photo.
- def post(self): Add a comment to a p... | 62f8e8e904e379541193f0cbb91a8434b47f538f | <|skeleton|>
class PhotoCommentsView:
def index(self):
"""Return all comments for all photos."""
<|body_0|>
def get(self, photo_id):
"""Return the comments for a specific photo."""
<|body_1|>
def post(self):
"""Add a comment to a photo specified in the payload."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhotoCommentsView:
def index(self):
"""Return all comments for all photos."""
comments = CommentsPhotos.query.order_by(asc(CommentsPhotos.PhotoID), asc(CommentsPhotos.Created)).all()
contents = jsonify({'comments': [{'commentID': comment.CommentID, 'photoID': comment.PhotoID, 'userID':... | the_stack_v2_python_sparse | apps/comments/views.py | Torniojaws/vortech-backend | train | 0 | |
ec6ca6b6d74089b2c95d073c17d4b7d3dcbd28d9 | [
"self.reader = reader\nself.writer = writer\nself.nlp = nlp\nself.dtype = dtype\nif dtype not in ALLOWED_DATA_TYPES:\n raise ValueError('Invalid dtypes. Supported dtypes are {0}, not {1}'.format(ALLOWED_DATA_TYPES, dtype))",
"query_result = self.reader.read()\ndata = None\nwhile query_result:\n if len(query... | <|body_start_0|>
self.reader = reader
self.writer = writer
self.nlp = nlp
self.dtype = dtype
if dtype not in ALLOWED_DATA_TYPES:
raise ValueError('Invalid dtypes. Supported dtypes are {0}, not {1}'.format(ALLOWED_DATA_TYPES, dtype))
<|end_body_0|>
<|body_start_1|>
... | The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database. | Pipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipeline:
"""The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database."""
def __init__(self, reader, writer, nlp, dtype='ent'):
"""Create a new Pipeline object. Args: reader: A DbReader object writer:... | stack_v2_sparse_classes_75kplus_train_068243 | 2,574 | permissive | [
{
"docstring": "Create a new Pipeline object. Args: reader: A DbReader object writer: A Dbwriter object nlp: A spaCy model dtype: The DocConsumer data type to write to a database. Default \"ent Valid options are (\"ent\", \"section\", \"context\", \"doc\")",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_026887 | Implement the Python class `Pipeline` described below.
Class description:
The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database.
Method signatures and docstrings:
- def __init__(self, reader, writer, nlp, dtype='ent'): Create a new... | Implement the Python class `Pipeline` described below.
Class description:
The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database.
Method signatures and docstrings:
- def __init__(self, reader, writer, nlp, dtype='ent'): Create a new... | 1ce22f1e912d0231dd508ee18efa800a9a689f4d | <|skeleton|>
class Pipeline:
"""The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database."""
def __init__(self, reader, writer, nlp, dtype='ent'):
"""Create a new Pipeline object. Args: reader: A DbReader object writer:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pipeline:
"""The Pipeline class executes a batch process of reading texts, processing them with a spaCy model, and writing the results back to a database."""
def __init__(self, reader, writer, nlp, dtype='ent'):
"""Create a new Pipeline object. Args: reader: A DbReader object writer: A Dbwriter o... | the_stack_v2_python_sparse | medspacy/io/pipeline.py | trangtran72/medspacy | train | 0 |
65793e70abea673fa39ef42dcb4cffbec9911c16 | [
"n = len(nums)\nleft, right = (1, n - 1)\nwhile left < right:\n mid = left + (right - left) // 2\n count = 0\n for num in nums:\n if num <= mid:\n count += 1\n if count > mid:\n right = mid\n else:\n left = mid + 1\nreturn left",
"slow, fast = (0, 0)\nslow = nums[slo... | <|body_start_0|>
n = len(nums)
left, right = (1, n - 1)
while left < right:
mid = left + (right - left) // 2
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
right = mid
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def find_duplicate(self, nums: List[int]) -> int:
"""二分查找。"""
<|body_0|>
def find_duplicate2(self, nums: List[int]) -> int:
"""环形链表。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
left, right = (1, n - 1)
... | stack_v2_sparse_classes_75kplus_train_068244 | 3,636 | no_license | [
{
"docstring": "二分查找。",
"name": "find_duplicate",
"signature": "def find_duplicate(self, nums: List[int]) -> int"
},
{
"docstring": "环形链表。",
"name": "find_duplicate2",
"signature": "def find_duplicate2(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_000676 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def find_duplicate(self, nums: List[int]) -> int: 二分查找。
- def find_duplicate2(self, nums: List[int]) -> int: 环形链表。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def find_duplicate(self, nums: List[int]) -> int: 二分查找。
- def find_duplicate2(self, nums: List[int]) -> int: 环形链表。
<|skeleton|>
class OfficialSolution:
def ... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def find_duplicate(self, nums: List[int]) -> int:
"""二分查找。"""
<|body_0|>
def find_duplicate2(self, nums: List[int]) -> int:
"""环形链表。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficialSolution:
def find_duplicate(self, nums: List[int]) -> int:
"""二分查找。"""
n = len(nums)
left, right = (1, n - 1)
while left < right:
mid = left + (right - left) // 2
count = 0
for num in nums:
if num <= mid:
... | the_stack_v2_python_sparse | 0287_find-the-duplicate-number.py | Nigirimeshi/leetcode | train | 0 | |
eb4f6a533251d54ecbfd2d2ba2139b8fe9e34914 | [
"if not hasattr(self, '_references'):\n setattr(self, '_references', ReferenceProxyList(self))\nreturn self._references",
"if not hasattr(self, '_features'):\n setattr(self, '_features', FeatureProxyList(self))\nreturn self._features"
] | <|body_start_0|>
if not hasattr(self, '_references'):
setattr(self, '_references', ReferenceProxyList(self))
return self._references
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_features'):
setattr(self, '_features', FeatureProxyList(self))
return self.... | MultiTagMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiTagMixin:
def references(self):
"""A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be removed from the list, removing a referenced DataArray will not remove it from the file. New references can ... | stack_v2_sparse_classes_75kplus_train_068245 | 1,606 | permissive | [
{
"docstring": "A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be removed from the list, removing a referenced DataArray will not remove it from the file. New references can be added using the append method of the list. Th... | 2 | stack_v2_sparse_classes_30k_train_052944 | Implement the Python class `MultiTagMixin` described below.
Class description:
Implement the MultiTagMixin class.
Method signatures and docstrings:
- def references(self): A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be remove... | Implement the Python class `MultiTagMixin` described below.
Class description:
Implement the MultiTagMixin class.
Method signatures and docstrings:
- def references(self): A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be remove... | 25ccda7ddeeb81b67409a9a9d1a2fd09beddbc12 | <|skeleton|>
class MultiTagMixin:
def references(self):
"""A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be removed from the list, removing a referenced DataArray will not remove it from the file. New references can ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiTagMixin:
def references(self):
"""A property containing all data arrays referenced by the tag. Referenced data arrays can be obtained by index or their id. References can be removed from the list, removing a referenced DataArray will not remove it from the file. New references can be added using... | the_stack_v2_python_sparse | nixio/multi_tag.py | JiriVanek/nixpy | train | 0 | |
025ac29552ce9e2fb7d51e36934384c19f238489 | [
"super(PositionalEncoding3D, self).__init__()\nchannels = int(np.ceil(channels / 3))\nif channels % 2:\n channels += 1\nself.channels = channels\ninv_freq = 1.0 / 10000 ** (torch.arange(0, channels, 2).float() / channels)\nself.register_buffer('inv_freq', inv_freq)",
"if len(tensor.shape) != 5:\n raise Runt... | <|body_start_0|>
super(PositionalEncoding3D, self).__init__()
channels = int(np.ceil(channels / 3))
if channels % 2:
channels += 1
self.channels = channels
inv_freq = 1.0 / 10000 ** (torch.arange(0, channels, 2).float() / channels)
self.register_buffer('inv_fr... | PositionalEncoding3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding3D:
def __init__(self, channels):
""":param channels: The last dimension of the tensor you want to apply pos emb to."""
<|body_0|>
def forward(self, tensor):
""":param tensor: A 5d tensor of size (batch_size, x, y, z, ch) :return: Positional Encodin... | stack_v2_sparse_classes_75kplus_train_068246 | 8,320 | no_license | [
{
"docstring": ":param channels: The last dimension of the tensor you want to apply pos emb to.",
"name": "__init__",
"signature": "def __init__(self, channels)"
},
{
"docstring": ":param tensor: A 5d tensor of size (batch_size, x, y, z, ch) :return: Positional Encoding Matrix of size (batch_siz... | 2 | null | Implement the Python class `PositionalEncoding3D` described below.
Class description:
Implement the PositionalEncoding3D class.
Method signatures and docstrings:
- def __init__(self, channels): :param channels: The last dimension of the tensor you want to apply pos emb to.
- def forward(self, tensor): :param tensor: ... | Implement the Python class `PositionalEncoding3D` described below.
Class description:
Implement the PositionalEncoding3D class.
Method signatures and docstrings:
- def __init__(self, channels): :param channels: The last dimension of the tensor you want to apply pos emb to.
- def forward(self, tensor): :param tensor: ... | 0bd33d7a4c24816f3ecb4089a7d96ceaf64f298b | <|skeleton|>
class PositionalEncoding3D:
def __init__(self, channels):
""":param channels: The last dimension of the tensor you want to apply pos emb to."""
<|body_0|>
def forward(self, tensor):
""":param tensor: A 5d tensor of size (batch_size, x, y, z, ch) :return: Positional Encodin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding3D:
def __init__(self, channels):
""":param channels: The last dimension of the tensor you want to apply pos emb to."""
super(PositionalEncoding3D, self).__init__()
channels = int(np.ceil(channels / 3))
if channels % 2:
channels += 1
self.c... | the_stack_v2_python_sparse | models/mymod/utils.py | Myyyr/segmentation3D | train | 0 | |
db9788aaa0ae45006e2157243c4972c3fd065ad0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.emailFileAssessmentRequest'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | ThreatAssessmentRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""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 creat... | stack_v2_sparse_classes_75kplus_train_068247 | 7,669 | 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: ThreatAssessmentRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_036671 | Implement the Python class `ThreatAssessmentRequest` described below.
Class description:
Implement the ThreatAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest: Creates a new instance of the appropriate clas... | Implement the Python class `ThreatAssessmentRequest` described below.
Class description:
Implement the ThreatAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""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 creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreatAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ThreatAssessmentRequest:
"""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 R... | the_stack_v2_python_sparse | msgraph/generated/models/threat_assessment_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d62c7a8609c490ad354eac74f29f3c1dd31433ce | [
"self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])\nserver_def = self.server_conf['host'].split(':')\nserver_addr = server_def[0]\nsys_cmd = 'ipmitool -I lanplus -H ' + server_addr + \" -U '\" + self.pod_auth[0] + \"'\" + \" -P '\" + self.pod_auth[1] + \"'\" + ' bmc inf... | <|body_start_0|>
self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])
server_def = self.server_conf['host'].split(':')
server_addr = server_def[0]
sys_cmd = 'ipmitool -I lanplus -H ' + server_addr + " -U '" + self.pod_auth[0] + "'" + " -P '" + s... | Collect power consumption via IPMI protocol. | IPMICollector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
<|body_0|>
def get_sensors(self, manufacturer):
"""Return Power sensors list."""
<|body_1|>
def get_sensors_power(se... | stack_v2_sparse_classes_75kplus_train_068248 | 8,256 | no_license | [
{
"docstring": "Get Manufacturer id from IPMI.",
"name": "get_manufacturer_id",
"signature": "def get_manufacturer_id(self)"
},
{
"docstring": "Return Power sensors list.",
"name": "get_sensors",
"signature": "def get_sensors(self, manufacturer)"
},
{
"docstring": "Return power v... | 5 | stack_v2_sparse_classes_30k_train_001035 | Implement the Python class `IPMICollector` described below.
Class description:
Collect power consumption via IPMI protocol.
Method signatures and docstrings:
- def get_manufacturer_id(self): Get Manufacturer id from IPMI.
- def get_sensors(self, manufacturer): Return Power sensors list.
- def get_sensors_power(self, ... | Implement the Python class `IPMICollector` described below.
Class description:
Collect power consumption via IPMI protocol.
Method signatures and docstrings:
- def get_manufacturer_id(self): Get Manufacturer id from IPMI.
- def get_sensors(self, manufacturer): Return Power sensors list.
- def get_sensors_power(self, ... | a872f095f256b0dd63d292301426f0a807c04abb | <|skeleton|>
class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
<|body_0|>
def get_sensors(self, manufacturer):
"""Return Power sensors list."""
<|body_1|>
def get_sensors_power(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPMICollector:
"""Collect power consumption via IPMI protocol."""
def get_manufacturer_id(self):
"""Get Manufacturer id from IPMI."""
self.log.debug('[%s]: Getting manufacturer for server %s', self.name, self.server_conf['host'])
server_def = self.server_conf['host'].split(':')
... | the_stack_v2_python_sparse | server-collector/collectors/power/ipmicollector.py | bherard/energyrecorder | train | 2 |
80a18964f5e96a857e5f0c4c12792eddc145dfec | [
"f_s = 360\nX = fftpack.fft(sig)\nfreqs = fftpack.fftfreq(len(sig)) * f_s\nplt.plot(freqs, np.abs(X))\nplt.xlabel('Frequency in Hertz [Hz]')\nplt.ylabel('Frequency Domain (Spectrum) Magnitude')\nplt.xlim(0, f_s / 2)\nplt.ylim(-5, 110)",
"nyq = 0.5 * fs\nnormal_cutoff = cutoff / nyq\nb, a = butter(order, normal_cu... | <|body_start_0|>
f_s = 360
X = fftpack.fft(sig)
freqs = fftpack.fftfreq(len(sig)) * f_s
plt.plot(freqs, np.abs(X))
plt.xlabel('Frequency in Hertz [Hz]')
plt.ylabel('Frequency Domain (Spectrum) Magnitude')
plt.xlim(0, f_s / 2)
plt.ylim(-5, 110)
<|end_body_0... | filt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class filt:
def fft_plot(self, sig, label, color):
"""Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Frequencies"""
<|body_0|>
def butter_lowpass(self, cutoff, fs, order=5):
"""... | stack_v2_sparse_classes_75kplus_train_068249 | 6,842 | no_license | [
{
"docstring": "Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Frequencies",
"name": "fft_plot",
"signature": "def fft_plot(self, sig, label, color)"
},
{
"docstring": "Butterworth lowpass filter:: Al... | 4 | stack_v2_sparse_classes_30k_train_045109 | Implement the Python class `filt` described below.
Class description:
Implement the filt class.
Method signatures and docstrings:
- def fft_plot(self, sig, label, color): Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Freq... | Implement the Python class `filt` described below.
Class description:
Implement the filt class.
Method signatures and docstrings:
- def fft_plot(self, sig, label, color): Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Freq... | 22de91281f5918b715a4a2ab2d56d25418284293 | <|skeleton|>
class filt:
def fft_plot(self, sig, label, color):
"""Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Frequencies"""
<|body_0|>
def butter_lowpass(self, cutoff, fs, order=5):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class filt:
def fft_plot(self, sig, label, color):
"""Generates a FFT or fast fourier transform plot for the input signal. Input: Signal, Label (filtered/not), Color of Figure Output: Histogram of Frequencies"""
f_s = 360
X = fftpack.fft(sig)
freqs = fftpack.fftfreq(len(sig)) * f_s
... | the_stack_v2_python_sparse | DataPreparationScripts/normalizer.py | MLDawn/DRBFDD | train | 1 | |
5ead1ac6261c49b71fe1b9b5c5b902b596f576fd | [
"args = post_parser.parse_args(strict=True)\nLOGGER.info({'Args': args})\nuser = User.get_user(args.username)\nif user is None:\n hashed = bcrypt.hashpw(args.password.encode('utf8'), bcrypt.gensalt())\n record = User(username=args.username, pw_hash=hashed, bio=args.bio, displayName=args.displayName)\n reco... | <|body_start_0|>
args = post_parser.parse_args(strict=True)
LOGGER.info({'Args': args})
user = User.get_user(args.username)
if user is None:
hashed = bcrypt.hashpw(args.password.encode('utf8'), bcrypt.gensalt())
record = User(username=args.username, pw_hash=hashed... | UserList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserList:
def post(self):
"""Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: Bio of the user to be created."""
<|body_0|>
def get(self):
"""Get list of al... | stack_v2_sparse_classes_75kplus_train_068250 | 3,429 | no_license | [
{
"docstring": "Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: Bio of the user to be created.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get list of all users... | 2 | null | Implement the Python class `UserList` described below.
Class description:
Implement the UserList class.
Method signatures and docstrings:
- def post(self): Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: B... | Implement the Python class `UserList` described below.
Class description:
Implement the UserList class.
Method signatures and docstrings:
- def post(self): Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: B... | 6efc574af119b80dee5fbcd0234d1131aaf018fa | <|skeleton|>
class UserList:
def post(self):
"""Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: Bio of the user to be created."""
<|body_0|>
def get(self):
"""Get list of al... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserList:
def post(self):
"""Create a new user. Required in Payload: userame: Username of the new user to be created. password: Passowrd of the user to be created. Optional in Payload: bio: Bio of the user to be created."""
args = post_parser.parse_args(strict=True)
LOGGER.info({'Args'... | the_stack_v2_python_sparse | Backend/kite/api/v2/users.py | oshocker99/Kite | train | 1 | |
c6589ffc9e6bd84937a6a24377025e3ed373024a | [
"parent_outer = {}\nfor start_node in graph:\n if start_node not in parent_outer:\n parent_outer[start_node] = self.dfs_visit(graph, start_node)\nreturn parent_outer",
"if parent == None:\n parent = {start_node: None}\nfor node in graph[start_node]:\n if current_stack and node in current_stack:\n ... | <|body_start_0|>
parent_outer = {}
for start_node in graph:
if start_node not in parent_outer:
parent_outer[start_node] = self.dfs_visit(graph, start_node)
return parent_outer
<|end_body_0|>
<|body_start_1|>
if parent == None:
parent = {start_node... | Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze. The stack is implicitly handled by the recursion stack. | DepthFirstSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepthFirstSearch:
"""Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze. The stack is implicitly handled by the... | stack_v2_sparse_classes_75kplus_train_068251 | 2,623 | no_license | [
{
"docstring": "Used to call all the nodes once so that no node, even if unconnected, is left behind. Starting-node-choser.",
"name": "dfs",
"signature": "def dfs(self, graph)"
},
{
"docstring": "Actually the main function that takes a graph and a starting node and returns all the nodes reachabl... | 2 | stack_v2_sparse_classes_30k_train_039888 | Implement the Python class `DepthFirstSearch` described below.
Class description:
Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze.... | Implement the Python class `DepthFirstSearch` described below.
Class description:
Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze.... | 74194e660c2417f8d0c2a1b090dd41912e72efb3 | <|skeleton|>
class DepthFirstSearch:
"""Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze. The stack is implicitly handled by the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DepthFirstSearch:
"""Finds DFS route as well as whether the graph has a cycle/has a backward edge/can be topologically sorted. Pick a node and one of it neighbor and repeat. Go as deep as possible and then backtrack and go another route, like solving a maze. The stack is implicitly handled by the recursion st... | the_stack_v2_python_sparse | Extras/DFS for graph-MIT.py | okaysidd/Interview_material | train | 0 |
35cc0513731c42f2089428caa367fd7ad55bb112 | [
"assert 0 <= x <= 268435455\nbuffer = b''\nwhile 1:\n digit = x % 128\n x //= 128\n if x > 0:\n digit |= 128\n if sys.version_info[0] >= 3:\n buffer += bytes([digit])\n else:\n buffer += bytes(chr(digit))\n if x == 0:\n break\nreturn buffer",
"multiplier = 1\nvalue = ... | <|body_start_0|>
assert 0 <= x <= 268435455
buffer = b''
while 1:
digit = x % 128
x //= 128
if x > 0:
digit |= 128
if sys.version_info[0] >= 3:
buffer += bytes([digit])
else:
buffer += byt... | MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties. | VariableByteIntegers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
<|body_0|>
def decode(bu... | stack_v2_sparse_classes_75kplus_train_068252 | 16,499 | permissive | [
{
"docstring": "Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer.",
"name": "encode",
"signature": "def encode(x)"
},
{
"docstring": "Get the value of a multi-byte integer from a buffer Return the value, and the number of bytes used. [MQ... | 2 | stack_v2_sparse_classes_30k_train_052691 | Implement the Python class `VariableByteIntegers` described below.
Class description:
MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties.
Method signatures and docstrings:
- def encode(x): Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered f... | Implement the Python class `VariableByteIntegers` described below.
Class description:
MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties.
Method signatures and docstrings:
- def encode(x): Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered f... | d031aab82e3fa5ce7cf57b257fef8c9a4c63d71e | <|skeleton|>
class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
<|body_0|>
def decode(bu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VariableByteIntegers:
"""MQTT variable byte integer helper class. Used in several places in MQTT v5.0 properties."""
def encode(x):
"""Convert an integer 0 <= x <= 268435455 into multi-byte format. Returns the buffer convered from the integer."""
assert 0 <= x <= 268435455
buffer ... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/paho/mqtt/properties.py | CiscoDevNet/meraki-code | train | 67 |
379422795761c17158b780897250910eeb06333e | [
"self.pop_server = pop_server\nself.user = user\nself.password = passwd",
"try:\n self.reademail = poplib.POP3_SSL(self.pop_server)\n self.reademail.user(self.user)\n self.reademail.pass_(self.password)\n self.allemail = self.reademail.stat()\nexcept Exception as e:\n exit('读取邮件登录失败::%s' % str(e))"... | <|body_start_0|>
self.pop_server = pop_server
self.user = user
self.password = passwd
<|end_body_0|>
<|body_start_1|>
try:
self.reademail = poplib.POP3_SSL(self.pop_server)
self.reademail.user(self.user)
self.reademail.pass_(self.password)
... | My_Email_Rec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class My_Email_Rec:
def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs):
"""初始化接收邮件,获取第一封邮件标题字符的对象"""
<|body_0|>
def pop_connect(self):
"""连接pop服务器,收取邮件 :param self: :return:"""
<|body_1|>
def receiv... | stack_v2_sparse_classes_75kplus_train_068253 | 8,396 | no_license | [
{
"docstring": "初始化接收邮件,获取第一封邮件标题字符的对象",
"name": "__init__",
"signature": "def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs)"
},
{
"docstring": "连接pop服务器,收取邮件 :param self: :return:",
"name": "pop_connect",
"signature": "def p... | 3 | stack_v2_sparse_classes_30k_val_000195 | Implement the Python class `My_Email_Rec` described below.
Class description:
Implement the My_Email_Rec class.
Method signatures and docstrings:
- def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs): 初始化接收邮件,获取第一封邮件标题字符的对象
- def pop_connect(self): 连接pop服务器... | Implement the Python class `My_Email_Rec` described below.
Class description:
Implement the My_Email_Rec class.
Method signatures and docstrings:
- def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs): 初始化接收邮件,获取第一封邮件标题字符的对象
- def pop_connect(self): 连接pop服务器... | 8e4dfaaeae782a37f6baca4c024b1c2a1dc83cba | <|skeleton|>
class My_Email_Rec:
def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs):
"""初始化接收邮件,获取第一封邮件标题字符的对象"""
<|body_0|>
def pop_connect(self):
"""连接pop服务器,收取邮件 :param self: :return:"""
<|body_1|>
def receiv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class My_Email_Rec:
def __init__(self, pop_server='pop.qq.com', user='964725349@qq.com', passwd='kxsxacdjdelsbejc', *args, **kwargs):
"""初始化接收邮件,获取第一封邮件标题字符的对象"""
self.pop_server = pop_server
self.user = user
self.password = passwd
def pop_connect(self):
"""连接pop服务器,收取邮件... | the_stack_v2_python_sparse | poweroff_by_email.py | PeterZhangxing/codewars | train | 0 | |
4891cd65025a677d4f9f1828be8222c27826e829 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')\nnstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()\nfoodscores = []\nincome = []\nobesity = []\nfor nb in nstats:\n foodscores.append(nb['FoodSc... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')
nstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()
foodscores = []
income = []
... | statisticsanalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class statisticsanalysis:
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 every... | stack_v2_sparse_classes_75kplus_train_068254 | 3,448 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_038761 | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis 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(), startTi... | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis 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(), startTi... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class statisticsanalysis:
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 every... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class statisticsanalysis:
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('jguerero_mgarcia7', 'jguerero_mg... | the_stack_v2_python_sparse | jguerero_mgarcia7/statisticsanalysis.py | lingyigu/course-2017-spr-proj | train | 0 | |
e6b795fd35c0e84016a54451e672ef9de5e35417 | [
"ret = {'code': 1000, 'data': None}\ntry:\n queryset = models.Course.objects.all()\n ser = CourseSerializer(instance=queryset, many=True)\n ret['data'] = ser.data\nexcept Exception as e:\n ret['code'] = 1001\n ret['error'] = '获取课程失败'\nreturn Response(ret)",
"ret = {'code': 1000, 'data': None}\ntry:... | <|body_start_0|>
ret = {'code': 1000, 'data': None}
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset, many=True)
ret['data'] = ser.data
except Exception as e:
ret['code'] = 1001
ret['error'] = '获取课程失败... | 方式二 通过list和retrieve函数分配 | CourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseView:
"""方式二 通过list和retrieve函数分配"""
def list(self, request, *args, **kwargs):
"""获取课程列表的接口 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""获取课程详情的接口 :param request: :param args: :param kwar... | stack_v2_sparse_classes_75kplus_train_068255 | 2,772 | no_license | [
{
"docstring": "获取课程列表的接口 :param request: :param args: :param kwargs: :return:",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "获取课程详情的接口 :param request: :param args: :param kwargs: :return:",
"name": "retrieve",
"signature": "def retrieve(self... | 2 | null | Implement the Python class `CourseView` described below.
Class description:
方式二 通过list和retrieve函数分配
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 获取课程列表的接口 :param request: :param args: :param kwargs: :return:
- def retrieve(self, request, *args, **kwargs): 获取课程详情的接口 :param request: :pa... | Implement the Python class `CourseView` described below.
Class description:
方式二 通过list和retrieve函数分配
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 获取课程列表的接口 :param request: :param args: :param kwargs: :return:
- def retrieve(self, request, *args, **kwargs): 获取课程详情的接口 :param request: :pa... | 0d1fb870a59e21526481c4718a6a17ef2494e726 | <|skeleton|>
class CourseView:
"""方式二 通过list和retrieve函数分配"""
def list(self, request, *args, **kwargs):
"""获取课程列表的接口 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""获取课程详情的接口 :param request: :param args: :param kwar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CourseView:
"""方式二 通过list和retrieve函数分配"""
def list(self, request, *args, **kwargs):
"""获取课程列表的接口 :param request: :param args: :param kwargs: :return:"""
ret = {'code': 1000, 'data': None}
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(in... | the_stack_v2_python_sparse | s9day104/s9luffycity/api/views/course.py | qiu957919102/oldboy | train | 0 |
6755733b1d49386dec47bf6f3093791cffa63a42 | [
"project = self.get_project(projectid)\nif not project:\n return\nself.add_project_links(project)\nself.write(project)",
"project = self.get_project(projectid)\nself.upload_samples(project)\nself.write(dict(errors=self.errors, messages=self.messages))\nif self.errors:\n self.set_status(400)",
"project = s... | <|body_start_0|>
project = self.get_project(projectid)
if not project:
return
self.add_project_links(project)
self.write(project)
<|end_body_0|>
<|body_start_1|>
project = self.get_project(projectid)
self.upload_samples(project)
self.write(dict(errors... | Access a project. | ApiProject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiProject:
"""Access a project."""
def get(self, projectid):
"""Return the project data as JSON. Return HTTP 404 if no such project."""
<|body_0|>
def post(self, projectid):
"""Upload a CSV file containing identifiers of samples to create."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_068256 | 18,987 | permissive | [
{
"docstring": "Return the project data as JSON. Return HTTP 404 if no such project.",
"name": "get",
"signature": "def get(self, projectid)"
},
{
"docstring": "Upload a CSV file containing identifiers of samples to create.",
"name": "post",
"signature": "def post(self, projectid)"
},
... | 4 | stack_v2_sparse_classes_30k_train_007577 | Implement the Python class `ApiProject` described below.
Class description:
Access a project.
Method signatures and docstrings:
- def get(self, projectid): Return the project data as JSON. Return HTTP 404 if no such project.
- def post(self, projectid): Upload a CSV file containing identifiers of samples to create.
-... | Implement the Python class `ApiProject` described below.
Class description:
Access a project.
Method signatures and docstrings:
- def get(self, projectid): Return the project data as JSON. Return HTTP 404 if no such project.
- def post(self, projectid): Upload a CSV file containing identifiers of samples to create.
-... | 655400042cf782cf93c2d45388ed205d9a1ad296 | <|skeleton|>
class ApiProject:
"""Access a project."""
def get(self, projectid):
"""Return the project data as JSON. Return HTTP 404 if no such project."""
<|body_0|>
def post(self, projectid):
"""Upload a CSV file containing identifiers of samples to create."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiProject:
"""Access a project."""
def get(self, projectid):
"""Return the project data as JSON. Return HTTP 404 if no such project."""
project = self.get_project(projectid)
if not project:
return
self.add_project_links(project)
self.write(project)
... | the_stack_v2_python_sparse | charon/project.py | NationalGenomicsInfrastructure/charon | train | 3 |
7f4877bf798f62680318bfa8d1db725a08edb056 | [
"super(MainDashboard, self).__init__(parent, **props)\nself.state = {}\nself.status = StringVar()\nself.dashboard = Frame(self, bg=BG_COLOR, frame=self.parent_frame, width=self.width, height=self.height)\nself.label = Label(self, self.status, frame=self.dashboard, bg=BG_COLOR, foreground=TEXT_COLOR, font=('Helvetic... | <|body_start_0|>
super(MainDashboard, self).__init__(parent, **props)
self.state = {}
self.status = StringVar()
self.dashboard = Frame(self, bg=BG_COLOR, frame=self.parent_frame, width=self.width, height=self.height)
self.label = Label(self, self.status, frame=self.dashboard, bg=... | MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current title of the main dashboard. dashboard (react.widget_wrappers.Frame): The frame whe... | MainDashboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainDashboard:
"""MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current title of the main dashboard. dashboard (re... | stack_v2_sparse_classes_75kplus_train_068257 | 2,783 | no_license | [
{
"docstring": "Main Dashboard Component constructor. Args: parent (react.component.Component): The component that should contain the main dashboard. frame (react.widget_wrappers.Frame, optional): The Frame where the main dashboard should be placed. If no frame is specified, then the default frame is considered... | 2 | stack_v2_sparse_classes_30k_train_019785 | Implement the Python class `MainDashboard` described below.
Class description:
MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current tit... | Implement the Python class `MainDashboard` described below.
Class description:
MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current tit... | e689a133fd13e534281cc3a1b63a280964eacb5e | <|skeleton|>
class MainDashboard:
"""MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current title of the main dashboard. dashboard (re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainDashboard:
"""MainDashboard Component. The React Component that contains either the GUI's plot or a waiting screen if the device is not connected or the .hive file is not ready. Attributes: status (react.widget_wrappers.StringVar): Stores the current title of the main dashboard. dashboard (react.widget_wr... | the_stack_v2_python_sparse | driver/src/components/main_dashboard.py | mauesrog/temp | train | 0 |
3cff565e0045f0f73c4297aff336068ed03a3bbc | [
"Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()\nSchoolYear(school_year='2019-2020', first_semester='2019-09-02', winter_semester='2020-01-13', second_semester='2020-02-24', third_semester='2020-06-29', end_semester='2020-09-06').save()\nresponse = self.client.get('/ddl/Ca... | <|body_start_0|>
Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()
SchoolYear(school_year='2019-2020', first_semester='2019-09-02', winter_semester='2020-01-13', second_semester='2020-02-24', third_semester='2020-06-29', end_semester='2020-09-06').save()
r... | CalendarTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 成功的请求"""
<|body_0|>
def test_get_400(self):
"""检测返回状态码为400的get请求 1.参数名称错误 2.参数数量错误"""
<|body_1|>
def test_get_401(self):
"""检测返回状态码为401的get请求 数据库中无该用户"""
<|body_2|>
def test... | stack_v2_sparse_classes_75kplus_train_068258 | 9,602 | no_license | [
{
"docstring": "检测返回状态码为200的get请求 成功的请求",
"name": "test_get_200",
"signature": "def test_get_200(self)"
},
{
"docstring": "检测返回状态码为400的get请求 1.参数名称错误 2.参数数量错误",
"name": "test_get_400",
"signature": "def test_get_400(self)"
},
{
"docstring": "检测返回状态码为401的get请求 数据库中无该用户",
"name... | 6 | stack_v2_sparse_classes_30k_train_004861 | Implement the Python class `CalendarTests` described below.
Class description:
Implement the CalendarTests class.
Method signatures and docstrings:
- def test_get_200(self): 检测返回状态码为200的get请求 成功的请求
- def test_get_400(self): 检测返回状态码为400的get请求 1.参数名称错误 2.参数数量错误
- def test_get_401(self): 检测返回状态码为401的get请求 数据库中无该用户
- def... | Implement the Python class `CalendarTests` described below.
Class description:
Implement the CalendarTests class.
Method signatures and docstrings:
- def test_get_200(self): 检测返回状态码为200的get请求 成功的请求
- def test_get_400(self): 检测返回状态码为400的get请求 1.参数名称错误 2.参数数量错误
- def test_get_401(self): 检测返回状态码为401的get请求 数据库中无该用户
- def... | 7dfa07283d4130b931a92c80bf4f499f97a33b62 | <|skeleton|>
class CalendarTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 成功的请求"""
<|body_0|>
def test_get_400(self):
"""检测返回状态码为400的get请求 1.参数名称错误 2.参数数量错误"""
<|body_1|>
def test_get_401(self):
"""检测返回状态码为401的get请求 数据库中无该用户"""
<|body_2|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalendarTests:
def test_get_200(self):
"""检测返回状态码为200的get请求 成功的请求"""
Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()
SchoolYear(school_year='2019-2020', first_semester='2019-09-02', winter_semester='2020-01-13', second_semester='2020-02-24', th... | the_stack_v2_python_sparse | ddl_query/tests.py | SE2020-TopUnderstanding/BUAA-Campus-Tools-Backend | train | 7 | |
9e7198773e890ea71b2e20a49e20088106d647cc | [
"super(LoadBalancer, self).__init__()\nself.region = subnets[0].region\nself.name = 'pkb-%s' % FLAGS.run_uri\nself.subnet_ids = [subnet.id for subnet in subnets]\nself.type = 'network'\nself.arn = None\nself.dns_name = None",
"create_cmd = util.AWS_PREFIX + ['--region', self.region, 'elbv2', 'create-load-balancer... | <|body_start_0|>
super(LoadBalancer, self).__init__()
self.region = subnets[0].region
self.name = 'pkb-%s' % FLAGS.run_uri
self.subnet_ids = [subnet.id for subnet in subnets]
self.type = 'network'
self.arn = None
self.dns_name = None
<|end_body_0|>
<|body_start_1... | Class representing an AWS load balancer. | LoadBalancer | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadBalancer:
"""Class representing an AWS load balancer."""
def __init__(self, subnets):
"""Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects."""
<|body_0|>
def _Create(self):
"""Create the load balancer."""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus_train_068259 | 4,687 | permissive | [
{
"docstring": "Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects.",
"name": "__init__",
"signature": "def __init__(self, subnets)"
},
{
"docstring": "Create the load balancer.",
"name": "_Create",
"signature": "def _Create(self)"
},
{
"docstring": "De... | 3 | stack_v2_sparse_classes_30k_train_051546 | Implement the Python class `LoadBalancer` described below.
Class description:
Class representing an AWS load balancer.
Method signatures and docstrings:
- def __init__(self, subnets): Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects.
- def _Create(self): Create the load balancer.
- def _D... | Implement the Python class `LoadBalancer` described below.
Class description:
Class representing an AWS load balancer.
Method signatures and docstrings:
- def __init__(self, subnets): Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects.
- def _Create(self): Create the load balancer.
- def _D... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class LoadBalancer:
"""Class representing an AWS load balancer."""
def __init__(self, subnets):
"""Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects."""
<|body_0|>
def _Create(self):
"""Create the load balancer."""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadBalancer:
"""Class representing an AWS load balancer."""
def __init__(self, subnets):
"""Initializes the LoadBalancer object. Args: subnets: List of AwsSubnet objects."""
super(LoadBalancer, self).__init__()
self.region = subnets[0].region
self.name = 'pkb-%s' % FLAGS.... | the_stack_v2_python_sparse | perfkitbenchmarker/providers/aws/aws_load_balancer.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
4912cebce1da2ad71591cb2ba6c969b668de89b5 | [
"if output_as_json:\n output = {}\n for attribute in attributes_list:\n output.update(self.get_single_attribute(data, attribute, mapping_table, output_as_json=True, resources=resources))\nelse:\n output = ''\n for attribute in attributes_list:\n output += '\\n' + self.get_single_attribute(... | <|body_start_0|>
if output_as_json:
output = {}
for attribute in attributes_list:
output.update(self.get_single_attribute(data, attribute, mapping_table, output_as_json=True, resources=resources))
else:
output = ''
for attribute in attribut... | Helper functions for getting data | Mapper | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mapper:
"""Helper functions for getting data"""
def get_multiple_attributes(self, data, attributes_list, mapping_table, output_as_json=False, **resources):
"""Method used to get data for multiple attributes :param data: json from which data is to be extracted :param attributes_list: ... | stack_v2_sparse_classes_75kplus_train_068260 | 4,462 | permissive | [
{
"docstring": "Method used to get data for multiple attributes :param data: json from which data is to be extracted :param attributes_list: list of attributes to be extracted :param mapping_table: table used to extract data :param output_as_json: specifies whether the output should be in json or not :param res... | 2 | stack_v2_sparse_classes_30k_train_008056 | Implement the Python class `Mapper` described below.
Class description:
Helper functions for getting data
Method signatures and docstrings:
- def get_multiple_attributes(self, data, attributes_list, mapping_table, output_as_json=False, **resources): Method used to get data for multiple attributes :param data: json fr... | Implement the Python class `Mapper` described below.
Class description:
Helper functions for getting data
Method signatures and docstrings:
- def get_multiple_attributes(self, data, attributes_list, mapping_table, output_as_json=False, **resources): Method used to get data for multiple attributes :param data: json fr... | e3b3129619acf78ffb84f844978cb713d2a1b606 | <|skeleton|>
class Mapper:
"""Helper functions for getting data"""
def get_multiple_attributes(self, data, attributes_list, mapping_table, output_as_json=False, **resources):
"""Method used to get data for multiple attributes :param data: json from which data is to be extracted :param attributes_list: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mapper:
"""Helper functions for getting data"""
def get_multiple_attributes(self, data, attributes_list, mapping_table, output_as_json=False, **resources):
"""Method used to get data for multiple attributes :param data: json from which data is to be extracted :param attributes_list: list of attri... | the_stack_v2_python_sparse | src/extensions/PERSISTENT_MEMORY_COMMANDS/lib/Mapper.py | HewlettPackard/python-redfish-utility | train | 67 |
008b26372c5bfb441e7d9b1d98cd9a8a3662e7a7 | [
"self.parent = self\nself.rank = 0\nself.value = 0",
"s_root = self.find()\no_root = other.find()\nif s_root.rank > o_root.rank:\n o_root.parent = s_root\nelif o_root.rank > s_root.rank:\n s_root.parent = o_root\nelif o_root != s_root:\n o_root.parent = s_root\n s_root.rank += 1",
"if self.parent ==... | <|body_start_0|>
self.parent = self
self.rank = 0
self.value = 0
<|end_body_0|>
<|body_start_1|>
s_root = self.find()
o_root = other.find()
if s_root.rank > o_root.rank:
o_root.parent = s_root
elif o_root.rank > s_root.rank:
s_root.parent ... | A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure | DisjointSetTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisjointSetTree:
"""A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure"""
def __init__(self):
"""ctor."""
<|body_0|>
def union(self, other):
"""Union with another tree."""
<|body_1|>
def find(self):
... | stack_v2_sparse_classes_75kplus_train_068261 | 2,205 | permissive | [
{
"docstring": "ctor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Union with another tree.",
"name": "union",
"signature": "def union(self, other)"
},
{
"docstring": "Find the root of the tree.",
"name": "find",
"signature": "def find(self)"... | 3 | stack_v2_sparse_classes_30k_val_002130 | Implement the Python class `DisjointSetTree` described below.
Class description:
A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure
Method signatures and docstrings:
- def __init__(self): ctor.
- def union(self, other): Union with another tree.
- def find(self): Find the ... | Implement the Python class `DisjointSetTree` described below.
Class description:
A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure
Method signatures and docstrings:
- def __init__(self): ctor.
- def union(self, other): Union with another tree.
- def find(self): Find the ... | 1dcdfa3d9efd022f29f37495be15f9657c5e7374 | <|skeleton|>
class DisjointSetTree:
"""A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure"""
def __init__(self):
"""ctor."""
<|body_0|>
def union(self, other):
"""Union with another tree."""
<|body_1|>
def find(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisjointSetTree:
"""A disjoint set tree data structure. See http://en.wikipedia.org/wiki/Disjoint-set_data_structure"""
def __init__(self):
"""ctor."""
self.parent = self
self.rank = 0
self.value = 0
def union(self, other):
"""Union with another tree."""
... | the_stack_v2_python_sparse | pythonExcelReader/OpenANPR-master/experimental/connected.py | ashevel1/BehaveNet | train | 0 |
56d1e5199e2611796026b814ecf5d94bc34372cf | [
"expected_record_count = (4, 3, 12)\nexpected_error_count = (0, 0, 0)\ntup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_FILE_RENTAL)\nself.assertTupleEqual(tup_record_count, expected_record_count)\nself.assertTupleEqual(tup_error_count, expected_error_count... | <|body_start_0|>
expected_record_count = (4, 3, 12)
expected_error_count = (0, 0, 0)
tup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_FILE_RENTAL)
self.assertTupleEqual(tup_record_count, expected_record_count)
self.assert... | unit test for database.py | TestDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
<|body_0|>
def test_import_data_error(self):
"""test import_data"""
<|body_1|>
def test_show_available_product(self):
"""test show_available_prod... | stack_v2_sparse_classes_75kplus_train_068262 | 3,286 | no_license | [
{
"docstring": "test import_data",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "test import_data",
"name": "test_import_data_error",
"signature": "def test_import_data_error(self)"
},
{
"docstring": "test show_available_product",
"n... | 4 | stack_v2_sparse_classes_30k_train_021538 | Implement the Python class `TestDatabase` described below.
Class description:
unit test for database.py
Method signatures and docstrings:
- def test_import_data(self): test import_data
- def test_import_data_error(self): test import_data
- def test_show_available_product(self): test show_available_product
- def test_... | Implement the Python class `TestDatabase` described below.
Class description:
unit test for database.py
Method signatures and docstrings:
- def test_import_data(self): test import_data
- def test_import_data_error(self): test import_data
- def test_show_available_product(self): test show_available_product
- def test_... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
<|body_0|>
def test_import_data_error(self):
"""test import_data"""
<|body_1|>
def test_show_available_product(self):
"""test show_available_prod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
expected_record_count = (4, 3, 12)
expected_error_count = (0, 0, 0)
tup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_... | the_stack_v2_python_sparse | students/ttlarson/lesson05/assignment/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
232b0ab35c39ae33779d8d46f496162e61b53517 | [
"for rec in self:\n base_url = rec.get_base_url()\n share_url = rec._get_share_url(redirect=True, signup_partner=True)\n url = base_url + share_url\n return url",
"for rec in self:\n templated_id = self.env.ref('sale_whatsapp_connector.sale_order_status', raise_if_not_found=False)\n whatsapp_log... | <|body_start_0|>
for rec in self:
base_url = rec.get_base_url()
share_url = rec._get_share_url(redirect=True, signup_partner=True)
url = base_url + share_url
return url
<|end_body_0|>
<|body_start_1|>
for rec in self:
templated_id = self.env.r... | Inherit Sale Order. | SaleOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
<|body_0|>
def send_order_status(self):
"""Send Message to Customer."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for rec in self:
ba... | stack_v2_sparse_classes_75kplus_train_068263 | 3,182 | no_license | [
{
"docstring": "Method to genrate the share Link.",
"name": "get_link",
"signature": "def get_link(self)"
},
{
"docstring": "Send Message to Customer.",
"name": "send_order_status",
"signature": "def send_order_status(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052645 | Implement the Python class `SaleOrder` described below.
Class description:
Inherit Sale Order.
Method signatures and docstrings:
- def get_link(self): Method to genrate the share Link.
- def send_order_status(self): Send Message to Customer. | Implement the Python class `SaleOrder` described below.
Class description:
Inherit Sale Order.
Method signatures and docstrings:
- def get_link(self): Method to genrate the share Link.
- def send_order_status(self): Send Message to Customer.
<|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_li... | e5c27a9201d27f6a1dfabbc73a92cc62d25c9702 | <|skeleton|>
class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
<|body_0|>
def send_order_status(self):
"""Send Message to Customer."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaleOrder:
"""Inherit Sale Order."""
def get_link(self):
"""Method to genrate the share Link."""
for rec in self:
base_url = rec.get_base_url()
share_url = rec._get_share_url(redirect=True, signup_partner=True)
url = base_url + share_url
ret... | the_stack_v2_python_sparse | sale_whatsapp_connector/models/sale_order.py | Raniani-lab/dxm | train | 0 |
58489e4fe272cab1db7ddb9485e1396dec692623 | [
"super(ButtonSearch, self).mousePressEvent(event)\nupdate_pointer()\nself.setProperty('focused', False)",
"if self.isEnabled():\n update_pointer(Qt.ArrowCursor)\n self.setProperty('focused', True)\nsuper(ButtonSearch, self).enterEvent(event)",
"if self.isEnabled():\n update_pointer()\n self.setPrope... | <|body_start_0|>
super(ButtonSearch, self).mousePressEvent(event)
update_pointer()
self.setProperty('focused', False)
<|end_body_0|>
<|body_start_1|>
if self.isEnabled():
update_pointer(Qt.ArrowCursor)
self.setProperty('focused', True)
super(ButtonSearch,... | Button used for CSS styling. | ButtonSearch | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ButtonSearch:
"""Button used for CSS styling."""
def mousePressEvent(self, event):
"""Override Qt method."""
<|body_0|>
def enterEvent(self, event):
"""Override Qt method."""
<|body_1|>
def leaveEvent(self, event):
"""Override Qt method."""
... | stack_v2_sparse_classes_75kplus_train_068264 | 5,225 | permissive | [
{
"docstring": "Override Qt method.",
"name": "mousePressEvent",
"signature": "def mousePressEvent(self, event)"
},
{
"docstring": "Override Qt method.",
"name": "enterEvent",
"signature": "def enterEvent(self, event)"
},
{
"docstring": "Override Qt method.",
"name": "leaveEv... | 4 | stack_v2_sparse_classes_30k_train_041262 | Implement the Python class `ButtonSearch` described below.
Class description:
Button used for CSS styling.
Method signatures and docstrings:
- def mousePressEvent(self, event): Override Qt method.
- def enterEvent(self, event): Override Qt method.
- def leaveEvent(self, event): Override Qt method.
- def setProperty(s... | Implement the Python class `ButtonSearch` described below.
Class description:
Button used for CSS styling.
Method signatures and docstrings:
- def mousePressEvent(self, event): Override Qt method.
- def enterEvent(self, event): Override Qt method.
- def leaveEvent(self, event): Override Qt method.
- def setProperty(s... | 74476c9f00ee43338af696da7e9cd02b273f9005 | <|skeleton|>
class ButtonSearch:
"""Button used for CSS styling."""
def mousePressEvent(self, event):
"""Override Qt method."""
<|body_0|>
def enterEvent(self, event):
"""Override Qt method."""
<|body_1|>
def leaveEvent(self, event):
"""Override Qt method."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ButtonSearch:
"""Button used for CSS styling."""
def mousePressEvent(self, event):
"""Override Qt method."""
super(ButtonSearch, self).mousePressEvent(event)
update_pointer()
self.setProperty('focused', False)
def enterEvent(self, event):
"""Override Qt method... | the_stack_v2_python_sparse | python/anaconda/lib/python2.7/site-packages/anaconda_navigator/widgets/helperwidgets.py | locolucco209/MongoScraper | train | 3 |
e4c87ad0f607595914a296bc814c125b5065bd64 | [
"super(Generator, self).__init__()\n\ndef block(in_channels, out_channels, stride=2, padding=1, batch_norm=True, nonlinearity=nn.ReLU(True)):\n return [nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=stride, padding=padding, bias=False), *([nn.BatchNorm2d(out_channels)] if batch_norm else [])... | <|body_start_0|>
super(Generator, self).__init__()
def block(in_channels, out_channels, stride=2, padding=1, batch_norm=True, nonlinearity=nn.ReLU(True)):
return [nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=stride, padding=padding, bias=False), *([nn.BatchNorm2d(out_... | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
def __init__(self, nz, nf, nc, nc_gaussian):
"""nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image"""
<|body_0|>
def forward(self, z, c):
"""z (N, nz, 1, 1) or (N, nz) incompressible noise ... | stack_v2_sparse_classes_75kplus_train_068265 | 15,506 | no_license | [
{
"docstring": "nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image",
"name": "__init__",
"signature": "def __init__(self, nz, nf, nc, nc_gaussian)"
},
{
"docstring": "z (N, nz, 1, 1) or (N, nz) incompressible noise vector c (N, 1... | 2 | stack_v2_sparse_classes_30k_train_044342 | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, nz, nf, nc, nc_gaussian): nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image
- def forward... | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, nz, nf, nc, nc_gaussian): nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image
- def forward... | 0a6653a66f1fb2590df9d6697e4cd69d32a2baaa | <|skeleton|>
class Generator:
def __init__(self, nz, nf, nc, nc_gaussian):
"""nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image"""
<|body_0|>
def forward(self, z, c):
"""z (N, nz, 1, 1) or (N, nz) incompressible noise ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Generator:
def __init__(self, nz, nf, nc, nc_gaussian):
"""nz dimension of noise and latent codes nf dimension of features in last conv layer nc number of channels in the image"""
super(Generator, self).__init__()
def block(in_channels, out_channels, stride=2, padding=1, batch_norm=Tr... | the_stack_v2_python_sparse | infogan/infogan.py | tt6746690/misc_impl | train | 0 | |
90a70cdd0da6a5ffc2965df1bc9b68926434917c | [
"super().__init__(vehicle.coordinators[description.coordinator])\nself.vehicle = vehicle\nself.entity_description = description\nself._attr_device_info = self.vehicle.device_info\nself._attr_unique_id = f'{self.vehicle.details.vin}_{description.key}'.lower()",
"if self.coordinator.data is None:\n return None\n... | <|body_start_0|>
super().__init__(vehicle.coordinators[description.coordinator])
self.vehicle = vehicle
self.entity_description = description
self._attr_device_info = self.vehicle.device_info
self._attr_unique_id = f'{self.vehicle.details.vin}_{description.key}'.lower()
<|end_bod... | Implementation of a Renault entity with a data coordinator. | RenaultDataEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenaultDataEntity:
"""Implementation of a Renault entity with a data coordinator."""
def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None:
"""Initialise entity."""
<|body_0|>
def _get_data_attr(self, key: str) -> StateType:
... | stack_v2_sparse_classes_75kplus_train_068266 | 2,510 | permissive | [
{
"docstring": "Initialise entity.",
"name": "__init__",
"signature": "def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None"
},
{
"docstring": "Return the attribute value from the coordinator data.",
"name": "_get_data_attr",
"signature": "def _... | 3 | stack_v2_sparse_classes_30k_train_011112 | Implement the Python class `RenaultDataEntity` described below.
Class description:
Implementation of a Renault entity with a data coordinator.
Method signatures and docstrings:
- def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None: Initialise entity.
- def _get_data_attr(se... | Implement the Python class `RenaultDataEntity` described below.
Class description:
Implementation of a Renault entity with a data coordinator.
Method signatures and docstrings:
- def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None: Initialise entity.
- def _get_data_attr(se... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class RenaultDataEntity:
"""Implementation of a Renault entity with a data coordinator."""
def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None:
"""Initialise entity."""
<|body_0|>
def _get_data_attr(self, key: str) -> StateType:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RenaultDataEntity:
"""Implementation of a Renault entity with a data coordinator."""
def __init__(self, vehicle: RenaultVehicleProxy, description: RenaultEntityDescription) -> None:
"""Initialise entity."""
super().__init__(vehicle.coordinators[description.coordinator])
self.vehic... | the_stack_v2_python_sparse | homeassistant/components/renault/renault_entities.py | AlexxIT/home-assistant | train | 9 |
b6ca720e8de5230623ed66b784ad30985bf34dcf | [
"Nature.__init__(self, x, y, window)\nself.image = pygame.image.load('Images/desertpalmtree.png')\nself.rect = self.image.get_rect()\nself.rect.x = x\nself.rect.y = y",
"if window.model.heat < 255:\n window.model.heat += 0.01\nif window.model.wet > 0:\n window.model.wet -= 0.01"
] | <|body_start_0|>
Nature.__init__(self, x, y, window)
self.image = pygame.image.load('Images/desertpalmtree.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
<|end_body_0|>
<|body_start_1|>
if window.model.heat < 255:
window.model.heat +=... | Desert palm tree object | DesertPalmTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DesertPalmTree:
"""Desert palm tree object"""
def __init__(self, x, y, window):
"""replaces the default image with the desert palm tree image"""
<|body_0|>
def effect(self, window):
"""makes the environment hotter and wetter"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_068267 | 4,149 | no_license | [
{
"docstring": "replaces the default image with the desert palm tree image",
"name": "__init__",
"signature": "def __init__(self, x, y, window)"
},
{
"docstring": "makes the environment hotter and wetter",
"name": "effect",
"signature": "def effect(self, window)"
}
] | 2 | null | Implement the Python class `DesertPalmTree` described below.
Class description:
Desert palm tree object
Method signatures and docstrings:
- def __init__(self, x, y, window): replaces the default image with the desert palm tree image
- def effect(self, window): makes the environment hotter and wetter | Implement the Python class `DesertPalmTree` described below.
Class description:
Desert palm tree object
Method signatures and docstrings:
- def __init__(self, x, y, window): replaces the default image with the desert palm tree image
- def effect(self, window): makes the environment hotter and wetter
<|skeleton|>
cla... | dbe8fbd8825b47290d11d6e3d4a7199f668e7527 | <|skeleton|>
class DesertPalmTree:
"""Desert palm tree object"""
def __init__(self, x, y, window):
"""replaces the default image with the desert palm tree image"""
<|body_0|>
def effect(self, window):
"""makes the environment hotter and wetter"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DesertPalmTree:
"""Desert palm tree object"""
def __init__(self, x, y, window):
"""replaces the default image with the desert palm tree image"""
Nature.__init__(self, x, y, window)
self.image = pygame.image.load('Images/desertpalmtree.png')
self.rect = self.image.get_rect(... | the_stack_v2_python_sparse | environment.py | Greenlightrj/playgod | train | 0 |
aa7abb09970ceea9c69adc781a4f80bc3be0ba17 | [
"self.num_warmup_batches = num_warmup_batches\nself.batches_done = 0\nself.batch_times = np.zeros(num_batches)\nself.tic = timeit.default_timer()",
"batch_time = timeit.default_timer() - self.tic\nself.batches_done += 1\nidx = -1\nif self.batches_done > self.num_warmup_batches:\n idx = self.batches_done - self... | <|body_start_0|>
self.num_warmup_batches = num_warmup_batches
self.batches_done = 0
self.batch_times = np.zeros(num_batches)
self.tic = timeit.default_timer()
<|end_body_0|>
<|body_start_1|>
batch_time = timeit.default_timer() - self.tic
self.batches_done += 1
id... | A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop. | BatchEndCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchEndCallback:
"""A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop."""
def __init__(self, num_warmup_batches, num_batches):
"""Initializes this c... | stack_v2_sparse_classes_75kplus_train_068268 | 17,617 | permissive | [
{
"docstring": "Initializes this callback. :param int num_warmup_batches: Number of warmup batches. :param int num_batches: Number of benchmark batches.",
"name": "__init__",
"signature": "def __init__(self, num_warmup_batches, num_batches)"
},
{
"docstring": "Is called by `EarlyStoppableModule.... | 2 | null | Implement the Python class `BatchEndCallback` described below.
Class description:
A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop.
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `BatchEndCallback` described below.
Class description:
A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop.
Method signatures and docstrings:
- def __init__(s... | 834350c81154e48af132b7d27874e30a7b80a78c | <|skeleton|>
class BatchEndCallback:
"""A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop."""
def __init__(self, num_warmup_batches, num_batches):
"""Initializes this c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchEndCallback:
"""A callback for an end-of-batch event. Counts number of batches processed. A non-standard implementation. The `__call__` method returns boolean value. False indicates training must stop."""
def __init__(self, num_warmup_batches, num_batches):
"""Initializes this callback. :par... | the_stack_v2_python_sparse | python/mxnet_benchmarks/benchmarks.py | HewlettPackard/dlcookbook-dlbs | train | 132 |
8584923d499efa0ce0587feddebfeda7232c416b | [
"if self.backend is None:\n raise QiskitError('backend not set. Cannot determine the center frequency.')\nreturn self._backend_data.drive_freqs[self.physical_qubits[0]]",
"circuit = QuantumCircuit(1)\ncircuit.append(Gate(name=self.__spec_gate_name__, num_qubits=1, params=[freq_param]), (0,))\ncircuit.measure_a... | <|body_start_0|>
if self.backend is None:
raise QiskitError('backend not set. Cannot determine the center frequency.')
return self._backend_data.drive_freqs[self.physical_qubits[0]]
<|end_body_0|>
<|body_start_1|>
circuit = QuantumCircuit(1)
circuit.append(Gate(name=self.__s... | A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule embedded in a spectroscopy gate... | QubitSpectroscopy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_75kplus_train_068269 | 4,798 | permissive | [
{
"docstring": "Returns the center frequency of the experiment. Returns: The center frequency of the experiment. Raises: QiskitError: If the experiment does not have a backend set.",
"name": "_backend_center_frequency",
"signature": "def _backend_center_frequency(self) -> float"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_001303 | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule... | the_stack_v2_python_sparse | qiskit_experiments/library/characterization/qubit_spectroscopy.py | oliverdial/qiskit-experiments | train | 0 |
14ffce6d2708c2d36983f614fab4cd3256ce597d | [
"self.universe = universe\nself.typetable = typetable\nself.handler_table = handler_table",
"if type(value) in self.typetable:\n return self.typetable[type(value)]\nelif type(value) in self.handler_table:\n return self.handler_table[type(value)](self.universe, value)\nelse:\n for cls in self.handler_tabl... | <|body_start_0|>
self.universe = universe
self.typetable = typetable
self.handler_table = handler_table
<|end_body_0|>
<|body_start_1|>
if type(value) in self.typetable:
return self.typetable[type(value)]
elif type(value) in self.handler_table:
return sel... | ConstantTyper | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstantTyper:
def __init__(self, universe, typetable, handler_table):
"""Initialize to the given type universe"""
<|body_0|>
def typeof(self, value):
"""Get a concrete type given a python value. Return None f this ConstantTyper cannot type the constant"""
<|... | stack_v2_sparse_classes_75kplus_train_068270 | 10,580 | permissive | [
{
"docstring": "Initialize to the given type universe",
"name": "__init__",
"signature": "def __init__(self, universe, typetable, handler_table)"
},
{
"docstring": "Get a concrete type given a python value. Return None f this ConstantTyper cannot type the constant",
"name": "typeof",
"si... | 2 | stack_v2_sparse_classes_30k_train_019082 | Implement the Python class `ConstantTyper` described below.
Class description:
Implement the ConstantTyper class.
Method signatures and docstrings:
- def __init__(self, universe, typetable, handler_table): Initialize to the given type universe
- def typeof(self, value): Get a concrete type given a python value. Retur... | Implement the Python class `ConstantTyper` described below.
Class description:
Implement the ConstantTyper class.
Method signatures and docstrings:
- def __init__(self, universe, typetable, handler_table): Initialize to the given type universe
- def typeof(self, value): Get a concrete type given a python value. Retur... | 35546517b27764a9120f6dfcd82eba7f4dd858cb | <|skeleton|>
class ConstantTyper:
def __init__(self, universe, typetable, handler_table):
"""Initialize to the given type universe"""
<|body_0|>
def typeof(self, value):
"""Get a concrete type given a python value. Return None f this ConstantTyper cannot type the constant"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstantTyper:
def __init__(self, universe, typetable, handler_table):
"""Initialize to the given type universe"""
self.universe = universe
self.typetable = typetable
self.handler_table = handler_table
def typeof(self, value):
"""Get a concrete type given a python ... | the_stack_v2_python_sparse | oldnumba/typesystem/itypesystem.py | laserson/numba | train | 1 | |
625707c7629edefa52ea0ec8910ee17009199eea | [
"r = len(grid)\nc = len(grid[0])\ncol_sum = [0 for i in range(c)]\ncol_sum[0] = grid[0][0]\nfor j in range(1, c):\n col_sum[j] += col_sum[j - 1] + grid[0][j]\nfor i in range(1, r):\n col_sum[0] += grid[i][0]\n for j in range(1, c):\n col_sum[j] = min(col_sum[j - 1], col_sum[j]) + grid[i][j]\nreturn ... | <|body_start_0|>
r = len(grid)
c = len(grid[0])
col_sum = [0 for i in range(c)]
col_sum[0] = grid[0][0]
for j in range(1, c):
col_sum[j] += col_sum[j - 1] + grid[0][j]
for i in range(1, r):
col_sum[0] += grid[i][0]
for j in range(1, c):... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th element of the next row Checks for sum above and below (arr[i-1], arr[i]) which is updated after... | stack_v2_sparse_classes_75kplus_train_068271 | 2,430 | permissive | [
{
"docstring": "Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th element of the next row Checks for sum above and below (arr[i-1], arr[i]) which is updated after every iteration",
"name": "minPathSum",
... | 2 | stack_v2_sparse_classes_30k_test_000203 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th... | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | <|skeleton|>
class Solution:
def minPathSum(self, grid):
"""Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th element of the next row Checks for sum above and below (arr[i-1], arr[i]) which is updated after... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minPathSum(self, grid):
"""Solution that uses O(m) space Uses an array the length of a row to store every sum above cell in question. Array[0] in this case is the sum of the 0th element of the next row Checks for sum above and below (arr[i-1], arr[i]) which is updated after every iterati... | the_stack_v2_python_sparse | Leetcode/64.minimum-path-sum.py | EdwaRen/Competitve-Programming | train | 1 | |
b092d63aaba3c584dabbd74fc66fc874a02956fe | [
"super(QNetwork, self).__init__()\nself.seed = torch.manual_seed(seed)\n'*** YOUR CODE HERE ***'\nself.fc1 = nn.Linear(in_features=state_size, out_features=64)\nself.fc2 = nn.Linear(in_features=64, out_features=64)\nself.output = nn.Linear(in_features=64, out_features=action_size)",
"x = F.relu(self.fc1(state))\n... | <|body_start_0|>
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
'*** YOUR CODE HERE ***'
self.fc1 = nn.Linear(in_features=state_size, out_features=64)
self.fc2 = nn.Linear(in_features=64, out_features=64)
self.output = nn.Linear(in_features=64, out_f... | Actor (Policy) Model. | QNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_068272 | 1,981 | no_license | [
{
"docstring": "Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed",
"name": "__init__",
"signature": "def __init__(self, state_size, action_size, seed)"
},
{
"docstring": "Build a net... | 2 | stack_v2_sparse_classes_30k_train_003901 | Implement the Python class `QNetwork` described below.
Class description:
Actor (Policy) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each act... | Implement the Python class `QNetwork` described below.
Class description:
Actor (Policy) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each act... | 012d584b97706a8adb0ceaf58888ba7a1e1fa076 | <|skeleton|>
class QNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed"""
super(QNetwork, self).__init__(... | the_stack_v2_python_sparse | labs/lunar_lander/model.py | ennnas/rl-nanodegree | train | 0 |
4906642ef79dbec3fead6b19fb40172ed72a6254 | [
"result = []\nfor i in range(len(nums)):\n tn = nums\n loo = 1\n for j in range(len(tn)):\n if i == j:\n continue\n loo = loo * tn[j]\n result.append(loo)\nreturn result",
"if not nums:\n return []\nn = len(nums)\nresult = [1] * n\nfor i in range(1, n):\n result[i] = res... | <|body_start_0|>
result = []
for i in range(len(nums)):
tn = nums
loo = 1
for j in range(len(tn)):
if i == j:
continue
loo = loo * tn[j]
result.append(loo)
return result
<|end_body_0|>
<|body_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
"""out of times :param nums: :return:"""
<|body_0|>
def productExceptSelfV2(self, nums):
"""思路1 我们以一个4个元素的数组为例,nums=[a1, a2, a3, a4]。 想在O(n)时间复杂度完成最终的数组输出,res=[a2*a3*a4, a1*a3*a4, a1*a2*a4, a2*a3*a4]。 比较好的解决方法是构造两个数组相乘: [1... | stack_v2_sparse_classes_75kplus_train_068273 | 1,338 | no_license | [
{
"docstring": "out of times :param nums: :return:",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
},
{
"docstring": "思路1 我们以一个4个元素的数组为例,nums=[a1, a2, a3, a4]。 想在O(n)时间复杂度完成最终的数组输出,res=[a2*a3*a4, a1*a3*a4, a1*a2*a4, a2*a3*a4]。 比较好的解决方法是构造两个数组相乘: [1, a1, a1*a2, a1*... | 2 | stack_v2_sparse_classes_30k_train_047418 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): out of times :param nums: :return:
- def productExceptSelfV2(self, nums): 思路1 我们以一个4个元素的数组为例,nums=[a1, a2, a3, a4]。 想在O(n)时间复杂度完成最终的数组输出,res=[a... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): out of times :param nums: :return:
- def productExceptSelfV2(self, nums): 思路1 我们以一个4个元素的数组为例,nums=[a1, a2, a3, a4]。 想在O(n)时间复杂度完成最终的数组输出,res=[a... | 85e7d105b379ccabab31ee698b32cac57d3ba53e | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
"""out of times :param nums: :return:"""
<|body_0|>
def productExceptSelfV2(self, nums):
"""思路1 我们以一个4个元素的数组为例,nums=[a1, a2, a3, a4]。 想在O(n)时间复杂度完成最终的数组输出,res=[a2*a3*a4, a1*a3*a4, a1*a2*a4, a2*a3*a4]。 比较好的解决方法是构造两个数组相乘: [1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def productExceptSelf(self, nums):
"""out of times :param nums: :return:"""
result = []
for i in range(len(nums)):
tn = nums
loo = 1
for j in range(len(tn)):
if i == j:
continue
loo = loo ... | the_stack_v2_python_sparse | python/LeetCode/Product_Of_Array_Except_Self.py | jiazifa/developNoteBook | train | 2 | |
1670b7ccccadbd625158676cd32e1263ea8162c9 | [
"self._duration = duration\nself._cache = dict()\nself._cache_lock = RLock()",
"if duration is None:\n duration = self._duration\nwith self._cache_lock:\n if key in self._cache:\n _, job = self._cache.get(key)\n job.cancel()\n if duration > 0:\n job = Job(self._remove_item, timedelta... | <|body_start_0|>
self._duration = duration
self._cache = dict()
self._cache_lock = RLock()
<|end_body_0|>
<|body_start_1|>
if duration is None:
duration = self._duration
with self._cache_lock:
if key in self._cache:
_, job = self._cache.ge... | Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache. | Cache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cache:
"""Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache."""
def __init__(self, duration):
"""Create a new C... | stack_v2_sparse_classes_75kplus_train_068274 | 2,523 | no_license | [
{
"docstring": "Create a new Cache instance. Args: duration: default duration in seconds to use for items, it can be overriden when adding an item",
"name": "__init__",
"signature": "def __init__(self, duration)"
},
{
"docstring": "Adds an item to the cache When an item is added with a positive ... | 4 | null | Implement the Python class `Cache` described below.
Class description:
Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache.
Method signatures and d... | Implement the Python class `Cache` described below.
Class description:
Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache.
Method signatures and d... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class Cache:
"""Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache."""
def __init__(self, duration):
"""Create a new C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cache:
"""Utility class to cache and expire items given a certain duration There is no distinction as to what kind of items can be cached in a given instance, therefore, items of different types can be combined within the same cache."""
def __init__(self, duration):
"""Create a new Cache instance... | the_stack_v2_python_sparse | nio/util/cache.py | niolabs/nio | train | 5 |
8a2c625dc5abf745fd4f36636544e1834c8c2ff8 | [
"create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)\ncreate_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=constants.LISTENERS))\ncreate_listener_flow.add(amphora_driver_tasks.ListenersUpdate(requires=constants.LOADBALANCER_ID))\ncreate_listener_flow.add(network_tasks.U... | <|body_start_0|>
create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)
create_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=constants.LISTENERS))
create_listener_flow.add(amphora_driver_tasks.ListenersUpdate(requires=constants.LOADBALANCER_ID))
... | ListenerFlows | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
<|body_0|>
def get_create_all_listeners_flow(self):
"""Create a flow to create all listeners :returns: The flow for creating all lis... | stack_v2_sparse_classes_75kplus_train_068275 | 5,910 | permissive | [
{
"docstring": "Create a flow to create a listener :returns: The flow for creating a listener",
"name": "get_create_listener_flow",
"signature": "def get_create_listener_flow(self)"
},
{
"docstring": "Create a flow to create all listeners :returns: The flow for creating all listeners",
"name... | 5 | stack_v2_sparse_classes_30k_test_002323 | Implement the Python class `ListenerFlows` described below.
Class description:
Implement the ListenerFlows class.
Method signatures and docstrings:
- def get_create_listener_flow(self): Create a flow to create a listener :returns: The flow for creating a listener
- def get_create_all_listeners_flow(self): Create a fl... | Implement the Python class `ListenerFlows` described below.
Class description:
Implement the ListenerFlows class.
Method signatures and docstrings:
- def get_create_listener_flow(self): Create a flow to create a listener :returns: The flow for creating a listener
- def get_create_all_listeners_flow(self): Create a fl... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
<|body_0|>
def get_create_all_listeners_flow(self):
"""Create a flow to create all listeners :returns: The flow for creating all lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListenerFlows:
def get_create_listener_flow(self):
"""Create a flow to create a listener :returns: The flow for creating a listener"""
create_listener_flow = linear_flow.Flow(constants.CREATE_LISTENER_FLOW)
create_listener_flow.add(lifecycle_tasks.ListenersToErrorOnRevertTask(requires=... | the_stack_v2_python_sparse | octavia/controller/worker/v2/flows/listener_flows.py | openstack/octavia | train | 147 | |
cadd4a87168fff671770e8c1d8c94561f2533b21 | [
"balance = 0\nstring_buffer = []\nfor ch in S:\n if ch == '(':\n if balance == 0:\n balance += 1\n continue\n else:\n balance += 1\n string_buffer.append(ch)\n else:\n balance -= 1\n if balance == 0:\n continue\n else:\n... | <|body_start_0|>
balance = 0
string_buffer = []
for ch in S:
if ch == '(':
if balance == 0:
balance += 1
continue
else:
balance += 1
string_buffer.append(ch)
el... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeOuterParentheses(self, S):
"""time O(n) space O(n) :type S: str :rtype: str"""
<|body_0|>
def removeOuterParentheses_clear(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
balance = 0
... | stack_v2_sparse_classes_75kplus_train_068276 | 1,238 | no_license | [
{
"docstring": "time O(n) space O(n) :type S: str :rtype: str",
"name": "removeOuterParentheses",
"signature": "def removeOuterParentheses(self, S)"
},
{
"docstring": ":type S: str :rtype: str",
"name": "removeOuterParentheses_clear",
"signature": "def removeOuterParentheses_clear(self, ... | 2 | stack_v2_sparse_classes_30k_train_053648 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeOuterParentheses(self, S): time O(n) space O(n) :type S: str :rtype: str
- def removeOuterParentheses_clear(self, S): :type S: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeOuterParentheses(self, S): time O(n) space O(n) :type S: str :rtype: str
- def removeOuterParentheses_clear(self, S): :type S: str :rtype: str
<|skeleton|>
class Solut... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def removeOuterParentheses(self, S):
"""time O(n) space O(n) :type S: str :rtype: str"""
<|body_0|>
def removeOuterParentheses_clear(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeOuterParentheses(self, S):
"""time O(n) space O(n) :type S: str :rtype: str"""
balance = 0
string_buffer = []
for ch in S:
if ch == '(':
if balance == 0:
balance += 1
continue
... | the_stack_v2_python_sparse | LeetCode/Stack/1021_remove_outermost_parentheses.py | XyK0907/for_work | train | 0 | |
5320e3b192deada5d1a21d7f1c212cdbf25ff8df | [
"self.server = server\nself.key = key\nself.debug = debug\nself.logdupes = True\nself.bf = BloomFilter(server, key)",
"fp = self.request_fingerprint(request)\nif fp in self.bf:\n return True\nelse:\n self.bf.add(fp)\n return False"
] | <|body_start_0|>
self.server = server
self.key = key
self.debug = debug
self.logdupes = True
self.bf = BloomFilter(server, key)
<|end_body_0|>
<|body_start_1|>
fp = self.request_fingerprint(request)
if fp in self.bf:
return True
else:
... | BFDupeFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BFDupeFilter:
def __init__(self, server, key, debug=False):
"""Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redis key Where to store fingerprints. debug : bool, optional Whether to log filtered requests."""
... | stack_v2_sparse_classes_75kplus_train_068277 | 2,295 | no_license | [
{
"docstring": "Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redis key Where to store fingerprints. debug : bool, optional Whether to log filtered requests.",
"name": "__init__",
"signature": "def __init__(self, server, key, debu... | 2 | stack_v2_sparse_classes_30k_train_054186 | Implement the Python class `BFDupeFilter` described below.
Class description:
Implement the BFDupeFilter class.
Method signatures and docstrings:
- def __init__(self, server, key, debug=False): Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redi... | Implement the Python class `BFDupeFilter` described below.
Class description:
Implement the BFDupeFilter class.
Method signatures and docstrings:
- def __init__(self, server, key, debug=False): Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redi... | fd3e5855e9ca4c76e13e3680383870155cc3bb1a | <|skeleton|>
class BFDupeFilter:
def __init__(self, server, key, debug=False):
"""Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redis key Where to store fingerprints. debug : bool, optional Whether to log filtered requests."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BFDupeFilter:
def __init__(self, server, key, debug=False):
"""Initialize the duplicates filter. Parameters ---------- server : redis.StrictRedis The redis server instance. key : str Redis key Where to store fingerprints. debug : bool, optional Whether to log filtered requests."""
self.server ... | the_stack_v2_python_sparse | crawler/used_car/dupefilter.py | jwyx3/capstone | train | 2 | |
dfdfa68417d9f47f51319862aca75b714a3ad0cf | [
"self._use_layer_norm_att = use_layer_norm_att\nself._use_layer_norm_ffn = use_layer_norm_ffn\nself._use_spec_norm_att = use_spec_norm_att\nself._use_spec_norm_ffn = use_spec_norm_ffn\nself._spec_norm_kwargs = spec_norm_kwargs\nfeedforward_cls = functools.partial(SpectralNormalizedFeedforwardLayer, use_layer_norm=s... | <|body_start_0|>
self._use_layer_norm_att = use_layer_norm_att
self._use_layer_norm_ffn = use_layer_norm_ffn
self._use_spec_norm_att = use_spec_norm_att
self._use_spec_norm_ffn = use_spec_norm_ffn
self._spec_norm_kwargs = spec_norm_kwargs
feedforward_cls = functools.parti... | Transformer layer with spectral-normalized dense layers. | SpectralNormalizedTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralNormalizedTransformer:
"""Transformer layer with spectral-normalized dense layers."""
def __init__(self, use_layer_norm_att: bool=True, use_layer_norm_ffn: bool=True, use_spec_norm_att: bool=False, use_spec_norm_ffn: bool=False, spec_norm_kwargs: Optional[Mapping[str, Any]]=None, **k... | stack_v2_sparse_classes_75kplus_train_068278 | 24,406 | permissive | [
{
"docstring": "Initializer. Args: use_layer_norm_att: Whether to use layer normalization in the attention layer. use_layer_norm_ffn: Whether to use layer normalization in the feedforward layer. use_spec_norm_att: Whether to use spectral normalization in the attention layer. use_spec_norm_ffn: Whether to use sp... | 2 | stack_v2_sparse_classes_30k_val_001442 | Implement the Python class `SpectralNormalizedTransformer` described below.
Class description:
Transformer layer with spectral-normalized dense layers.
Method signatures and docstrings:
- def __init__(self, use_layer_norm_att: bool=True, use_layer_norm_ffn: bool=True, use_spec_norm_att: bool=False, use_spec_norm_ffn:... | Implement the Python class `SpectralNormalizedTransformer` described below.
Class description:
Transformer layer with spectral-normalized dense layers.
Method signatures and docstrings:
- def __init__(self, use_layer_norm_att: bool=True, use_layer_norm_ffn: bool=True, use_spec_norm_att: bool=False, use_spec_norm_ffn:... | f5f6f50f82bd441339c9d9efbef3f09e72c5fef6 | <|skeleton|>
class SpectralNormalizedTransformer:
"""Transformer layer with spectral-normalized dense layers."""
def __init__(self, use_layer_norm_att: bool=True, use_layer_norm_ffn: bool=True, use_spec_norm_att: bool=False, use_spec_norm_ffn: bool=False, spec_norm_kwargs: Optional[Mapping[str, Any]]=None, **k... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectralNormalizedTransformer:
"""Transformer layer with spectral-normalized dense layers."""
def __init__(self, use_layer_norm_att: bool=True, use_layer_norm_ffn: bool=True, use_spec_norm_att: bool=False, use_spec_norm_ffn: bool=False, spec_norm_kwargs: Optional[Mapping[str, Any]]=None, **kwargs):
... | the_stack_v2_python_sparse | uncertainty_baselines/models/bert_sngp.py | google/uncertainty-baselines | train | 1,235 |
83224d20b07c4b152e8da0ac797dc4cadfc3404b | [
"output = self.build(FilePath(args[0]).child('docs'))\nif output:\n sys.stdout.write('Unclean build:\\n{}\\n'.format(output))\n raise sys.exit(1)",
"if buildDir is None:\n buildDir = docDir.parent().child('doc')\ndoctreeDir = buildDir.child('doctrees')\noutput = runCommand(['sphinx-build', '-q', '-b', 'h... | <|body_start_0|>
output = self.build(FilePath(args[0]).child('docs'))
if output:
sys.stdout.write('Unclean build:\n{}\n'.format(output))
raise sys.exit(1)
<|end_body_0|>
<|body_start_1|>
if buildDir is None:
buildDir = docDir.parent().child('doc')
doc... | Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory called "source" which contains the Sphinx source files, and BUILDDIR is the direct... | SphinxBuilder | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphinxBuilder:
"""Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory called "source" which contains the Sphinx... | stack_v2_sparse_classes_75kplus_train_068279 | 19,015 | permissive | [
{
"docstring": "Build the main documentation. @type args: list of str @param args: The command line arguments to process. This must contain one string argument: the path to the root of a Twisted checkout. Additional arguments will be ignored for compatibility with legacy build infrastructure.",
"name": "mai... | 2 | stack_v2_sparse_classes_30k_train_018087 | Implement the Python class `SphinxBuilder` described below.
Class description:
Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory ca... | Implement the Python class `SphinxBuilder` described below.
Class description:
Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory ca... | 5cee0a8c4180a3108538b4e4ce945a18726595a6 | <|skeleton|>
class SphinxBuilder:
"""Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory called "source" which contains the Sphinx... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SphinxBuilder:
"""Generate HTML documentation using Sphinx. Generates and runs a shell command that looks something like:: sphinx-build -b html -d [BUILDDIR]/doctrees [DOCDIR]/source [BUILDDIR]/html where DOCDIR is a directory containing another directory called "source" which contains the Sphinx source files... | the_stack_v2_python_sparse | venv/Lib/site-packages/twisted/python/_release.py | zoelesv/Smathchat | train | 9 |
9f6fd7899f8391d4eb13df3e8550197d32582d3a | [
"self.num_workers: int = args.num_workers\nself.batch_size: Dict[str, int] = {'train': args.batch_size, 'val': args.batch_size}\nself.lr: float = args.lr\nself.num_epochs: int = args.num_epochs\nself.current_epoch: int = 0\nself.phases: Tuple[str, ...] = ('train', 'val')\nself.val_freq: int = args.val_freq\nif not ... | <|body_start_0|>
self.num_workers: int = args.num_workers
self.batch_size: Dict[str, int] = {'train': args.batch_size, 'val': args.batch_size}
self.lr: float = args.lr
self.num_epochs: int = args.num_epochs
self.current_epoch: int = 0
self.phases: Tuple[str, ...] = ('trai... | An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epochs : int Number of epochs current_epoch : int Current epoch phases : list... | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epochs : int Number of epochs current_epoc... | stack_v2_sparse_classes_75kplus_train_068280 | 8,396 | no_license | [
{
"docstring": "Initialize a Trainer object Parameters ---------- model : torch.nn.Module PyTorch model of your NN args : :obj: CLI arguments",
"name": "__init__",
"signature": "def __init__(self, model, args)"
},
{
"docstring": "Forward pass Parameters ---------- images : torch.Tensor Input to ... | 4 | stack_v2_sparse_classes_30k_train_029908 | Implement the Python class `Trainer` described below.
Class description:
An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epo... | Implement the Python class `Trainer` described below.
Class description:
An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epo... | ef8304bc07ff9ece10d7e3ef1f72e6961b679bfb | <|skeleton|>
class Trainer:
"""An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epochs : int Number of epochs current_epoc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trainer:
"""An object to encompass all training and validation Training loop, validation loop, logging, checkpoints are all implemented here. Attributes ---------- num_workers : int Number of workers batch_size : int Batch size lr : int Learning rate num_epochs : int Number of epochs current_epoch : int Curre... | the_stack_v2_python_sparse | torchseg/trainer.py | rshwndsz/torch-seg | train | 1 |
155ac6be79e4931c06137a9d729858304184e822 | [
"dataset = make_image_dataset(pd.Series(['img1.png', 'img2', 'img3']), np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1]]), [])\nfor d in dataset.take(1):\n self.assertEqual(d['image_paths'], 'img1.png')",
"dataset = make_image_dataset(pd.Series(['img1.png', 'img2', 'img3']), np.array([[1, 0, 0, 0], [1, 1, 0,... | <|body_start_0|>
dataset = make_image_dataset(pd.Series(['img1.png', 'img2', 'img3']), np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1]]), [])
for d in dataset.take(1):
self.assertEqual(d['image_paths'], 'img1.png')
<|end_body_0|>
<|body_start_1|>
dataset = make_image_dataset(pd.S... | TestConvertToTfDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConvertToTfDataset:
def test_make_image_dataset(self):
"""test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully"""
<|body_0|>
def test_make_image_dataset_additional(self):
"""test if a set of strings and array... | stack_v2_sparse_classes_75kplus_train_068281 | 1,221 | permissive | [
{
"docstring": "test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully",
"name": "test_make_image_dataset",
"signature": "def test_make_image_dataset(self)"
},
{
"docstring": "test if a set of strings and arrays (for image path and label) can ... | 2 | stack_v2_sparse_classes_30k_val_000511 | Implement the Python class `TestConvertToTfDataset` described below.
Class description:
Implement the TestConvertToTfDataset class.
Method signatures and docstrings:
- def test_make_image_dataset(self): test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully
- def t... | Implement the Python class `TestConvertToTfDataset` described below.
Class description:
Implement the TestConvertToTfDataset class.
Method signatures and docstrings:
- def test_make_image_dataset(self): test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully
- def t... | ffbf24e740d9154312d02b9f775816ed4b3d4691 | <|skeleton|>
class TestConvertToTfDataset:
def test_make_image_dataset(self):
"""test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully"""
<|body_0|>
def test_make_image_dataset_additional(self):
"""test if a set of strings and array... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConvertToTfDataset:
def test_make_image_dataset(self):
"""test if a set of strings and arrays (for image path and label) can be turned into a tf.dataset successfully"""
dataset = make_image_dataset(pd.Series(['img1.png', 'img2', 'img3']), np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1]]... | the_stack_v2_python_sparse | unittests/test_dataset_creation/test_convert_to_tf_dataset.py | imsb-uke/ecarenet | train | 3 | |
e0cc80fa1dde0ee6cbf688a3230925e127f2e09f | [
"super().__init__(mesh=mesh, verbose=verbose)\nself.f = f\nself.rhoDC = rho\nself.rhoAC = rho * 1\nself.drhodm = -self.rhoDC\nif response is None:\n response = f.response(self.rhoDC)\nself.rhoaDC = response\nself.rhoaAC = pg.Vector(self.rhoaDC)\nself.dmdrhoa = -1.0 / self.rhoaDC\nself.J = pg.matrix.MultLeftRight... | <|body_start_0|>
super().__init__(mesh=mesh, verbose=verbose)
self.f = f
self.rhoDC = rho
self.rhoAC = rho * 1
self.drhodm = -self.rhoDC
if response is None:
response = f.response(self.rhoDC)
self.rhoaDC = response
self.rhoaAC = pg.Vector(self.... | DC/IP modelling class using an (FD-based) approach. | IPSeigelModelling | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPSeigelModelling:
"""DC/IP modelling class using an (FD-based) approach."""
def __init__(self, f, mesh, rho, verbose=False, response=None):
"""Init class with DC forward operator and resistivity vector."""
<|body_0|>
def response(self, m):
"""Return forward resp... | stack_v2_sparse_classes_75kplus_train_068282 | 4,290 | permissive | [
{
"docstring": "Init class with DC forward operator and resistivity vector.",
"name": "__init__",
"signature": "def __init__(self, f, mesh, rho, verbose=False, response=None)"
},
{
"docstring": "Return forward response as function of chargeability model.",
"name": "response",
"signature"... | 3 | null | Implement the Python class `IPSeigelModelling` described below.
Class description:
DC/IP modelling class using an (FD-based) approach.
Method signatures and docstrings:
- def __init__(self, f, mesh, rho, verbose=False, response=None): Init class with DC forward operator and resistivity vector.
- def response(self, m)... | Implement the Python class `IPSeigelModelling` described below.
Class description:
DC/IP modelling class using an (FD-based) approach.
Method signatures and docstrings:
- def __init__(self, f, mesh, rho, verbose=False, response=None): Init class with DC forward operator and resistivity vector.
- def response(self, m)... | 0f55444b624f390a674053f62ba1a05506deafa6 | <|skeleton|>
class IPSeigelModelling:
"""DC/IP modelling class using an (FD-based) approach."""
def __init__(self, f, mesh, rho, verbose=False, response=None):
"""Init class with DC forward operator and resistivity vector."""
<|body_0|>
def response(self, m):
"""Return forward resp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPSeigelModelling:
"""DC/IP modelling class using an (FD-based) approach."""
def __init__(self, f, mesh, rho, verbose=False, response=None):
"""Init class with DC forward operator and resistivity vector."""
super().__init__(mesh=mesh, verbose=verbose)
self.f = f
self.rhoDC... | the_stack_v2_python_sparse | pygimli/physics/ert/ipModelling.py | gimli-org/gimli | train | 307 |
7933e492f6d95a818e560852f787a28c66e452a0 | [
"self.long = long * DEG_RAD\nself.cola = cola * DEG_RAD\nself.x = RAYON_PLANETE * sin(self.cola) * cos(self.long)\nself.y = RAYON_PLANETE * sin(self.cola) * sin(self.long)\nself.z = RAYON_PLANETE * cos(self.cola)",
"x_dist = self.x - sat.x\ny_dist = self.y - sat.y\nz_dist = self.z - sat.z\nreturn hypot3(x_dist, y... | <|body_start_0|>
self.long = long * DEG_RAD
self.cola = cola * DEG_RAD
self.x = RAYON_PLANETE * sin(self.cola) * cos(self.long)
self.y = RAYON_PLANETE * sin(self.cola) * sin(self.long)
self.z = RAYON_PLANETE * cos(self.cola)
<|end_body_0|>
<|body_start_1|>
x_dist = self.... | Classe qui crée un point à la surface de la Terre à la position donnée : colat, long | Point | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Point:
"""Classe qui crée un point à la surface de la Terre à la position donnée : colat, long"""
def __init__(self, cola, long):
"""Initialise un point (en fonction des paramètres donnés)"""
<|body_0|>
def distance(self, sat):
"""Retourne le distance entre le po... | stack_v2_sparse_classes_75kplus_train_068283 | 10,986 | no_license | [
{
"docstring": "Initialise un point (en fonction des paramètres donnés)",
"name": "__init__",
"signature": "def __init__(self, cola, long)"
},
{
"docstring": "Retourne le distance entre le point et le satellite",
"name": "distance",
"signature": "def distance(self, sat)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_032171 | Implement the Python class `Point` described below.
Class description:
Classe qui crée un point à la surface de la Terre à la position donnée : colat, long
Method signatures and docstrings:
- def __init__(self, cola, long): Initialise un point (en fonction des paramètres donnés)
- def distance(self, sat): Retourne le... | Implement the Python class `Point` described below.
Class description:
Classe qui crée un point à la surface de la Terre à la position donnée : colat, long
Method signatures and docstrings:
- def __init__(self, cola, long): Initialise un point (en fonction des paramètres donnés)
- def distance(self, sat): Retourne le... | bb90efcbb3383a5168d77809bc8b05e790dedece | <|skeleton|>
class Point:
"""Classe qui crée un point à la surface de la Terre à la position donnée : colat, long"""
def __init__(self, cola, long):
"""Initialise un point (en fonction des paramètres donnés)"""
<|body_0|>
def distance(self, sat):
"""Retourne le distance entre le po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Point:
"""Classe qui crée un point à la surface de la Terre à la position donnée : colat, long"""
def __init__(self, cola, long):
"""Initialise un point (en fonction des paramètres donnés)"""
self.long = long * DEG_RAD
self.cola = cola * DEG_RAD
self.x = RAYON_PLANETE * si... | the_stack_v2_python_sparse | Python/TIPE/TIPE v.SPE.4.0.py | Solenoide420/Projects | train | 0 |
b67b406eb65443eca319ad1c4cf5145b6345592e | [
"keys = list(self.keys())\ntry:\n keys.remove(None)\nexcept ValueError:\n pass\nkeys.sort()\nkey = lookup_language(keys, language_ranges)\nreturn self[key]",
"if not self:\n raise ValueError('any() on empty map')\ntry:\n return self[None]\nexcept KeyError:\n return self[min(self)]"
] | <|body_start_0|>
keys = list(self.keys())
try:
keys.remove(None)
except ValueError:
pass
keys.sort()
key = lookup_language(keys, language_ranges)
return self[key]
<|end_body_0|>
<|body_start_1|>
if not self:
raise ValueError('a... | A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: any | LanguageMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageMap:
"""A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: any"""
def lookup(self, language_ra... | stack_v2_sparse_classes_75kplus_train_068284 | 40,933 | no_license | [
{
"docstring": "Perform an RFC4647 language range lookup on the keys in the dictionary. `language_ranges` must be a sequence of :class:`LanguageRange` instances. Return the entry in the dictionary with a key as produced by `lookup_language`. If `lookup_language` does not find a match and the mapping contains an... | 2 | stack_v2_sparse_classes_30k_train_047270 | Implement the Python class `LanguageMap` described below.
Class description:
A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: a... | Implement the Python class `LanguageMap` described below.
Class description:
A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: a... | f567347c1dc7013e086981b940c3c8e68b1f5af1 | <|skeleton|>
class LanguageMap:
"""A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: any"""
def lookup(self, language_ra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LanguageMap:
"""A :class:`dict` subclass specialized for holding :class:`LanugageTag` instances as keys. In addition to the interface provided by :class:`dict`, instances of this class also have the following methods: .. automethod:: lookup .. automethod:: any"""
def lookup(self, language_ranges):
... | the_stack_v2_python_sparse | venv/lib/python3.8/site-packages/aioxmpp/structs.py | migarbo1/SpyAgent | train | 0 |
622901b7ed3dddd61e16dfb858a3eb390bb64629 | [
"super().__init__()\nself.embedding_dim = embedding_dim\nself.num_filters = num_filters\nself.cnn_layers = ModuleList([Conv1d(in_channels=embedding_dim, out_channels=num_filters, kernel_size=kernel_size) for kernel_size in kernel_sizes])\nself.activtion = ReLU()",
"assert sequence.dim() == 3, f'tokens.dim: {seque... | <|body_start_0|>
super().__init__()
self.embedding_dim = embedding_dim
self.num_filters = num_filters
self.cnn_layers = ModuleList([Conv1d(in_channels=embedding_dim, out_channels=num_filters, kernel_size=kernel_size) for kernel_size in kernel_sizes])
self.activtion = ReLU()
<|end... | text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化 | CnnSeq2Vec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnnSeq2Vec:
"""text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化"""
def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int]):
"""初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :param kernel_sizes: kernel size"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_068285 | 3,349 | permissive | [
{
"docstring": "初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :param kernel_sizes: kernel size",
"name": "__init__",
"signature": "def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int])"
},
{
"docstring": "执行模型。对多个 kernel size 最终会将每一个 kernel 输出的... | 2 | stack_v2_sparse_classes_30k_train_054396 | Implement the Python class `CnnSeq2Vec` described below.
Class description:
text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化
Method signatures and docstrings:
- def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int]): 初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :para... | Implement the Python class `CnnSeq2Vec` described below.
Class description:
text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化
Method signatures and docstrings:
- def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int]): 初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :para... | 95511a5a12d3af4a102ecb7a4d10e09a7d9b8680 | <|skeleton|>
class CnnSeq2Vec:
"""text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化"""
def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int]):
"""初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :param kernel_sizes: kernel size"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CnnSeq2Vec:
"""text cnn 编码器,将文本经过cnn 完成的是 sequence 到 vector 转化"""
def __init__(self, embedding_dim: int, num_filters: int, kernel_sizes: List[int]):
"""初始化 :param embedding_dim: 输入的维度 :param num_filters: filter 数量,也就是输出维度 :param kernel_sizes: kernel size"""
super().__init__()
self... | the_stack_v2_python_sparse | easytext/modules/seq2vec/cnn_seq2vec.py | cuilunan/easytext | train | 1 |
9f3f628954de779253b554fbda7c6b718f9fb4b0 | [
"super().__init__(coordinator)\nself._site_info = site_info\nself._device_type = device_type\nself._version = status.version\nself.base_unique_id = '_'.join(powerwalls_serial_numbers)",
"device_info = {'identifiers': {(DOMAIN, self.base_unique_id)}, 'name': self._site_info.site_name, 'manufacturer': MANUFACTURER}... | <|body_start_0|>
super().__init__(coordinator)
self._site_info = site_info
self._device_type = device_type
self._version = status.version
self.base_unique_id = '_'.join(powerwalls_serial_numbers)
<|end_body_0|>
<|body_start_1|>
device_info = {'identifiers': {(DOMAIN, sel... | Base class for powerwall entities. | PowerWallEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerWallEntity:
"""Base class for powerwall entities."""
def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers):
"""Initialize the sensor."""
<|body_0|>
def device_info(self):
"""Powerwall device info."""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_068286 | 1,145 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers)"
},
{
"docstring": "Powerwall device info.",
"name": "device_info",
"signature": "def device_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048815 | Implement the Python class `PowerWallEntity` described below.
Class description:
Base class for powerwall entities.
Method signatures and docstrings:
- def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers): Initialize the sensor.
- def device_info(self): Powerwall device info. | Implement the Python class `PowerWallEntity` described below.
Class description:
Base class for powerwall entities.
Method signatures and docstrings:
- def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers): Initialize the sensor.
- def device_info(self): Powerwall device info.
<|... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class PowerWallEntity:
"""Base class for powerwall entities."""
def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers):
"""Initialize the sensor."""
<|body_0|>
def device_info(self):
"""Powerwall device info."""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PowerWallEntity:
"""Base class for powerwall entities."""
def __init__(self, coordinator, site_info, status, device_type, powerwalls_serial_numbers):
"""Initialize the sensor."""
super().__init__(coordinator)
self._site_info = site_info
self._device_type = device_type
... | the_stack_v2_python_sparse | homeassistant/components/powerwall/entity.py | BenWoodford/home-assistant | train | 11 |
339ca0b9b4c4fc9ad8d09864da097e917006b846 | [
"with codecs.open(input_file, mode='r', encoding=enc) as in_f, codecs.open(output_file, mode='w', encoding='utf-8') as out_f:\n reader = csv.DictReader(in_f)\n writer = csv.writer(out_f)\n writer.writerow(remains)\n for row in reader:\n contents = []\n for col in remains:\n cont... | <|body_start_0|>
with codecs.open(input_file, mode='r', encoding=enc) as in_f, codecs.open(output_file, mode='w', encoding='utf-8') as out_f:
reader = csv.DictReader(in_f)
writer = csv.writer(out_f)
writer.writerow(remains)
for row in reader:
conte... | File | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class File:
def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'):
"""Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new cs... | stack_v2_sparse_classes_75kplus_train_068287 | 2,975 | permissive | [
{
"docstring": "Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new csv enc=utf-8 (str): encording",
"name": "remove_csv_col",
"signature": "def remove_... | 3 | stack_v2_sparse_classes_30k_train_034867 | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file ... | Implement the Python class `File` described below.
Class description:
Implement the File class.
Method signatures and docstrings:
- def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file ... | e523653a9f96f84810c06824133c3a146a053b75 | <|skeleton|>
class File:
def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'):
"""Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new cs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class File:
def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'):
"""Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new csv enc=utf-8 (s... | the_stack_v2_python_sparse | cliboa/adapter/file.py | BrainPad/cliboa | train | 27 | |
820e2dff412b2620efbc7822dd2001f3da8b03a8 | [
"integ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nalphabet = [' ', '*', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\nindex = dict(zip(integ, alphabet))\nif i < 0:\n return (i, A, B, C)\nelif A[i] == len(index[B[i]]):\n for j in range(i, len(A)):\n A[j] = 0\n i = i - 1\n A[i] = A[i] + 1\n ... | <|body_start_0|>
integ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
alphabet = [' ', '*', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
index = dict(zip(integ, alphabet))
if i < 0:
return (i, A, B, C)
elif A[i] == len(index[B[i]]):
for j in range(i, len(A)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reprint(self, i, A, B, C):
""":type i: num :type digit:str :rtype: List[str], num"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
integ = [0, 1,... | stack_v2_sparse_classes_75kplus_train_068288 | 1,400 | no_license | [
{
"docstring": ":type i: num :type digit:str :rtype: List[str], num",
"name": "reprint",
"signature": "def reprint(self, i, A, B, C)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011171 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reprint(self, i, A, B, C): :type i: num :type digit:str :rtype: List[str], num
- def letterCombinations(self, digits): :type digits: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reprint(self, i, A, B, C): :type i: num :type digit:str :rtype: List[str], num
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
<|skeleton|>
class... | 9752533bc76ce5ecb881f61e33a3bc4b20dcf666 | <|skeleton|>
class Solution:
def reprint(self, i, A, B, C):
""":type i: num :type digit:str :rtype: List[str], num"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reprint(self, i, A, B, C):
""":type i: num :type digit:str :rtype: List[str], num"""
integ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
alphabet = [' ', '*', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
index = dict(zip(integ, alphabet))
if i < 0:
... | the_stack_v2_python_sparse | 017. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.py | 603lzy/LeetCode | train | 3 | |
a7f2cfc2a00feec3a4656898afc46df083090709 | [
"self.clerk = clerk\nself.fID = fID\nself.fclass = fclass",
"if name == 'ID' or isinstance(getattr(stub.__class__, name), linkset):\n pass\nelse:\n stub.removeInjector(self.inject)\n stub.removeObserver(self.inject)\n if hasattr(stub.private, 'isStub'):\n pri = stub.private\n raw = self.... | <|body_start_0|>
self.clerk = clerk
self.fID = fID
self.fclass = fclass
<|end_body_0|>
<|body_start_1|>
if name == 'ID' or isinstance(getattr(stub.__class__, name), linkset):
pass
else:
stub.removeInjector(self.inject)
stub.removeObserver(self... | LinkInjector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_068289 | 20,272 | no_license | [
{
"docstring": "Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.",
"name": "__init__",
"signature": "def __init__(self, clerk, fclass, fID)"
},... | 2 | stack_v2_sparse_classes_30k_train_022447 | Implement the Python class `LinkInjector` described below.
Class description:
Implement the LinkInjector class.
Method signatures and docstrings:
- def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i... | Implement the Python class `LinkInjector` described below.
Class description:
Implement the LinkInjector class.
Method signatures and docstrings:
- def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i... | 1ea55a754a7568b8df2bab297a8036c0b3a671e0 | <|skeleton|>
class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkInjector:
def __init__(self, clerk, fclass, fID):
"""Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen."""
self.clerk = clerk
... | the_stack_v2_python_sparse | code/clerks.py | tangentstorm/workshop | train | 0 | |
07566a18861c063a9b936c225199d2263dad8460 | [
"self.model_class = model_class\nself.initial = initial\nself.requires = requires\nself.fields = fields\nif queryset is None:\n self.queryset = model_class.objects.all()\nelse:\n self.queryset = queryset\nself.label = underscore(model_class.__name__)",
"app_name = self.model_class._meta.app_config.name\napp... | <|body_start_0|>
self.model_class = model_class
self.initial = initial
self.requires = requires
self.fields = fields
if queryset is None:
self.queryset = model_class.objects.all()
else:
self.queryset = queryset
self.label = underscore(model... | A representation of a fixture for a single application model. | Fixture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fixture:
"""A representation of a fixture for a single application model."""
def __init__(self, model_class, queryset=None, initial=False, requires=[], fields=None):
"""Create a new fixture. Args: model_class (django.db.models.Model): The model class for the fixture queryset (django.... | stack_v2_sparse_classes_75kplus_train_068290 | 3,006 | no_license | [
{
"docstring": "Create a new fixture. Args: model_class (django.db.models.Model): The model class for the fixture queryset (django.db.models.query.QuerySet): A queryset of models Keyword Args: initial (bool): Whether the fixture should only be run to initialize data requires (list[django.db.models.model]): All ... | 4 | null | Implement the Python class `Fixture` described below.
Class description:
A representation of a fixture for a single application model.
Method signatures and docstrings:
- def __init__(self, model_class, queryset=None, initial=False, requires=[], fields=None): Create a new fixture. Args: model_class (django.db.models.... | Implement the Python class `Fixture` described below.
Class description:
A representation of a fixture for a single application model.
Method signatures and docstrings:
- def __init__(self, model_class, queryset=None, initial=False, requires=[], fields=None): Create a new fixture. Args: model_class (django.db.models.... | 6ca38962d08a6ca154434a1f78235155710ffeec | <|skeleton|>
class Fixture:
"""A representation of a fixture for a single application model."""
def __init__(self, model_class, queryset=None, initial=False, requires=[], fields=None):
"""Create a new fixture. Args: model_class (django.db.models.Model): The model class for the fixture queryset (django.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fixture:
"""A representation of a fixture for a single application model."""
def __init__(self, model_class, queryset=None, initial=False, requires=[], fields=None):
"""Create a new fixture. Args: model_class (django.db.models.Model): The model class for the fixture queryset (django.db.models.que... | the_stack_v2_python_sparse | chiton/core/fixture.py | justinlocsei/chiton | train | 0 |
1c3e5c8702655c29df949a06672ab1a51bcebcac | [
"agent_now = request.user.userinfo.agent\ncompany_now = request.user.userinfo.company\nq = request.DATA.get('q', '')\ndata_list = models.SSADataTag.objects.filter(name__contains=q).filter(Q(agent=agent_now, company=company_now) | Q(agent=None, company=None)).values('id', 'name')\nnew_data_list = []\nfor data in dat... | <|body_start_0|>
agent_now = request.user.userinfo.agent
company_now = request.user.userinfo.company
q = request.DATA.get('q', '')
data_list = models.SSADataTag.objects.filter(name__contains=q).filter(Q(agent=agent_now, company=company_now) | Q(agent=None, company=None)).values('id', 'na... | 数据标签列表 | ETLDataTagSelect2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ETLDataTagSelect2:
"""数据标签列表"""
def post(self, request):
"""数据标签列表"""
<|body_0|>
def parsed_post(self, request, data_tag):
"""事件搜索"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
agent_now = request.user.userinfo.agent
company_now = requ... | stack_v2_sparse_classes_75kplus_train_068291 | 19,601 | no_license | [
{
"docstring": "数据标签列表",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "事件搜索",
"name": "parsed_post",
"signature": "def parsed_post(self, request, data_tag)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037585 | Implement the Python class `ETLDataTagSelect2` described below.
Class description:
数据标签列表
Method signatures and docstrings:
- def post(self, request): 数据标签列表
- def parsed_post(self, request, data_tag): 事件搜索 | Implement the Python class `ETLDataTagSelect2` described below.
Class description:
数据标签列表
Method signatures and docstrings:
- def post(self, request): 数据标签列表
- def parsed_post(self, request, data_tag): 事件搜索
<|skeleton|>
class ETLDataTagSelect2:
"""数据标签列表"""
def post(self, request):
"""数据标签列表"""
... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class ETLDataTagSelect2:
"""数据标签列表"""
def post(self, request):
"""数据标签列表"""
<|body_0|>
def parsed_post(self, request, data_tag):
"""事件搜索"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ETLDataTagSelect2:
"""数据标签列表"""
def post(self, request):
"""数据标签列表"""
agent_now = request.user.userinfo.agent
company_now = request.user.userinfo.company
q = request.DATA.get('q', '')
data_list = models.SSADataTag.objects.filter(name__contains=q).filter(Q(agent=age... | the_stack_v2_python_sparse | soc_ssa/views/event_views.py | sundw2015/841 | train | 4 |
c4c9293b9fb93a73c3e633d271c9942d218d3cb2 | [
"board_rule_test = BoardRules()\nboard_rule_test.create_board()\nboard_rule_test.setup_tile()\nnew_input = board_rule_test.get_board_letters()\nnew_input[7][7] = 'k'\nboard_rule_test.set_board_letters(new_input)\noutput = board_rule_test.get_board_letters()\nself.assertEqual(output[7][7], 'k')",
"dawg_test = Dawg... | <|body_start_0|>
board_rule_test = BoardRules()
board_rule_test.create_board()
board_rule_test.setup_tile()
new_input = board_rule_test.get_board_letters()
new_input[7][7] = 'k'
board_rule_test.set_board_letters(new_input)
output = board_rule_test.get_board_letter... | TestBoardRules | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBoardRules:
def test_set_board(self):
"""Verifying if set and get board letters are working after setup"""
<|body_0|>
def test_validate_board(self):
"""Validate the board see if words are correctly validated"""
<|body_1|>
def test_calculate_points(se... | stack_v2_sparse_classes_75kplus_train_068292 | 2,183 | permissive | [
{
"docstring": "Verifying if set and get board letters are working after setup",
"name": "test_set_board",
"signature": "def test_set_board(self)"
},
{
"docstring": "Validate the board see if words are correctly validated",
"name": "test_validate_board",
"signature": "def test_validate_b... | 3 | stack_v2_sparse_classes_30k_train_044737 | Implement the Python class `TestBoardRules` described below.
Class description:
Implement the TestBoardRules class.
Method signatures and docstrings:
- def test_set_board(self): Verifying if set and get board letters are working after setup
- def test_validate_board(self): Validate the board see if words are correctl... | Implement the Python class `TestBoardRules` described below.
Class description:
Implement the TestBoardRules class.
Method signatures and docstrings:
- def test_set_board(self): Verifying if set and get board letters are working after setup
- def test_validate_board(self): Validate the board see if words are correctl... | 18a953e9bac6cc197266c7234f38296027c2e23d | <|skeleton|>
class TestBoardRules:
def test_set_board(self):
"""Verifying if set and get board letters are working after setup"""
<|body_0|>
def test_validate_board(self):
"""Validate the board see if words are correctly validated"""
<|body_1|>
def test_calculate_points(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBoardRules:
def test_set_board(self):
"""Verifying if set and get board letters are working after setup"""
board_rule_test = BoardRules()
board_rule_test.create_board()
board_rule_test.setup_tile()
new_input = board_rule_test.get_board_letters()
new_input[7]... | the_stack_v2_python_sparse | unit_testing/board_rules_test.py | tijmenjoppe/IPASS_Scrabble | train | 0 | |
54f3cf1a5d1b078434f735418a3b97b1294ac355 | [
"super().__init__()\nself.name = ''\nself.position = ()",
"super().initialize(hp)\nself.name = name\nself.position = position"
] | <|body_start_0|>
super().__init__()
self.name = ''
self.position = ()
<|end_body_0|>
<|body_start_1|>
super().initialize(hp)
self.name = name
self.position = position
<|end_body_1|>
| Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
def __init__(self):
"""Player class constructor"""
<|body_0|>
def initialize(self, hp, name, position):
"""Initializes player's attributes :param int hp: :param str name: :param tuple position:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_068293 | 660 | no_license | [
{
"docstring": "Player class constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initializes player's attributes :param int hp: :param str name: :param tuple position:",
"name": "initialize",
"signature": "def initialize(self, hp, name, position)"
}
] | 2 | null | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self): Player class constructor
- def initialize(self, hp, name, position): Initializes player's attributes :param int hp: :param str name: :param tuple position: | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self): Player class constructor
- def initialize(self, hp, name, position): Initializes player's attributes :param int hp: :param str name: :param tuple position:
<|ske... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class Player:
def __init__(self):
"""Player class constructor"""
<|body_0|>
def initialize(self, hp, name, position):
"""Initializes player's attributes :param int hp: :param str name: :param tuple position:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
def __init__(self):
"""Player class constructor"""
super().__init__()
self.name = ''
self.position = ()
def initialize(self, hp, name, position):
"""Initializes player's attributes :param int hp: :param str name: :param tuple position:"""
super().in... | the_stack_v2_python_sparse | Dmytro_Shalimov/10/dungeon_game_shalimov/dungeon_game/my_player.py | SmischenkoB/campus_2018_python | train | 0 | |
a9618f24dc8e4bad15ec2241f7e4912d5d4091fa | [
"logger.debug('Initializing websocket state manager')\nself._websocket = websocket\nself.state = State()\nself.state.enqueue_message(AuthenticationRequiredMessage())\nself.state.start_authentication_timeout()",
"logger.debug('Starting websocket consumer')\nwhile not self.state.exit:\n msg = await self._websock... | <|body_start_0|>
logger.debug('Initializing websocket state manager')
self._websocket = websocket
self.state = State()
self.state.enqueue_message(AuthenticationRequiredMessage())
self.state.start_authentication_timeout()
<|end_body_0|>
<|body_start_1|>
logger.debug('Star... | A class for managing the inbound/outbound messages and state of a websocket session. | StateManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateManager:
"""A class for managing the inbound/outbound messages and state of a websocket session."""
def __init__(self, websocket: websockets.WebSocketServerProtocol):
"""Initializer."""
<|body_0|>
async def consumer_handler(self):
"""This is the primary asyn... | stack_v2_sparse_classes_75kplus_train_068294 | 6,011 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, websocket: websockets.WebSocketServerProtocol)"
},
{
"docstring": "This is the primary asynchronous method that is used for handling inbound websocket massages.",
"name": "consumer_handler",
"signature": ... | 5 | stack_v2_sparse_classes_30k_train_032154 | Implement the Python class `StateManager` described below.
Class description:
A class for managing the inbound/outbound messages and state of a websocket session.
Method signatures and docstrings:
- def __init__(self, websocket: websockets.WebSocketServerProtocol): Initializer.
- async def consumer_handler(self): Thi... | Implement the Python class `StateManager` described below.
Class description:
A class for managing the inbound/outbound messages and state of a websocket session.
Method signatures and docstrings:
- def __init__(self, websocket: websockets.WebSocketServerProtocol): Initializer.
- async def consumer_handler(self): Thi... | 56d808d7836cd15d6c6748cbf704cdea4407fef6 | <|skeleton|>
class StateManager:
"""A class for managing the inbound/outbound messages and state of a websocket session."""
def __init__(self, websocket: websockets.WebSocketServerProtocol):
"""Initializer."""
<|body_0|>
async def consumer_handler(self):
"""This is the primary asyn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StateManager:
"""A class for managing the inbound/outbound messages and state of a websocket session."""
def __init__(self, websocket: websockets.WebSocketServerProtocol):
"""Initializer."""
logger.debug('Initializing websocket state manager')
self._websocket = websocket
s... | the_stack_v2_python_sparse | src/installer/src/tortuga/web_service/websocket/state_manager.py | UnivaCorporation/tortuga | train | 33 |
ce666c1870da474ee28e3313a939fc31e9f5e927 | [
"if rect is None:\n rect = [0.05, 0.05, 0.9, 0.9]\nself.n = len(titles)\nself.color = color\nself.angles = np.arange(45, 45 + 360, 360.0 / self.n)\nself.axes = [fig.add_axes(rect, projection='polar', label='axes%d' % i) for i in range(self.n)]\nself.ax = self.axes[0]\nself.ax.set_thetagrids(self.angles, labels=t... | <|body_start_0|>
if rect is None:
rect = [0.05, 0.05, 0.9, 0.9]
self.n = len(titles)
self.color = color
self.angles = np.arange(45, 45 + 360, 360.0 / self.n)
self.axes = [fig.add_axes(rect, projection='polar', label='axes%d' % i) for i in range(self.n)]
self.a... | Radar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Radar:
def __init__(self, fig, titles, labels, color='b', rect=None):
"""constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color for plotting :param rect: area for plotting"""
<|body_0|>
def plot(self, values, ... | stack_v2_sparse_classes_75kplus_train_068295 | 43,229 | no_license | [
{
"docstring": "constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color for plotting :param rect: area for plotting",
"name": "__init__",
"signature": "def __init__(self, fig, titles, labels, color='b', rect=None)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_000863 | Implement the Python class `Radar` described below.
Class description:
Implement the Radar class.
Method signatures and docstrings:
- def __init__(self, fig, titles, labels, color='b', rect=None): constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color ... | Implement the Python class `Radar` described below.
Class description:
Implement the Radar class.
Method signatures and docstrings:
- def __init__(self, fig, titles, labels, color='b', rect=None): constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color ... | b11d30049ef14703933cb357a727cf92d838b46b | <|skeleton|>
class Radar:
def __init__(self, fig, titles, labels, color='b', rect=None):
"""constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color for plotting :param rect: area for plotting"""
<|body_0|>
def plot(self, values, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Radar:
def __init__(self, fig, titles, labels, color='b', rect=None):
"""constructor :param fig: given figure-object :param titles: title-list :param labels: lable-list :param color: used color for plotting :param rect: area for plotting"""
if rect is None:
rect = [0.05, 0.05, 0.9,... | the_stack_v2_python_sparse | gui_prototype/rc_gui.py | QueensGambit/GitHubRepositoryClassifier | train | 3 | |
cf01f8d2ea80607b9465fb35fc6170f72403ac85 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingCustomerInformation()",
"from .booking_customer_information_base import BookingCustomerInformationBase\nfrom .booking_question_answer import BookingQuestionAnswer\nfrom .location import Location\nfrom .booking_customer_informati... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingCustomerInformation()
<|end_body_0|>
<|body_start_1|>
from .booking_customer_information_base import BookingCustomerInformationBase
from .booking_question_answer import BookingQue... | BookingCustomerInformation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingCustomerInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomerInformation:
"""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... | stack_v2_sparse_classes_75kplus_train_068296 | 4,891 | 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: BookingCustomerInformation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discri... | 3 | stack_v2_sparse_classes_30k_train_054493 | Implement the Python class `BookingCustomerInformation` described below.
Class description:
Implement the BookingCustomerInformation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomerInformation: Creates a new instance of the appropr... | Implement the Python class `BookingCustomerInformation` described below.
Class description:
Implement the BookingCustomerInformation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomerInformation: Creates a new instance of the appropr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingCustomerInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomerInformation:
"""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... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookingCustomerInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomerInformation:
"""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 ob... | the_stack_v2_python_sparse | msgraph/generated/models/booking_customer_information.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
25284a6cd819f5d6b15015e2c852e7020f1a46ef | [
"nlg = read_endpoint_config(endpoint_file, endpoint_type='nlg')\nnlu = read_endpoint_config(endpoint_file, endpoint_type='nlu')\naction = read_endpoint_config(endpoint_file, endpoint_type='action_endpoint')\nmodel = read_endpoint_config(endpoint_file, endpoint_type='models')\ntracker_store = read_endpoint_config(en... | <|body_start_0|>
nlg = read_endpoint_config(endpoint_file, endpoint_type='nlg')
nlu = read_endpoint_config(endpoint_file, endpoint_type='nlu')
action = read_endpoint_config(endpoint_file, endpoint_type='action_endpoint')
model = read_endpoint_config(endpoint_file, endpoint_type='models')... | Collection of configured endpoints. | AvailableEndpoints | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvailableEndpoints:
"""Collection of configured endpoints."""
def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints':
"""Read the different endpoints from a yaml file."""
<|body_0|>
def __init__(self, nlg: Optional[EndpointConfig]=None, nlu: Optional[Endpoi... | stack_v2_sparse_classes_75kplus_train_068297 | 10,995 | permissive | [
{
"docstring": "Read the different endpoints from a yaml file.",
"name": "read_endpoints",
"signature": "def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints'"
},
{
"docstring": "Create an `AvailableEndpoints` object.",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | stack_v2_sparse_classes_30k_val_002790 | Implement the Python class `AvailableEndpoints` described below.
Class description:
Collection of configured endpoints.
Method signatures and docstrings:
- def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints': Read the different endpoints from a yaml file.
- def __init__(self, nlg: Optional[EndpointCo... | Implement the Python class `AvailableEndpoints` described below.
Class description:
Collection of configured endpoints.
Method signatures and docstrings:
- def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints': Read the different endpoints from a yaml file.
- def __init__(self, nlg: Optional[EndpointCo... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class AvailableEndpoints:
"""Collection of configured endpoints."""
def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints':
"""Read the different endpoints from a yaml file."""
<|body_0|>
def __init__(self, nlg: Optional[EndpointConfig]=None, nlu: Optional[Endpoi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AvailableEndpoints:
"""Collection of configured endpoints."""
def read_endpoints(cls, endpoint_file: Text) -> 'AvailableEndpoints':
"""Read the different endpoints from a yaml file."""
nlg = read_endpoint_config(endpoint_file, endpoint_type='nlg')
nlu = read_endpoint_config(endpoi... | the_stack_v2_python_sparse | rasa/core/utils.py | RasaHQ/rasa | train | 13,167 |
70324fc97aa52c579200d4389a8a21a45aed213d | [
"super(ResFCBlock, self).__init__()\nself.act = activation\nself.fc1 = fc_block(in_channels, in_channels, activation=self.act, norm_type=norm_type)\nself.fc2 = fc_block(in_channels, in_channels, activation=None, norm_type=norm_type)",
"residual = x\nx = self.fc1(x)\nx = self.fc2(x)\nx = self.act(x + residual)\nre... | <|body_start_0|>
super(ResFCBlock, self).__init__()
self.act = activation
self.fc1 = fc_block(in_channels, in_channels, activation=self.act, norm_type=norm_type)
self.fc2 = fc_block(in_channels, in_channels, activation=None, norm_type=norm_type)
<|end_body_0|>
<|body_start_1|>
r... | Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward | ResFCBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResFCBlock:
"""Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward"""
def __init__(self, in_channels: int, activation: nn.Module=nn.ReLU(), norm_type: str='BN'):
"""Ov... | stack_v2_sparse_classes_75kplus_train_068298 | 4,174 | permissive | [
{
"docstring": "Overview: Init the Residual Block Arguments: - in_channels (:obj:`int`): Number of channels in the input tensor - activation (:obj:`nn.Module`): the optional activation function - norm_type (:obj:`str`): type of the normalization, defalut set to 'BN'",
"name": "__init__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_026462 | Implement the Python class `ResFCBlock` described below.
Class description:
Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward
Method signatures and docstrings:
- def __init__(self, in_channels: int, ... | Implement the Python class `ResFCBlock` described below.
Class description:
Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward
Method signatures and docstrings:
- def __init__(self, in_channels: int, ... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ResFCBlock:
"""Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward"""
def __init__(self, in_channels: int, activation: nn.Module=nn.ReLU(), norm_type: str='BN'):
"""Ov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResFCBlock:
"""Overview: Residual Block with 2 fully connected block x -> fc1 -> norm -> act -> fc2 -> norm -> act -> out \\_____________________________________/+ Interfaces: forward"""
def __init__(self, in_channels: int, activation: nn.Module=nn.ReLU(), norm_type: str='BN'):
"""Overview: Init ... | the_stack_v2_python_sparse | ding/torch_utils/network/res_block.py | shengxuesun/DI-engine | train | 1 |
f87f9418cde308fd800e2a53fcc076827b31013d | [
"if not root:\n return 0\nreturn max(self.maxDepth_recursive(root.left), self.maxDepth_recursive(root.right)) + 1",
"if not root:\n return 0\nstack = [root]\ndepth = 1\ndepth_stack = [depth]\nwhile stack:\n node = stack.pop()\n tmp = depth_stack.pop()\n depth = max(depth, tmp)\n if node.right:\n... | <|body_start_0|>
if not root:
return 0
return max(self.maxDepth_recursive(root.left), self.maxDepth_recursive(root.right)) + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
stack = [root]
depth = 1
depth_stack = [depth]
while stack... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth_recursive(self, root: TreeNode) -> int:
"""递归"""
<|body_0|>
def maxDepth_dfs(self, root: TreeNode) -> int:
"""栈 深度优先"""
<|body_1|>
def maxDepth_bfs(self, root: TreeNode) -> int:
"""队列广度优先"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_068299 | 2,214 | no_license | [
{
"docstring": "递归",
"name": "maxDepth_recursive",
"signature": "def maxDepth_recursive(self, root: TreeNode) -> int"
},
{
"docstring": "栈 深度优先",
"name": "maxDepth_dfs",
"signature": "def maxDepth_dfs(self, root: TreeNode) -> int"
},
{
"docstring": "队列广度优先",
"name": "maxDepth... | 3 | stack_v2_sparse_classes_30k_train_016119 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth_recursive(self, root: TreeNode) -> int: 递归
- def maxDepth_dfs(self, root: TreeNode) -> int: 栈 深度优先
- def maxDepth_bfs(self, root: TreeNode) -> int: 队列广度优先 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth_recursive(self, root: TreeNode) -> int: 递归
- def maxDepth_dfs(self, root: TreeNode) -> int: 栈 深度优先
- def maxDepth_bfs(self, root: TreeNode) -> int: 队列广度优先
<|skeleto... | 0abc04bc44e6fedf6ce59e83dd37be5787b88a25 | <|skeleton|>
class Solution:
def maxDepth_recursive(self, root: TreeNode) -> int:
"""递归"""
<|body_0|>
def maxDepth_dfs(self, root: TreeNode) -> int:
"""栈 深度优先"""
<|body_1|>
def maxDepth_bfs(self, root: TreeNode) -> int:
"""队列广度优先"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDepth_recursive(self, root: TreeNode) -> int:
"""递归"""
if not root:
return 0
return max(self.maxDepth_recursive(root.left), self.maxDepth_recursive(root.right)) + 1
def maxDepth_dfs(self, root: TreeNode) -> int:
"""栈 深度优先"""
if not root... | the_stack_v2_python_sparse | maxDepth_104.py | oratun/Py-LeetCode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.