blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
75dc346b53892900b7b68ff567f5a543835e20c0 | [
"self.d = defaultdict(list)\nfor i, w in enumerate(words):\n self.d[w].append(i)",
"a, b = (self.d[word1], self.d[word2])\nm, n, i, j = (len(a), len(b), 0, 0)\nres = float('inf')\nwhile i < m and j < n:\n idx1, idx2 = (a[i], b[j])\n if idx1 > idx2:\n res = min(res, idx1 - idx2)\n j += 1\n ... | <|body_start_0|>
self.d = defaultdict(list)
for i, w in enumerate(words):
self.d[w].append(i)
<|end_body_0|>
<|body_start_1|>
a, b = (self.d[word1], self.d[word2])
m, n, i, j = (len(a), len(b), 0, 0)
res = float('inf')
while i < m and j < n:
idx1,... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_026300 | 1,163 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_015756 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 16468a4397430b24b685cab02570ff3f5849e86f | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.d = defaultdict(list)
for i, w in enumerate(words):
self.d[w].append(i)
def shortest(self, word1, word2):
"""Adds a word into the data structure. :ty... | the_stack_v2_python_sparse | shortest-word-distance-II/s1.py | fingerroll/wip | train | 0 | |
73ede61936158950cf9c8c1480afb518b8beef39 | [
"self.wordToIndice = {}\nfor i in range(len(words)):\n word = words[i]\n if word not in self.wordToIndice:\n self.wordToIndice[word] = []\n self.wordToIndice[word].append(i)",
"indice1 = self.wordToIndice[word1]\nindice2 = self.wordToIndice[word2]\nminDis = float('inf')\nfor i in range(len(indice1... | <|body_start_0|>
self.wordToIndice = {}
for i in range(len(words)):
word = words[i]
if word not in self.wordToIndice:
self.wordToIndice[word] = []
self.wordToIndice[word].append(i)
<|end_body_0|>
<|body_start_1|>
indice1 = self.wordToIndice[wo... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wordToIndice = {}
for i ... | stack_v2_sparse_classes_36k_train_026301 | 926 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 1d8821da01c9c200732a6b7037b8631689e2f7e7 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.wordToIndice = {}
for i in range(len(words)):
word = words[i]
if word not in self.wordToIndice:
self.wordToIndice[word] = []
self.wordToIndice[word].append(i)
... | the_stack_v2_python_sparse | Leetcode0244.py | xiaojinghu/Leetcode | train | 0 | |
4b96b43b6f30a06ab9a55da59cbbe7a2d7287d13 | [
"super().__init__()\nself.urls = urls\nself.queue = queue\nself.username = username\nself.password = password\nself.max_retries = max_retries\nself.retry_delay = retry_delay\nself.ttl_in_seconds = ttl_in_seconds\nif self.urls is None or not isinstance(urls, List) or len(urls) == 0:\n raise ValueError('Invalid ur... | <|body_start_0|>
super().__init__()
self.urls = urls
self.queue = queue
self.username = username
self.password = password
self.max_retries = max_retries
self.retry_delay = retry_delay
self.ttl_in_seconds = ttl_in_seconds
if self.urls is None or not... | Proton implementation of a queue adaptor. | ProtonQueueAdaptor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAd... | stack_v2_sparse_classes_36k_train_026302 | 10,709 | permissive | [
{
"docstring": "Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAdaptor>`. The kwargs provided should contain the following information: * host: The host of the Message Queue to be interacted with. * username: The username to use to connect to the Message Queue. * password ... | 5 | stack_v2_sparse_classes_30k_train_018420 | Implement the Python class `ProtonQueueAdaptor` described below.
Class description:
Proton implementation of a queue adaptor.
Method signatures and docstrings:
- def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None: Construct a Proton implementati... | Implement the Python class `ProtonQueueAdaptor` described below.
Class description:
Proton implementation of a queue adaptor.
Method signatures and docstrings:
- def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None: Construct a Proton implementati... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtonQueueAdaptor:
"""Proton implementation of a queue adaptor."""
def __init__(self, urls: List[str], queue: str, username, password, max_retries=0, retry_delay=0, ttl_in_seconds=0) -> None:
"""Construct a Proton implementation of a :class:`QueueAdaptor <comms.queue_adaptor.QueueAdaptor>`. The ... | the_stack_v2_python_sparse | common/comms/proton_queue_adaptor.py | nhsconnect/integration-adaptors | train | 15 |
d55c270fa377a735a4ffa415b18afe147b30abc7 | [
"self.case_dir = case_dir\nassert os.path.isdir(self.case_dir)\nself.output_dir = os.path.join(case_dir, 'output')\nassert os.path.isdir(self.output_dir)\nself.visit_file = os.path.join(self.output_dir, 'solution.visit')\nassert os.access(self.visit_file, os.R_OK)\nself.output_dir = os.path.join(case_dir, 'output')... | <|body_start_0|>
self.case_dir = case_dir
assert os.path.isdir(self.case_dir)
self.output_dir = os.path.join(case_dir, 'output')
assert os.path.isdir(self.output_dir)
self.visit_file = os.path.join(self.output_dir, 'solution.visit')
assert os.access(self.visit_file, os.R_... | parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionary of key and value to output | VISIT_OPTIONS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VISIT_OPTIONS:
"""parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionary of key and value to output"""
de... | stack_v2_sparse_classes_36k_train_026303 | 8,641 | no_license | [
{
"docstring": "Initiation Args: case_dir(str): directory of case",
"name": "__init__",
"signature": "def __init__(self, case_dir)"
},
{
"docstring": "Interpret the inputs parsed from a prm file kwargs: options last_step(list): plot the last few steps",
"name": "Interpret",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_012292 | Implement the Python class `VISIT_OPTIONS` described below.
Class description:
parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionar... | Implement the Python class `VISIT_OPTIONS` described below.
Class description:
parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionar... | d919cadce2b57811351c0615d94da5c6ebfff800 | <|skeleton|>
class VISIT_OPTIONS:
"""parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionary of key and value to output"""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VISIT_OPTIONS:
"""parse .prm file to a option file that bash can easily read This inherit from Utilities.CODESUB Attributes: case_dir(str): path of this case output_dir(str): path of the output visit_file(str): path of the visit file options(dict): dictionary of key and value to output"""
def __init__(se... | the_stack_v2_python_sparse | jupyter_notebooks/Auto-visit/Auto_visit.py | lhy11009/aspectLib | train | 0 |
9aadfc02f47751f9d1b2fd6f4582573a3a9d934a | [
"url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'\nreq = urllib2.Request(url)\nf = urllib2.urlopen(req)\nsoup = BeautifulSoup(f)\ntable = soup.find('table', attrs={'class': 'contenido'})\nbanks = []\nfor row in table.findAll('tr')[2:]:\n banks.append([td.ge... | <|body_start_0|>
url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'
req = urllib2.Request(url)
f = urllib2.urlopen(req)
soup = BeautifulSoup(f)
table = soup.find('table', attrs={'class': 'contenido'})
banks = []
... | Banks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
<|body_0|>
def get_values(banks_list):
""":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco""... | stack_v2_sparse_classes_36k_train_026304 | 1,626 | no_license | [
{
"docstring": "Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping",
"name": "get_banks_list",
"signature": "def get_banks_list()"
},
{
"docstring": ":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco",
"n... | 2 | stack_v2_sparse_classes_30k_train_009280 | Implement the Python class `Banks` described below.
Class description:
Implement the Banks class.
Method signatures and docstrings:
- def get_banks_list(): Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping
- def get_values(banks_list): :param banks_list: Lista de bancos. :ret... | Implement the Python class `Banks` described below.
Class description:
Implement the Banks class.
Method signatures and docstrings:
- def get_banks_list(): Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping
- def get_values(banks_list): :param banks_list: Lista de bancos. :ret... | 1a60305c457c84cae6de9481efc9ca5c459038f6 | <|skeleton|>
class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
<|body_0|>
def get_values(banks_list):
""":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'
req = urllib2.Request(url)
f = urllib2.urlopen... | the_stack_v2_python_sparse | l10n_ar_api/padron/banks.py | MarcoKlemenc/l10n_ar_api | train | 0 | |
dfe1f0e000450e3c3b62e1b59b231293c1b91e77 | [
"super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)",
"h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred"
] | <|body_start_0|>
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
<|end_body_1|>
| TwoLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Variable of input data and we must return a Var... | stack_v2_sparse_classes_36k_train_026305 | 3,631 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Variable of input data and we must return a Variable of outp... | 2 | stack_v2_sparse_classes_30k_train_014863 | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | 868d54b6094cb92240600418f2849d4b196374be | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Variable of input data and we must return a Var... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forw... | the_stack_v2_python_sparse | pytorchtest/simpleMnist.py | metatron/pythontest | train | 1 | |
ac731eae7f0e4b87ee7e659db0c648d6a4e5020a | [
"group = {}\nfor s in strs:\n k = ''.join(sorted(s))\n if k not in group:\n group[k] = []\n group[k].append(s)\nreturn list(group.values())",
"mapping = {}\nans = []\nfor s in strs:\n k = ''.join(sorted(s))\n if k not in mapping:\n mapping[k] = len(mapping)\n ans.append([s])\n ... | <|body_start_0|>
group = {}
for s in strs:
k = ''.join(sorted(s))
if k not in group:
group[k] = []
group[k].append(s)
return list(group.values())
<|end_body_0|>
<|body_start_1|>
mapping = {}
ans = []
for s in strs:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
group = {}
... | stack_v2_sparse_classes_36k_train_026306 | 1,291 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams2",
"signature": "def groupAnagrams2(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010022 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): :type strs: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): :type strs: List[str] :rtype: List[List[str]]
<|skeleton|>
class S... | f2c4f727689567e00ee06560132fca55a6fd9286 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
group = {}
for s in strs:
k = ''.join(sorted(s))
if k not in group:
group[k] = []
group[k].append(s)
return list(group.values())
... | the_stack_v2_python_sparse | leetcode/49_Group_Anagrams.py | JianxiangWang/python-journey | train | 1 | |
1a6f3edc80012e12f2b5871f685184e9f9eb40e9 | [
"try:\n result = self._component_result\nexcept AttributeError as err:\n raise AttributeError('Components have not been loaded yet') from err\nresult.unload()",
"self_class = self.__class__\ntry:\n component_loader = self_class._component_loader\n if component_loader.component_tags != self_class.compo... | <|body_start_0|>
try:
result = self._component_result
except AttributeError as err:
raise AttributeError('Components have not been loaded yet') from err
result.unload()
<|end_body_0|>
<|body_start_1|>
self_class = self.__class__
try:
component... | Base class for handling game engine specific system components | ComponentEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentEntity:
"""Base class for handling game engine specific system components"""
def unload_components(self):
"""Unloads entity components"""
<|body_0|>
def load_components(self):
"""Loads entity-specific components marked using the with_tag system/ Uses an ... | stack_v2_sparse_classes_36k_train_026307 | 11,299 | no_license | [
{
"docstring": "Unloads entity components",
"name": "unload_components",
"signature": "def unload_components(self)"
},
{
"docstring": "Loads entity-specific components marked using the with_tag system/ Uses an abstract ComponentLoader to read a configuration file providing loader data",
"nam... | 2 | stack_v2_sparse_classes_30k_train_015192 | Implement the Python class `ComponentEntity` described below.
Class description:
Base class for handling game engine specific system components
Method signatures and docstrings:
- def unload_components(self): Unloads entity components
- def load_components(self): Loads entity-specific components marked using the with... | Implement the Python class `ComponentEntity` described below.
Class description:
Base class for handling game engine specific system components
Method signatures and docstrings:
- def unload_components(self): Unloads entity components
- def load_components(self): Loads entity-specific components marked using the with... | a90b2ce703a72b8463e5b467f6f50728007592e9 | <|skeleton|>
class ComponentEntity:
"""Base class for handling game engine specific system components"""
def unload_components(self):
"""Unloads entity components"""
<|body_0|>
def load_components(self):
"""Loads entity-specific components marked using the with_tag system/ Uses an ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComponentEntity:
"""Base class for handling game engine specific system components"""
def unload_components(self):
"""Unloads entity components"""
try:
result = self._component_result
except AttributeError as err:
raise AttributeError('Components have not b... | the_stack_v2_python_sparse | game_system/entities.py | TurBoss/PyAuthServer | train | 0 |
ce62854d93d713c3085b9ea2038b607f067d7e81 | [
"self._parameters = parameters\nif not hasattr(self, '_mapper'):\n self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabl... | <|body_start_0|>
self._parameters = parameters
if not hasattr(self, '_mapper'):
self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))
if parameters.get_filter('enabled') is N... | Handles tag queries and responses for AWS. | AWSTagQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_36k_train_026308 | 3,275 | permissive | [
{
"docstring": "Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Establish which filter map to use based on tag API.",
"name": "filter_map",
"signature... | 2 | stack_v2_sparse_classes_30k_train_012466 | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
self._parameters = parameters
if not hasattr(self, '_mapper'):
... | the_stack_v2_python_sparse | koku/api/tags/aws/queries.py | project-koku/koku | train | 225 |
b9214029d439a4adbb3ccc25e22d7118d47dcdc5 | [
"self.text = str(text)\nself.screen = screen\nself.drawCursor = drawCursor\nself.colour = colour\nif settings.textSpeed == 'SLOW':\n self.speed = 1\nelif settings.textSpeed == 'MEDIUM':\n self.speed = 2\nelif settings.textSpeed == 'FAST':\n self.speed = 4\nroot = data.getTreeRoot(globs.BOX, 'Ditto main')\n... | <|body_start_0|>
self.text = str(text)
self.screen = screen
self.drawCursor = drawCursor
self.colour = colour
if settings.textSpeed == 'SLOW':
self.speed = 1
elif settings.textSpeed == 'MEDIUM':
self.speed = 2
elif settings.textSpeed == 'FA... | Class to provide dialogs to be shown by the script engine. | Dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog:
"""Class to provide dialogs to be shown by the script engine."""
def __init__(self, text, screen, drawCursor=True, colour='main'):
"""Create the dialog box and load cursors. text - a list of lines of text to go in the dialog. font - the font with which to write the text. scre... | stack_v2_sparse_classes_36k_train_026309 | 7,179 | no_license | [
{
"docstring": "Create the dialog box and load cursors. text - a list of lines of text to go in the dialog. font - the font with which to write the text. screen - the surface to draw the dialog onto. soundManager - the sound manager. drawCursor - whether a continuation cursor should be drawn when the text has f... | 4 | stack_v2_sparse_classes_30k_train_008430 | Implement the Python class `Dialog` described below.
Class description:
Class to provide dialogs to be shown by the script engine.
Method signatures and docstrings:
- def __init__(self, text, screen, drawCursor=True, colour='main'): Create the dialog box and load cursors. text - a list of lines of text to go in the d... | Implement the Python class `Dialog` described below.
Class description:
Class to provide dialogs to be shown by the script engine.
Method signatures and docstrings:
- def __init__(self, text, screen, drawCursor=True, colour='main'): Create the dialog box and load cursors. text - a list of lines of text to go in the d... | 72841fc503c716ac3b524e42f2311cbd9d18a092 | <|skeleton|>
class Dialog:
"""Class to provide dialogs to be shown by the script engine."""
def __init__(self, text, screen, drawCursor=True, colour='main'):
"""Create the dialog box and load cursors. text - a list of lines of text to go in the dialog. font - the font with which to write the text. scre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dialog:
"""Class to provide dialogs to be shown by the script engine."""
def __init__(self, text, screen, drawCursor=True, colour='main'):
"""Create the dialog box and load cursors. text - a list of lines of text to go in the dialog. font - the font with which to write the text. screen - the surf... | the_stack_v2_python_sparse | eng/dialog.py | andrew-turner/Ditto | train | 0 |
a60d8d941e04d8e8fae1536d1638df21082f2625 | [
"old_schema = self.old.Schema()\nfor field_name in ['creation_date', 'modification_date']:\n old_field = old_schema[field_name]\n accessor = old_field.getEditAccessor(self.old) or old_field.getAccessor(self.old)\n setattr(self, 'old_' + field_name, accessor())",
"new_schema = self.new.Schema()\nfor field... | <|body_start_0|>
old_schema = self.old.Schema()
for field_name in ['creation_date', 'modification_date']:
old_field = old_schema[field_name]
accessor = old_field.getEditAccessor(self.old) or old_field.getAccessor(self.old)
setattr(self, 'old_' + field_name, accessor()... | Migrates content of one AT type to another AT type. | ATMigratorMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATMigratorMixin:
"""Migrates content of one AT type to another AT type."""
def beforeChange_storeDates(self):
"""Save creation date and modification date"""
<|body_0|>
def last_migrate_date(self):
"""migrate creation / last modified date Must be called as *last* ... | stack_v2_sparse_classes_36k_train_026310 | 7,595 | no_license | [
{
"docstring": "Save creation date and modification date",
"name": "beforeChange_storeDates",
"signature": "def beforeChange_storeDates(self)"
},
{
"docstring": "migrate creation / last modified date Must be called as *last* migration",
"name": "last_migrate_date",
"signature": "def last... | 4 | stack_v2_sparse_classes_30k_train_005757 | Implement the Python class `ATMigratorMixin` described below.
Class description:
Migrates content of one AT type to another AT type.
Method signatures and docstrings:
- def beforeChange_storeDates(self): Save creation date and modification date
- def last_migrate_date(self): migrate creation / last modified date Must... | Implement the Python class `ATMigratorMixin` described below.
Class description:
Migrates content of one AT type to another AT type.
Method signatures and docstrings:
- def beforeChange_storeDates(self): Save creation date and modification date
- def last_migrate_date(self): migrate creation / last modified date Must... | e137eb6225cc5e724bee74a892567796166134ac | <|skeleton|>
class ATMigratorMixin:
"""Migrates content of one AT type to another AT type."""
def beforeChange_storeDates(self):
"""Save creation date and modification date"""
<|body_0|>
def last_migrate_date(self):
"""migrate creation / last modified date Must be called as *last* ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ATMigratorMixin:
"""Migrates content of one AT type to another AT type."""
def beforeChange_storeDates(self):
"""Save creation date and modification date"""
old_schema = self.old.Schema()
for field_name in ['creation_date', 'modification_date']:
old_field = old_schema[... | the_stack_v2_python_sparse | eggs/Products.contentmigration-2.0.1-py2.7.egg/Products/contentmigration/archetypes.py | nacho22martin/tesis | train | 0 |
32c1f8165b7b3bf2fdca7817fafe338859533daa | [
"@lru_cache(None)\ndef dp(i, j):\n if i == len(text1) or j == len(text2):\n return 0\n if text1[i] == text2[j]:\n return 1 + dp(i + 1, j + 1)\n return max(dp(i + 1, j), dp(i, j + 1))\nreturn dp(0, 0)",
"pre = [0] * (len(text2) + 1)\nfor i in range(len(text1)):\n cur = [0] * (len(text2) +... | <|body_start_0|>
@lru_cache(None)
def dp(i, j):
if i == len(text1) or j == len(text2):
return 0
if text1[i] == text2[j]:
return 1 + dp(i + 1, j + 1)
return max(dp(i + 1, j), dp(i, j + 1))
return dp(0, 0)
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""Oct 11, 2021 09:07"""
<|body_0|>
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""Oct 11, 2021 09:15"""
<|body_1|>
def longestCommonSubsequence(self, tex... | stack_v2_sparse_classes_36k_train_026311 | 2,702 | no_license | [
{
"docstring": "Oct 11, 2021 09:07",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1: str, text2: str) -> int"
},
{
"docstring": "Oct 11, 2021 09:15",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1: st... | 3 | stack_v2_sparse_classes_30k_test_000916 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: Oct 11, 2021 09:07
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: Oct 11, 2021 09:15
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: Oct 11, 2021 09:07
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: Oct 11, 2021 09:15
- de... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""Oct 11, 2021 09:07"""
<|body_0|>
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""Oct 11, 2021 09:15"""
<|body_1|>
def longestCommonSubsequence(self, tex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""Oct 11, 2021 09:07"""
@lru_cache(None)
def dp(i, j):
if i == len(text1) or j == len(text2):
return 0
if text1[i] == text2[j]:
return 1 + dp(i + 1, j +... | the_stack_v2_python_sparse | leetcode/solved/1250_Longest_Common_Subsequence/solution.py | sungminoh/algorithms | train | 0 | |
4ec664e8014dd8ac706e9fcf815d0ed6dffe9a49 | [
"if attrs is None:\n attrs = {}\nattrs['multiple'] = 'multiple'\nreturn super(AjaxBulkFileMultiInput, self).render(name, value, attrs)",
"if isinstance(files, (MultiValueDict, MergeDict)):\n return files.getlist(name)\nreturn files.get(name, None)"
] | <|body_start_0|>
if attrs is None:
attrs = {}
attrs['multiple'] = 'multiple'
return super(AjaxBulkFileMultiInput, self).render(name, value, attrs)
<|end_body_0|>
<|body_start_1|>
if isinstance(files, (MultiValueDict, MergeDict)):
return files.getlist(name)
... | Handle multiple uploaded files. | AjaxBulkFileMultiInput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AjaxBulkFileMultiInput:
"""Handle multiple uploaded files."""
def render(self, name, value, attrs=None):
"""Add 'multiple' class to widget."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Return list of files uploaded."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_026312 | 1,338 | no_license | [
{
"docstring": "Add 'multiple' class to widget.",
"name": "render",
"signature": "def render(self, name, value, attrs=None)"
},
{
"docstring": "Return list of files uploaded.",
"name": "value_from_datadict",
"signature": "def value_from_datadict(self, data, files, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018115 | Implement the Python class `AjaxBulkFileMultiInput` described below.
Class description:
Handle multiple uploaded files.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Add 'multiple' class to widget.
- def value_from_datadict(self, data, files, name): Return list of files uploaded. | Implement the Python class `AjaxBulkFileMultiInput` described below.
Class description:
Handle multiple uploaded files.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Add 'multiple' class to widget.
- def value_from_datadict(self, data, files, name): Return list of files uploaded.
<|s... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class AjaxBulkFileMultiInput:
"""Handle multiple uploaded files."""
def render(self, name, value, attrs=None):
"""Add 'multiple' class to widget."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Return list of files uploaded."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AjaxBulkFileMultiInput:
"""Handle multiple uploaded files."""
def render(self, name, value, attrs=None):
"""Add 'multiple' class to widget."""
if attrs is None:
attrs = {}
attrs['multiple'] = 'multiple'
return super(AjaxBulkFileMultiInput, self).render(name, va... | the_stack_v2_python_sparse | tunobase/bulk_loading/widgets.py | unomena/tunobase | train | 0 |
5b5dffc8ad78d5d85b770d04227ac521029b698b | [
"api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)\nif await api.get_active_dataset_tlvs() is None:\n allowed_channel = await get_allowed_channel(self.hass, otbr_url)\n thread_dataset_channel = None\n thread_dataset_tlv = await async_get_preferred_dataset(self.hass)\n if threa... | <|body_start_0|>
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)
if await api.get_active_dataset_tlvs() is None:
allowed_channel = await get_allowed_channel(self.hass, otbr_url)
thread_dataset_channel = None
thread_dataset_tlv = await asyn... | Handle a config flow for Open Thread Border Router. | OTBRConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_36k_train_026313 | 6,444 | permissive | [
{
"docstring": "Connect to the OTBR and create or apply a dataset if it doesn't have one.",
"name": "_connect_and_set_dataset",
"signature": "async def _connect_and_set_dataset(self, otbr_url: str) -> None"
},
{
"docstring": "Set up by user.",
"name": "async_step_user",
"signature": "asy... | 3 | stack_v2_sparse_classes_30k_train_005006 | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass... | the_stack_v2_python_sparse | homeassistant/components/otbr/config_flow.py | home-assistant/core | train | 35,501 |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = TableSerializer(username=username, repo_base=repo_base, request=request)\ntables = serializer.list_tables(repo_name)\nreturn Response(tables, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nserializer = TableSerializer(username=username, ... | <|body_start_0|>
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base, request=request)
tables = serializer.list_tables(repo_name)
return Response(tables, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
username = ... | Tables | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a table in a repo note: Using execute_query to create tables gives more control over table creat... | stack_v2_sparse_classes_36k_train_026314 | 31,465 | permissive | [
{
"docstring": "Tables in a repo",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, format=None)"
},
{
"docstring": "Create a table in a repo note: Using execute_query to create tables gives more control over table creation e.g. { \"table_name\": \"mytablename\", \"param... | 2 | stack_v2_sparse_classes_30k_train_017602 | Implement the Python class `Tables` described below.
Class description:
Implement the Tables class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Tables in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a table in a repo note: Using execute... | Implement the Python class `Tables` described below.
Class description:
Implement the Tables class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Tables in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a table in a repo note: Using execute... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a table in a repo note: Using execute_query to create tables gives more control over table creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base, request=request)
tables = serializer.list_tables(repo_name)
return Respo... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
51918672a551ed9cd8990f94db8f979aa16f2843 | [
"logger.debug('Getting audit records...start')\nlogger.info('Getting audit records for the query:[{}]...start'.format(q))\nmodel = None\nif q is not None:\n model = q.to_model()\nquery_result = transaction_service.get_transactions(model, limit, marker)\nlogger.debug('Getting audit records...end')\nreturn query_r... | <|body_start_0|>
logger.debug('Getting audit records...start')
logger.info('Getting audit records for the query:[{}]...start'.format(q))
model = None
if q is not None:
model = q.to_model()
query_result = transaction_service.get_transactions(model, limit, marker)
... | Transaction Audit controller. | TransactionController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionController:
"""Transaction Audit controller."""
def get_all(self, q=None, limit=10, marker=None):
"""get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transactions. :param limit: the maximun number of transactions t... | stack_v2_sparse_classes_36k_train_026315 | 8,312 | no_license | [
{
"docstring": "get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transactions. :param limit: the maximun number of transactions to return. :param marker: a place order for pagination (not implemented yet). Example of usage: http://127.0.0.1:8777/v1/audi... | 2 | null | Implement the Python class `TransactionController` described below.
Class description:
Transaction Audit controller.
Method signatures and docstrings:
- def get_all(self, q=None, limit=10, marker=None): get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transac... | Implement the Python class `TransactionController` described below.
Class description:
Transaction Audit controller.
Method signatures and docstrings:
- def get_all(self, q=None, limit=10, marker=None): get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transac... | 3ea2dcb191d8e41498fe062a79349c9d055224c6 | <|skeleton|>
class TransactionController:
"""Transaction Audit controller."""
def get_all(self, q=None, limit=10, marker=None):
"""get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transactions. :param limit: the maximun number of transactions t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransactionController:
"""Transaction Audit controller."""
def get_all(self, q=None, limit=10, marker=None):
"""get all transactions that meet the given query. :param q: the query to use in order to search for relevant. transactions. :param limit: the maximun number of transactions to return. :pa... | the_stack_v2_python_sparse | orm/services/audit_trail_manager/audit_server/controllers/v1/transaction.py | jq1581/ranger | train | 0 |
3de78b84a8fe8dedfeb021f99996643bad8b60b0 | [
"n = len(s)\ndp = [[0 for _ in range(n)] for _ in range(n)]\nmax_length = 1\nmax_str = s[0]\nfor i in range(n):\n dp[i][i] = 1\nfor i in range(n - 1):\n if s[i] == s[i + 1]:\n dp[i][i + 1] = 1\n max_str = s[i:i + 2]\n max_length = 2\nfor k in range(3, n + 1):\n for i in range(n - k + 1... | <|body_start_0|>
n = len(s)
dp = [[0 for _ in range(n)] for _ in range(n)]
max_length = 1
max_str = s[0]
for i in range(n):
dp[i][i] = 1
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = 1
max_str = s[i:i + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2]... | stack_v2_sparse_classes_36k_train_026316 | 4,264 | no_license | [
{
"docstring": "DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2], dp[i][i+1] = 1 max_length >= 3, max_str = s[i:i+k], k is the le... | 2 | stack_v2_sparse_classes_30k_train_009837 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最... | 3a5649357e0f21cbbc5e238351300cd706d533b3 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s: str) -> str:
"""DP 视频:https://www.youtube.com/watch?v=UflHuQj6MVA&t=441s 代码:https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ 思想: 先判断最长的子串是否为 1,2,及大于 3 max_length = 1, max_str = s[0], dp[i][i] = 1 max_length = 2, max_str = s[i:i+2], dp[i][i+1] =... | the_stack_v2_python_sparse | leetcode-py/leetcode5.py | cicihou/LearningProject | train | 0 | |
02be7ae811fd1da2669375fe4ce5a159c17f0a92 | [
"trie = Trie()\nfor word in words:\n trie.add(word)\nret = set()\nvisited = set()\nfor i in xrange(len(board)):\n for j in xrange(len(board[0])):\n self.dfs(board, i, j, trie.root, visited, ret)\nreturn list(ret)",
"c = board[i][j]\nvisited.add((i, j))\nif c in parent.children:\n cur = parent.chil... | <|body_start_0|>
trie = Trie()
for word in words:
trie.add(word)
ret = set()
visited = set()
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.dfs(board, i, j, trie.root, visited, ret)
return list(ret)
<|end_body_0|>... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSearchII_TLE(self, board, words):
"""Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string"""
<|body_0|>
def dfs(self, board, i, j, parent, visited, ret):
""":type paren... | stack_v2_sparse_classes_36k_train_026317 | 4,840 | permissive | [
{
"docstring": "Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string",
"name": "wordSearchII_TLE",
"signature": "def wordSearchII_TLE(self, board, words)"
},
{
"docstring": ":type parent: TrieNode",
"name": "dfs... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSearchII_TLE(self, board, words): Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string
- ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSearchII_TLE(self, board, words): Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string
- ... | 4629a3857b2c57418b86a3b3a7180ecb15e763e3 | <|skeleton|>
class Solution:
def wordSearchII_TLE(self, board, words):
"""Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string"""
<|body_0|>
def dfs(self, board, i, j, parent, visited, ret):
""":type paren... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSearchII_TLE(self, board, words):
"""Trie+dfs pure Trie solution :param board: a list of lists of 1 length string :param words: a list of string :return: a list of string"""
trie = Trie()
for word in words:
trie.add(word)
ret = set()
visite... | the_stack_v2_python_sparse | Word Search II.py | RijuDasgupta9116/LintCode | train | 0 | |
e77a820a86d3222217a9fbe36cc494e583f4c6c5 | [
"try:\n date = ElectionDay.objects.get(date=self.kwargs['date'])\nexcept:\n raise APIException('No elections on {}.'.format(self.kwargs['date']))\nbody_ids = []\nfor election in date.elections.all():\n body = election.race.office.body\n if body:\n body_ids.append(body.uid)\nreturn Body.objects.fi... | <|body_start_0|>
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
body_ids = []
for election in date.elections.all():
body = election.race.office.body
... | BodyMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BodyMixin:
def get_queryset(self):
"""Returns a queryset of all bodies holding an election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try... | stack_v2_sparse_classes_36k_train_026318 | 5,447 | no_license | [
{
"docstring": "Returns a queryset of all bodies holding an election on a date.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Adds ``election_day`` to serializer context.",
"name": "get_serializer_context",
"signature": "def get_serializer_context(sel... | 2 | stack_v2_sparse_classes_30k_train_002727 | Implement the Python class `BodyMixin` described below.
Class description:
Implement the BodyMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all bodies holding an election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer context. | Implement the Python class `BodyMixin` described below.
Class description:
Implement the BodyMixin class.
Method signatures and docstrings:
- def get_queryset(self): Returns a queryset of all bodies holding an election on a date.
- def get_serializer_context(self): Adds ``election_day`` to serializer context.
<|skel... | 9137a0c59e044d081d6c34f0e9e97b789e69bdbf | <|skeleton|>
class BodyMixin:
def get_queryset(self):
"""Returns a queryset of all bodies holding an election on a date."""
<|body_0|>
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BodyMixin:
def get_queryset(self):
"""Returns a queryset of all bodies holding an election on a date."""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except:
raise APIException('No elections on {}.'.format(self.kwargs['date']))
body_ids ... | the_stack_v2_python_sparse | theshow/viewsets.py | The-Politico/politico-elections | train | 0 | |
348e0658f9244f8a6c255af0e7f7d1f5927e7139 | [
"super(AdvantageLearning, self).__init__(nb_actions)\nself.alpha = alpha\nself.gamma = gamma\nself.kappa = kappa",
"if len(episode.actions) > 0:\n last_action = episode.actions[-1]\n last_reward = episode.rewards[-1]\n advantage = episode.values[-2][last_action]\n value = max(episode.values[-2])\n ... | <|body_start_0|>
super(AdvantageLearning, self).__init__(nb_actions)
self.alpha = alpha
self.gamma = gamma
self.kappa = kappa
<|end_body_0|>
<|body_start_1|>
if len(episode.actions) > 0:
last_action = episode.actions[-1]
last_reward = episode.rewards[-1]
... | Advantage Learning learning strategy | AdvantageLearning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvantageLearning:
"""Advantage Learning learning strategy"""
def __init__(self, nb_actions, alpha, gamma, kappa):
"""Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to store the Q-values. Can be any discrete or continuous model... | stack_v2_sparse_classes_36k_train_026319 | 2,800 | no_license | [
{
"docstring": "Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to store the Q-values. Can be any discrete or continuous model. @param alpha Learning factor @param gamma Discount factor @param kappa The smaller this factor is, the strongest the bias toward... | 2 | stack_v2_sparse_classes_30k_train_014004 | Implement the Python class `AdvantageLearning` described below.
Class description:
Advantage Learning learning strategy
Method signatures and docstrings:
- def __init__(self, nb_actions, alpha, gamma, kappa): Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to st... | Implement the Python class `AdvantageLearning` described below.
Class description:
Advantage Learning learning strategy
Method signatures and docstrings:
- def __init__(self, nb_actions, alpha, gamma, kappa): Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to st... | 66c41c5d4aac08a49f0fdc3ef7e2db8d5778f10b | <|skeleton|>
class AdvantageLearning:
"""Advantage Learning learning strategy"""
def __init__(self, nb_actions, alpha, gamma, kappa):
"""Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to store the Q-values. Can be any discrete or continuous model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdvantageLearning:
"""Advantage Learning learning strategy"""
def __init__(self, nb_actions, alpha, gamma, kappa):
"""Constructor. @param nb_actions Number of actions that are possible in the world @param model Model used to store the Q-values. Can be any discrete or continuous model. @param alph... | the_stack_v2_python_sparse | learning/advantagelearning.py | steckdenis/rlpy | train | 11 |
65773b1cf093ca44b66838dcb9b6238dbd005466 | [
"if site is None:\n site = Site.objects.get_current()\nreturn self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=obj.pk, site=site).count()",
"if site is None:\n site = Site.objects.get_current()\nqueryset = self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=o... | <|body_start_0|>
if site is None:
site = Site.objects.get_current()
return self.filter(content_type=ContentType.objects.get_for_model(obj), object_pk=obj.pk, site=site).count()
<|end_body_0|>
<|body_start_1|>
if site is None:
site = Site.objects.get_current()
que... | Manage how users are able to interact with the Like mechanism. | LikeManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
<|body_0|>
def get_already_liked(self, user, obj, site=None):
"""Retur... | stack_v2_sparse_classes_36k_train_026320 | 1,264 | no_license | [
{
"docstring": "Retrieve the number of likes an object has received.",
"name": "get_num_likes_for_object",
"signature": "def get_num_likes_for_object(self, obj, site=None)"
},
{
"docstring": "Return a flag stating whether an object has already been liked.",
"name": "get_already_liked",
"... | 2 | stack_v2_sparse_classes_30k_train_012498 | Implement the Python class `LikeManager` described below.
Class description:
Manage how users are able to interact with the Like mechanism.
Method signatures and docstrings:
- def get_num_likes_for_object(self, obj, site=None): Retrieve the number of likes an object has received.
- def get_already_liked(self, user, o... | Implement the Python class `LikeManager` described below.
Class description:
Manage how users are able to interact with the Like mechanism.
Method signatures and docstrings:
- def get_num_likes_for_object(self, obj, site=None): Retrieve the number of likes an object has received.
- def get_already_liked(self, user, o... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
<|body_0|>
def get_already_liked(self, user, obj, site=None):
"""Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LikeManager:
"""Manage how users are able to interact with the Like mechanism."""
def get_num_likes_for_object(self, obj, site=None):
"""Retrieve the number of likes an object has received."""
if site is None:
site = Site.objects.get_current()
return self.filter(conten... | the_stack_v2_python_sparse | tunobase/social_media/tunosocial/managers.py | unomena/tunobase | train | 0 |
fa653d07f89ef5a1d687ac3f4cecb31dbdeb6824 | [
"parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register('Cmd', TestEchoCmdParser)\nfilesystem_test_lib.Command('/bin/echo', args=['1'])\nsource = rdf_artifact.ArtifactSource(type=rdf_artifact.ArtifactSource.SourceType.COMMAND, attributes={'cmd': '/bin/echo', 'args': ['1']})\next_src = rdf_artifact.ExpandedSource(base_sour... | <|body_start_0|>
parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register('Cmd', TestEchoCmdParser)
filesystem_test_lib.Command('/bin/echo', args=['1'])
source = rdf_artifact.ArtifactSource(type=rdf_artifact.ArtifactSource.SourceType.COMMAND, attributes={'cmd': '/bin/echo', 'args': ['1']})
ext_sr... | ParseResponsesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseResponsesTest:
def testCmdArtifactAction(self):
"""Test the actual client action with parsers."""
<|body_0|>
def testFakeFileArtifactAction(self):
"""Test collecting a file artifact and parsing the response."""
<|body_1|>
def testFakeFileArtifactAct... | stack_v2_sparse_classes_36k_train_026321 | 30,576 | permissive | [
{
"docstring": "Test the actual client action with parsers.",
"name": "testCmdArtifactAction",
"signature": "def testCmdArtifactAction(self)"
},
{
"docstring": "Test collecting a file artifact and parsing the response.",
"name": "testFakeFileArtifactAction",
"signature": "def testFakeFil... | 3 | null | Implement the Python class `ParseResponsesTest` described below.
Class description:
Implement the ParseResponsesTest class.
Method signatures and docstrings:
- def testCmdArtifactAction(self): Test the actual client action with parsers.
- def testFakeFileArtifactAction(self): Test collecting a file artifact and parsi... | Implement the Python class `ParseResponsesTest` described below.
Class description:
Implement the ParseResponsesTest class.
Method signatures and docstrings:
- def testCmdArtifactAction(self): Test the actual client action with parsers.
- def testFakeFileArtifactAction(self): Test collecting a file artifact and parsi... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class ParseResponsesTest:
def testCmdArtifactAction(self):
"""Test the actual client action with parsers."""
<|body_0|>
def testFakeFileArtifactAction(self):
"""Test collecting a file artifact and parsing the response."""
<|body_1|>
def testFakeFileArtifactAct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParseResponsesTest:
def testCmdArtifactAction(self):
"""Test the actual client action with parsers."""
parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register('Cmd', TestEchoCmdParser)
filesystem_test_lib.Command('/bin/echo', args=['1'])
source = rdf_artifact.ArtifactSource(type=rdf_ar... | the_stack_v2_python_sparse | grr/client/grr_response_client/client_actions/artifact_collector_test.py | google/grr | train | 4,683 | |
16235eb9555ab1833087ca6d9798d2f0cca5f3ef | [
"logging.debug('get sensor: %d' % id)\nbuffer = self._app.getSensor(id)\nreturn str('return from get id=%d: %s' % (id, buffer))",
"if type != None:\n logging.info('set type: %s on id: %d' % (type, id))\n self._app.setSensorType(id, int(type))\nelse:\n type = request.args.get('type')\n if type == None:... | <|body_start_0|>
logging.debug('get sensor: %d' % id)
buffer = self._app.getSensor(id)
return str('return from get id=%d: %s' % (id, buffer))
<|end_body_0|>
<|body_start_1|>
if type != None:
logging.info('set type: %s on id: %d' % (type, id))
self._app.setSensorT... | Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type | SensorsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorsView:
"""Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type"""
def get(self, id):
"""Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str"""
<|body_0|>
def put(self, id, type=None):
... | stack_v2_sparse_classes_36k_train_026322 | 7,133 | permissive | [
{
"docstring": "Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Change a sensor type. ** PUT ** to change the sensors type. Give type in url or as query_string. :param int id: n... | 2 | stack_v2_sparse_classes_30k_train_000649 | Implement the Python class `SensorsView` described below.
Class description:
Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type
Method signatures and docstrings:
- def get(self, id): Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str
- def ... | Implement the Python class `SensorsView` described below.
Class description:
Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type
Method signatures and docstrings:
- def get(self, id): Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str
- def ... | f661c8767f819490e170a2cd80f82716301cec65 | <|skeleton|>
class SensorsView:
"""Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type"""
def get(self, id):
"""Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str"""
<|body_0|>
def put(self, id, type=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SensorsView:
"""Sensor class. ** GET ** to read the sensor state ** PUT ** change the sensor type"""
def get(self, id):
"""Read a sensor. ** GET ** to read the sensors value. :param int id: number of channel returns: str"""
logging.debug('get sensor: %d' % id)
buffer = self._app.g... | the_stack_v2_python_sparse | RaspberryPi/scripts/WebService.py | janhieber/WaterCtrl | train | 6 |
98563d5f71f5565532860c96cb91a660e54cca54 | [
"new_objects = self.row_converter.block_converter.converter.new_objects\nnew_people = new_objects[Person]\npeople = []\nemails = []\nfor email in self.raw_value.splitlines():\n email = email.strip()\n if not email:\n continue\n if email in new_people:\n people.append(new_people[email].id or 0... | <|body_start_0|>
new_objects = self.row_converter.block_converter.converter.new_objects
new_people = new_objects[Person]
people = []
emails = []
for email in self.raw_value.splitlines():
email = email.strip()
if not email:
continue
... | Handler for default verifiers and assessors. | DefaultPersonColumnHandler | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultPersonColumnHandler:
"""Handler for default verifiers and assessors."""
def _parse_email_values(self):
"""Parse an email list of default assessors. This is the "other" option in the default assessor dropdown menu."""
<|body_0|>
def _parse_label_values(self):
... | stack_v2_sparse_classes_36k_train_026323 | 4,359 | permissive | [
{
"docstring": "Parse an email list of default assessors. This is the \"other\" option in the default assessor dropdown menu.",
"name": "_parse_email_values",
"signature": "def _parse_email_values(self)"
},
{
"docstring": "Parse predefined default assessors. These values are the normal selection... | 5 | stack_v2_sparse_classes_30k_train_015794 | Implement the Python class `DefaultPersonColumnHandler` described below.
Class description:
Handler for default verifiers and assessors.
Method signatures and docstrings:
- def _parse_email_values(self): Parse an email list of default assessors. This is the "other" option in the default assessor dropdown menu.
- def ... | Implement the Python class `DefaultPersonColumnHandler` described below.
Class description:
Handler for default verifiers and assessors.
Method signatures and docstrings:
- def _parse_email_values(self): Parse an email list of default assessors. This is the "other" option in the default assessor dropdown menu.
- def ... | 9bdc0fc6ca9e252f4919db682d80e360d5581eb4 | <|skeleton|>
class DefaultPersonColumnHandler:
"""Handler for default verifiers and assessors."""
def _parse_email_values(self):
"""Parse an email list of default assessors. This is the "other" option in the default assessor dropdown menu."""
<|body_0|>
def _parse_label_values(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultPersonColumnHandler:
"""Handler for default verifiers and assessors."""
def _parse_email_values(self):
"""Parse an email list of default assessors. This is the "other" option in the default assessor dropdown menu."""
new_objects = self.row_converter.block_converter.converter.new_ob... | the_stack_v2_python_sparse | src/ggrc/converters/handlers/default_people.py | HLD/ggrc-core | train | 0 |
85af3da0ab8ca495c63c5630722630c8f6447ca0 | [
"for procurement in self.browse(cr, uid, ids, context=context):\n if procurement.product_id.fal_proc_po_disable:\n return False\nreturn super(procurement_order, self).check_buy(cr, uid, ids, context)",
"ok = True\nif procurement.move_id:\n message = False\n id = procurement.move_id.id\n if not ... | <|body_start_0|>
for procurement in self.browse(cr, uid, ids, context=context):
if procurement.product_id.fal_proc_po_disable:
return False
return super(procurement_order, self).check_buy(cr, uid, ids, context)
<|end_body_0|>
<|body_start_1|>
ok = True
if pro... | procurement_order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class procurement_order:
def check_buy(self, cr, uid, ids, context=None):
"""return True if the supply method of the mto product is 'buy'"""
<|body_0|>
def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
"""Checks procurement move state. @param proc... | stack_v2_sparse_classes_36k_train_026324 | 2,641 | no_license | [
{
"docstring": "return True if the supply method of the mto product is 'buy'",
"name": "check_buy",
"signature": "def check_buy(self, cr, uid, ids, context=None)"
},
{
"docstring": "Checks procurement move state. @param procurement: Current procurement. @return: True or move id.",
"name": "_... | 2 | null | Implement the Python class `procurement_order` described below.
Class description:
Implement the procurement_order class.
Method signatures and docstrings:
- def check_buy(self, cr, uid, ids, context=None): return True if the supply method of the mto product is 'buy'
- def _check_make_to_stock_product(self, cr, uid, ... | Implement the Python class `procurement_order` described below.
Class description:
Implement the procurement_order class.
Method signatures and docstrings:
- def check_buy(self, cr, uid, ids, context=None): return True if the supply method of the mto product is 'buy'
- def _check_make_to_stock_product(self, cr, uid, ... | be96a209479259cd5b47dec73694938848a2db6c | <|skeleton|>
class procurement_order:
def check_buy(self, cr, uid, ids, context=None):
"""return True if the supply method of the mto product is 'buy'"""
<|body_0|>
def _check_make_to_stock_product(self, cr, uid, procurement, context=None):
"""Checks procurement move state. @param proc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class procurement_order:
def check_buy(self, cr, uid, ids, context=None):
"""return True if the supply method of the mto product is 'buy'"""
for procurement in self.browse(cr, uid, ids, context=context):
if procurement.product_id.fal_proc_po_disable:
return False
... | the_stack_v2_python_sparse | fal_procurement_no_po/purchase.py | jeanabreu/falinwa_branch | train | 0 | |
c5c8881bd0be191f11f319032efc6f9d1dd40f21 | [
"res = defaultdict(list)\nfor s in strs:\n res[tuple(sorted(s))].append(s)\nreturn list(res.values())",
"res = defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n res[tuple(count)].append(s)\nreturn list(res.values())"
] | <|body_start_0|>
res = defaultdict(list)
for s in strs:
res[tuple(sorted(s))].append(s)
return list(res.values())
<|end_body_0|>
<|body_start_1|>
res = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[str]:
"""方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词"""
<|body_0|>
def fun2(self, strs):
"""方法二:按计数分类 思路 当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_026325 | 858 | no_license | [
{
"docstring": "方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs: list[str]) -> list[str]"
},
{
"docstring": "方法二:按计数分类 思路 当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。",
"name": "fun2",
"signature": "def fun2(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: list[str]) -> list[str]: 方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词
- def fun2(self, strs): 方法二:按计数分类 思路 当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: list[str]) -> list[str]: 方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词
- def fun2(self, strs): 方法二:按计数分类 思路 当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。
<|sk... | 0b10f5731690da7998add288e4b0b87d5d71a97e | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[str]:
"""方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词"""
<|body_0|>
def fun2(self, strs):
"""方法二:按计数分类 思路 当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs: list[str]) -> list[str]:
"""方法一:排序数组分类 思路 当且仅当它们的排序字符串相等时,两个字符串是字母异位词"""
res = defaultdict(list)
for s in strs:
res[tuple(sorted(s))].append(s)
return list(res.values())
def fun2(self, strs):
"""方法二:按计数分类 思路 当且仅当它... | the_stack_v2_python_sparse | leetcode/leetcode/49.字母异位词分组.py | GGL12/myStudy | train | 0 | |
6b00a9bf98504e604ea482a9cddc3674ce47d7cf | [
"hex_addr = _HexAddressRegexpFor(android_abi)\nself._re_backtrace = re.compile('.*#(?P<frame>[0-9]{2})\\\\s+' + '(..)\\\\s+' + '(?P<rel_pc>' + hex_addr + ')\\\\s+' + '(?P<location>[^ \\\\t]+)' + '(\\\\s+\\\\(offset 0x(?P<offset>[0-9a-f]+)\\\\))?')\nself._re_location_offset = re.compile('.*\\\\+0x(?P<offset>[0-9a-f]... | <|body_start_0|>
hex_addr = _HexAddressRegexpFor(android_abi)
self._re_backtrace = re.compile('.*#(?P<frame>[0-9]{2})\\s+' + '(..)\\s+' + '(?P<rel_pc>' + hex_addr + ')\\s+' + '(?P<location>[^ \\t]+)' + '(\\s+\\(offset 0x(?P<offset>[0-9a-f]+)\\))?')
self._re_location_offset = re.compile('.*\\+0x(... | Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order to detect which library offsets will need to be symbolized during a future parse. Doin... | BacktraceTranslator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BacktraceTranslator:
"""Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order to detect which library offsets will ne... | stack_v2_sparse_classes_36k_train_026326 | 28,535 | permissive | [
{
"docstring": "Initialize instance. Args: android_abi: Android CPU ABI name (e.g. 'armeabi-v7a'). apk_translator: ApkLibraryPathTranslator instance used to convert mapped APK file offsets into uncompressed library file paths with new offsets.",
"name": "__init__",
"signature": "def __init__(self, andro... | 4 | null | Implement the Python class `BacktraceTranslator` described below.
Class description:
Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order ... | Implement the Python class `BacktraceTranslator` described below.
Class description:
Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order ... | acefdaaadd3ef46f10f63d1acae2259e4024d383 | <|skeleton|>
class BacktraceTranslator:
"""Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order to detect which library offsets will ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BacktraceTranslator:
"""Translates backtrace-related lines in a tombstone or crash report. Usage is the following: 1) Create new instance with appropriate arguments. 2) If the tombstone / logcat input is available, one can call FindLibraryOffsets() in order to detect which library offsets will need to be symb... | the_stack_v2_python_sparse | build/android/pylib/symbols/symbol_utils.py | youtube/cobalt | train | 169 |
2b979fed4ee2f59563e048954de05b486f264ca3 | [
"nums1.sort()\nnums2.sort()\ni, j = (0, 0)\nresult = []\nwhile i < len(nums1) and j < len(nums2):\n if nums1[i] == nums2[j]:\n result.append(nums1[i])\n i += 1\n j += 1\n elif nums1[i] < nums2[j]:\n i += 1\n else:\n j += 1\nreturn result",
"counter1, counter2 = ({}, {})... | <|body_start_0|>
nums1.sort()
nums2.sort()
i, j = (0, 0)
result = []
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
result.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_026327 | 1,099 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(se... | 2 | stack_v2_sparse_classes_30k_train_014202 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[i... | 9f6ccf8a8fd8eaaeae2f11557b73be4e5e7adba8 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
nums1.sort()
nums2.sort()
i, j = (0, 0)
result = []
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
r... | the_stack_v2_python_sparse | python/350.py | MrRabbit0o0/LeetCode | train | 0 | |
1d80b38b793fdd2f0e6cc0ed08f9d1c0bdd385a0 | [
"self.comparer_title = ComparerTitle()\nself.comparer_desciption = ComparerDescription()\nself.comparer_text = ComparerText()\nself.comparer_author = ComparerAuthor()\nself.comparer_date = ComparerDate()",
"result = ArticleCandidate()\nresult.title = self.comparer_title.extract(item, article_candidates)\nresult.d... | <|body_start_0|>
self.comparer_title = ComparerTitle()
self.comparer_desciption = ComparerDescription()
self.comparer_text = ComparerText()
self.comparer_author = ComparerAuthor()
self.comparer_date = ComparerDate()
<|end_body_0|>
<|body_start_1|>
result = ArticleCandida... | Sends the list of ArticleCandidates to the subcomparer and saves the result in Article. | Comparer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparer:
"""Sends the list of ArticleCandidates to the subcomparer and saves the result in Article."""
def __init__(self):
"""Initializes the Comparer classes with an object each."""
<|body_0|>
def compare(self, item, article_candidates):
"""Compares the article... | stack_v2_sparse_classes_36k_train_026328 | 1,833 | no_license | [
{
"docstring": "Initializes the Comparer classes with an object each.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compares the article candidates using the different submodules and saves the best results in new ArticleCandidate object :param item: The NewscrawlerIt... | 2 | stack_v2_sparse_classes_30k_test_001188 | Implement the Python class `Comparer` described below.
Class description:
Sends the list of ArticleCandidates to the subcomparer and saves the result in Article.
Method signatures and docstrings:
- def __init__(self): Initializes the Comparer classes with an object each.
- def compare(self, item, article_candidates):... | Implement the Python class `Comparer` described below.
Class description:
Sends the list of ArticleCandidates to the subcomparer and saves the result in Article.
Method signatures and docstrings:
- def __init__(self): Initializes the Comparer classes with an object each.
- def compare(self, item, article_candidates):... | 733a48b20fbe45fe86f656d6a40afdc41be2c223 | <|skeleton|>
class Comparer:
"""Sends the list of ArticleCandidates to the subcomparer and saves the result in Article."""
def __init__(self):
"""Initializes the Comparer classes with an object each."""
<|body_0|>
def compare(self, item, article_candidates):
"""Compares the article... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Comparer:
"""Sends the list of ArticleCandidates to the subcomparer and saves the result in Article."""
def __init__(self):
"""Initializes the Comparer classes with an object each."""
self.comparer_title = ComparerTitle()
self.comparer_desciption = ComparerDescription()
se... | the_stack_v2_python_sparse | archive_crawling (as on Neo)/pipeline/extractor/comparer/comparer.py | Anacoder1/archive_crawling | train | 0 |
224358ce7f789ed245f0722eabaf20d47eaabeba | [
"RPObject.__init__(self)\nself._pipeline = pipeline\nself._parent = parent\nself._node = self._parent.attach_new_node('ExposureWidgetNode')\nself._create_components()",
"self._node.hide()\nself._storage_tex = Image.create_2d('ExposureDisplay', 140, 20, 'RGBA8')\nself._storage_tex.set_clear_color(Vec4(0.2, 0.6, 1.... | <|body_start_0|>
RPObject.__init__(self)
self._pipeline = pipeline
self._parent = parent
self._node = self._parent.attach_new_node('ExposureWidgetNode')
self._create_components()
<|end_body_0|>
<|body_start_1|>
self._node.hide()
self._storage_tex = Image.create_2... | Widget to show the current exposure | ExposureWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExposureWidget:
"""Widget to show the current exposure"""
def __init__(self, pipeline, parent):
"""Inits the widget"""
<|body_0|>
def _create_components(self):
"""Internal method to init the widgets components"""
<|body_1|>
def _late_init(self, task)... | stack_v2_sparse_classes_36k_train_026329 | 3,914 | permissive | [
{
"docstring": "Inits the widget",
"name": "__init__",
"signature": "def __init__(self, pipeline, parent)"
},
{
"docstring": "Internal method to init the widgets components",
"name": "_create_components",
"signature": "def _create_components(self)"
},
{
"docstring": "Gets called ... | 3 | null | Implement the Python class `ExposureWidget` described below.
Class description:
Widget to show the current exposure
Method signatures and docstrings:
- def __init__(self, pipeline, parent): Inits the widget
- def _create_components(self): Internal method to init the widgets components
- def _late_init(self, task): Ge... | Implement the Python class `ExposureWidget` described below.
Class description:
Widget to show the current exposure
Method signatures and docstrings:
- def __init__(self, pipeline, parent): Inits the widget
- def _create_components(self): Internal method to init the widgets components
- def _late_init(self, task): Ge... | 3f610cf72002beb11e73a47c2f118e35ff2d9575 | <|skeleton|>
class ExposureWidget:
"""Widget to show the current exposure"""
def __init__(self, pipeline, parent):
"""Inits the widget"""
<|body_0|>
def _create_components(self):
"""Internal method to init the widgets components"""
<|body_1|>
def _late_init(self, task)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExposureWidget:
"""Widget to show the current exposure"""
def __init__(self, pipeline, parent):
"""Inits the widget"""
RPObject.__init__(self)
self._pipeline = pipeline
self._parent = parent
self._node = self._parent.attach_new_node('ExposureWidgetNode')
se... | the_stack_v2_python_sparse | spacedrive/renderpipeline/rpcore/gui/exposure_widget.py | croxis/SpaceDrive | train | 5 |
44eafb8c193c6c5ba65faf9c6863a6951af3361c | [
"def back_track(string='', left=0, right=0):\n if len(string) == 2 * num:\n combinations.append(string)\n if left < num:\n back_track(string + '(', left + 1, right)\n if right < left:\n back_track(string + ')', left, right + 1)\nif num == 0:\n return ['']\ncombinations = []\nback_tr... | <|body_start_0|>
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combinations.append(string)
if left < num:
back_track(string + '(', left + 1, right)
if right < left:
back_track(string + ')', left, right +... | Parenthesis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_36k_train_026330 | 1,434 | no_license | [
{
"docstring": "Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:",
"name": "generate_combinations",
"signature": "def generate_combinations(self, num: int) -> List[str]"
},
{
"docstring": "Approach: Closure Number Time Complexity: ... | 2 | stack_v2_sparse_classes_30k_train_016557 | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combin... | the_stack_v2_python_sparse | math_and_srings/paranthesis.py | Shiv2157k/leet_code | train | 1 | |
2eac61f47ea89396592342a54aaf486fbafd9e63 | [
"if action == 'walk':\n print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))\n agent.walk()\nelif action == 'eat':\n items = self.list_things_at(agent.location, tclass=Food)\n if len(items) != 0:\n if agent.eat(items[0]):\n print('{} ate {} at loca... | <|body_start_0|>
if action == 'walk':
print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))
agent.walk()
elif action == 'eat':
items = self.list_things_at(agent.location, tclass=Food)
if len(items) != 0:
... | NewPark | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewPark:
def execute_action(self, agent, action):
"""changes the state of the environment based on what the agent does."""
<|body_0|>
def is_done(self):
"""By default, we're done when we can't find a live agent, but to prevent killing our cute dog, we will stop befor... | stack_v2_sparse_classes_36k_train_026331 | 12,926 | no_license | [
{
"docstring": "changes the state of the environment based on what the agent does.",
"name": "execute_action",
"signature": "def execute_action(self, agent, action)"
},
{
"docstring": "By default, we're done when we can't find a live agent, but to prevent killing our cute dog, we will stop befor... | 2 | stack_v2_sparse_classes_30k_train_013850 | Implement the Python class `NewPark` described below.
Class description:
Implement the NewPark class.
Method signatures and docstrings:
- def execute_action(self, agent, action): changes the state of the environment based on what the agent does.
- def is_done(self): By default, we're done when we can't find a live ag... | Implement the Python class `NewPark` described below.
Class description:
Implement the NewPark class.
Method signatures and docstrings:
- def execute_action(self, agent, action): changes the state of the environment based on what the agent does.
- def is_done(self): By default, we're done when we can't find a live ag... | 93e21966b78e61117a37d2a90e3ad00fa8a78ba0 | <|skeleton|>
class NewPark:
def execute_action(self, agent, action):
"""changes the state of the environment based on what the agent does."""
<|body_0|>
def is_done(self):
"""By default, we're done when we can't find a live agent, but to prevent killing our cute dog, we will stop befor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewPark:
def execute_action(self, agent, action):
"""changes the state of the environment based on what the agent does."""
if action == 'walk':
print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))
agent.walk()
elif action ==... | the_stack_v2_python_sparse | Introdução à Inteligência Artificial/aula1/agentes inteligentes.py | eduardopds/VirtusUp | train | 0 | |
31b4e5269f4bf45738094914c65fd56db1e4650e | [
"url = reverse('landing-page')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)",
"response = self.client.get(reverse('landing-page'))\nself.assertContains(response, 'Zgloś instytucję')\nself.assertTrue('institutions' in response.context)",
"institution1 = create_institution()\ninst... | <|body_start_0|>
url = reverse('landing-page')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
response = self.client.get(reverse('landing-page'))
self.assertContains(response, 'Zgloś instytucję')
self.assertTru... | LandingPageTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LandingPageTests:
def test_landing_page_access(self):
"""Verifies that landing page load properly and returns 200 ok status"""
<|body_0|>
def test_context_data_no_instutions(self):
"""If no institutions were created appropriate message is displayed"""
<|body_... | stack_v2_sparse_classes_36k_train_026332 | 9,069 | no_license | [
{
"docstring": "Verifies that landing page load properly and returns 200 ok status",
"name": "test_landing_page_access",
"signature": "def test_landing_page_access(self)"
},
{
"docstring": "If no institutions were created appropriate message is displayed",
"name": "test_context_data_no_instu... | 5 | stack_v2_sparse_classes_30k_train_014463 | Implement the Python class `LandingPageTests` described below.
Class description:
Implement the LandingPageTests class.
Method signatures and docstrings:
- def test_landing_page_access(self): Verifies that landing page load properly and returns 200 ok status
- def test_context_data_no_instutions(self): If no institut... | Implement the Python class `LandingPageTests` described below.
Class description:
Implement the LandingPageTests class.
Method signatures and docstrings:
- def test_landing_page_access(self): Verifies that landing page load properly and returns 200 ok status
- def test_context_data_no_instutions(self): If no institut... | 8cb619ed9208800fffec63e7aca7f4ef97098152 | <|skeleton|>
class LandingPageTests:
def test_landing_page_access(self):
"""Verifies that landing page load properly and returns 200 ok status"""
<|body_0|>
def test_context_data_no_instutions(self):
"""If no institutions were created appropriate message is displayed"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LandingPageTests:
def test_landing_page_access(self):
"""Verifies that landing page load properly and returns 200 ok status"""
url = reverse('landing-page')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_context_data_no_instutions(self... | the_stack_v2_python_sparse | inkind/tests.py | Michal-Rakowski/donation-project | train | 1 | |
8d2b2a183b0917a94012e56b77fa2837e644c47c | [
"if len(nums) < 2:\n return 0\nminP = nums[0]\nprofit = 0\nfor p in nums:\n profit = max(profit, p - minP)\n minP = min(minP, p)\nreturn profit",
"maxprofit = 0\nfor i in range(len(nums) - 1):\n fit = max(nums[i + 1:]) - nums[i]\n if fit > maxprofit:\n maxprofit = fit\nreturn maxprofit"
] | <|body_start_0|>
if len(nums) < 2:
return 0
minP = nums[0]
profit = 0
for p in nums:
profit = max(profit, p - minP)
minP = min(minP, p)
return profit
<|end_body_0|>
<|body_start_1|>
maxprofit = 0
for i in range(len(nums) - 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
<|body_0|>
def max_profit_2(self, nums):
""":param nums:list[int] :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 2:
return 0
... | stack_v2_sparse_classes_36k_train_026333 | 1,554 | no_license | [
{
"docstring": ":param nums: list[int] :return: int",
"name": "max_profit",
"signature": "def max_profit(self, nums)"
},
{
"docstring": ":param nums:list[int] :return: int",
"name": "max_profit_2",
"signature": "def max_profit_2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015424 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, nums): :param nums: list[int] :return: int
- def max_profit_2(self, nums): :param nums:list[int] :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, nums): :param nums: list[int] :return: int
- def max_profit_2(self, nums): :param nums:list[int] :return: int
<|skeleton|>
class Solution:
def max_prof... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
<|body_0|>
def max_profit_2(self, nums):
""":param nums:list[int] :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
if len(nums) < 2:
return 0
minP = nums[0]
profit = 0
for p in nums:
profit = max(profit, p - minP)
minP = min(minP, p)
return profit
def max_... | the_stack_v2_python_sparse | leetcode/35_maxprofit_only.py | Yara7L/python_algorithm | train | 0 | |
fb11f150c17464687c6b74bcd58c7fcb80635ecc | [
"ret = -1\nfor i in range(len(strs)):\n for j in range(len(strs)):\n if j != i and self.judge(strs[i], strs[j]):\n break\n else:\n ret = max(ret, len(strs[i]))\nreturn ret",
"if len(s2) < len(s1):\n return False\nindex_of_s1 = 0\nindex_of_s2 = 0\nwhile index_of_s1 < len(s1) and i... | <|body_start_0|>
ret = -1
for i in range(len(strs)):
for j in range(len(strs)):
if j != i and self.judge(strs[i], strs[j]):
break
else:
ret = max(ret, len(strs[i]))
return ret
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLUSlength(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_0|>
def judge(self, s1, s2):
"""if s1 is a subsequence of s2 :param s1: :param s2: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = -1
for ... | stack_v2_sparse_classes_36k_train_026334 | 1,176 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: int",
"name": "findLUSlength",
"signature": "def findLUSlength(self, strs)"
},
{
"docstring": "if s1 is a subsequence of s2 :param s1: :param s2: :return:",
"name": "judge",
"signature": "def judge(self, s1, s2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005497 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLUSlength(self, strs): :type strs: List[str] :rtype: int
- def judge(self, s1, s2): if s1 is a subsequence of s2 :param s1: :param s2: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLUSlength(self, strs): :type strs: List[str] :rtype: int
- def judge(self, s1, s2): if s1 is a subsequence of s2 :param s1: :param s2: :return:
<|skeleton|>
class Soluti... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findLUSlength(self, strs):
""":type strs: List[str] :rtype: int"""
<|body_0|>
def judge(self, s1, s2):
"""if s1 is a subsequence of s2 :param s1: :param s2: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLUSlength(self, strs):
""":type strs: List[str] :rtype: int"""
ret = -1
for i in range(len(strs)):
for j in range(len(strs)):
if j != i and self.judge(strs[i], strs[j]):
break
else:
ret = max(... | the_stack_v2_python_sparse | python/leetcode/522_Longest_Uncommon_Subsequence_II.py | bobcaoge/my-code | train | 0 | |
019f1141aafc7b72fcafb5e954970e316bcb1538 | [
"node_prop: NodeProperty = self._node.aux_properties[self._control]\nif node_prop.value == ISY_VALUE_UNKNOWN:\n return None\nif self.entity_description.native_unit_of_measurement == PERCENTAGE and node_prop.uom == UOM_8_BIT_RANGE:\n return ranged_value_to_percentage(ON_RANGE, node_prop.value)\nreturn int(node... | <|body_start_0|>
node_prop: NodeProperty = self._node.aux_properties[self._control]
if node_prop.value == ISY_VALUE_UNKNOWN:
return None
if self.entity_description.native_unit_of_measurement == PERCENTAGE and node_prop.uom == UOM_8_BIT_RANGE:
return ranged_value_to_percen... | Representation of a ISY/IoX Aux Control Number entity. | ISYAuxControlNumberEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYAuxControlNumberEntity:
"""Representation of a ISY/IoX Aux Control Number entity."""
def native_value(self) -> float | int | None:
"""Return the state of the variable."""
<|body_0|>
async def async_set_native_value(self, value: float) -> None:
"""Update the cu... | stack_v2_sparse_classes_36k_train_026335 | 10,460 | permissive | [
{
"docstring": "Return the state of the variable.",
"name": "native_value",
"signature": "def native_value(self) -> float | int | None"
},
{
"docstring": "Update the current value.",
"name": "async_set_native_value",
"signature": "async def async_set_native_value(self, value: float) -> N... | 2 | null | Implement the Python class `ISYAuxControlNumberEntity` described below.
Class description:
Representation of a ISY/IoX Aux Control Number entity.
Method signatures and docstrings:
- def native_value(self) -> float | int | None: Return the state of the variable.
- async def async_set_native_value(self, value: float) -... | Implement the Python class `ISYAuxControlNumberEntity` described below.
Class description:
Representation of a ISY/IoX Aux Control Number entity.
Method signatures and docstrings:
- def native_value(self) -> float | int | None: Return the state of the variable.
- async def async_set_native_value(self, value: float) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ISYAuxControlNumberEntity:
"""Representation of a ISY/IoX Aux Control Number entity."""
def native_value(self) -> float | int | None:
"""Return the state of the variable."""
<|body_0|>
async def async_set_native_value(self, value: float) -> None:
"""Update the cu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ISYAuxControlNumberEntity:
"""Representation of a ISY/IoX Aux Control Number entity."""
def native_value(self) -> float | int | None:
"""Return the state of the variable."""
node_prop: NodeProperty = self._node.aux_properties[self._control]
if node_prop.value == ISY_VALUE_UNKNOWN:... | the_stack_v2_python_sparse | homeassistant/components/isy994/number.py | home-assistant/core | train | 35,501 |
047bf30cea8bfbe663760abb27746838606a8d0a | [
"try:\n existing_favourite = Favourite.objects.get(article=article, user=profile)\n existing_favourite.delete()\nexcept Favourite.DoesNotExist:\n pass\ndata = {'article': article.id, 'user': profile, 'favourite': favourite}\nserializer = self.serializer_class(data=data)\nserializer.is_valid(raise_exception... | <|body_start_0|>
try:
existing_favourite = Favourite.objects.get(article=article, user=profile)
existing_favourite.delete()
except Favourite.DoesNotExist:
pass
data = {'article': article.id, 'user': profile, 'favourite': favourite}
serializer = self.se... | Define the view for Favourite | FavouriteView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavouriteView:
"""Define the view for Favourite"""
def set_favourite(self, article, profile, favourite):
"""Helper method to set the favourite"""
<|body_0|>
def post(self, request):
"""POST a favourite on an article with a given slug"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_026336 | 5,684 | permissive | [
{
"docstring": "Helper method to set the favourite",
"name": "set_favourite",
"signature": "def set_favourite(self, article, profile, favourite)"
},
{
"docstring": "POST a favourite on an article with a given slug",
"name": "post",
"signature": "def post(self, request)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_013049 | Implement the Python class `FavouriteView` described below.
Class description:
Define the view for Favourite
Method signatures and docstrings:
- def set_favourite(self, article, profile, favourite): Helper method to set the favourite
- def post(self, request): POST a favourite on an article with a given slug
- def ge... | Implement the Python class `FavouriteView` described below.
Class description:
Define the view for Favourite
Method signatures and docstrings:
- def set_favourite(self, article, profile, favourite): Helper method to set the favourite
- def post(self, request): POST a favourite on an article with a given slug
- def ge... | a304718929936dd4a759d737fb3570d6cc25fb76 | <|skeleton|>
class FavouriteView:
"""Define the view for Favourite"""
def set_favourite(self, article, profile, favourite):
"""Helper method to set the favourite"""
<|body_0|>
def post(self, request):
"""POST a favourite on an article with a given slug"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FavouriteView:
"""Define the view for Favourite"""
def set_favourite(self, article, profile, favourite):
"""Helper method to set the favourite"""
try:
existing_favourite = Favourite.objects.get(article=article, user=profile)
existing_favourite.delete()
exce... | the_stack_v2_python_sparse | authors/apps/favourite/views.py | andela/ah-jumanji | train | 1 |
74843c6faf6579dc0c046e1f93774b12c8614a57 | [
"self.access_token_type = 'access_token'\nself.device_authorization_endpoint = device_authorization_endpoint\nself.code_challenge_method = code_challenge_method\nsuper(OidcDeviceAuthorization, self).__init__(auth_url=auth_url, identity_provider=identity_provider, protocol=protocol, client_id=client_id, client_secre... | <|body_start_0|>
self.access_token_type = 'access_token'
self.device_authorization_endpoint = device_authorization_endpoint
self.code_challenge_method = code_challenge_method
super(OidcDeviceAuthorization, self).__init__(auth_url=auth_url, identity_provider=identity_provider, protocol=pr... | Implementation for OAuth 2.0 Device Authorization Grant. | OidcDeviceAuthorization | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OidcDeviceAuthorization:
"""Implementation for OAuth 2.0 Device Authorization Grant."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret=None, access_token_endpoint=None, device_authorization_endpoint=None, discovery_endpoint=None, code_challenge=None, code_... | stack_v2_sparse_classes_36k_train_026337 | 26,868 | permissive | [
{
"docstring": "The OAuth 2.0 Device Authorization plugin expects the following. :param device_authorization_endpoint: OAuth 2.0 Device Authorization Endpoint, for example: https://localhost:8020/oidc/authorize/device Note that if a discovery document is provided this value will override the discovered one. :ty... | 6 | stack_v2_sparse_classes_30k_train_011782 | Implement the Python class `OidcDeviceAuthorization` described below.
Class description:
Implementation for OAuth 2.0 Device Authorization Grant.
Method signatures and docstrings:
- def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret=None, access_token_endpoint=None, device_authorizatio... | Implement the Python class `OidcDeviceAuthorization` described below.
Class description:
Implementation for OAuth 2.0 Device Authorization Grant.
Method signatures and docstrings:
- def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret=None, access_token_endpoint=None, device_authorizatio... | e6f3999c6f2f846e3dda505343166ab8c8346c2a | <|skeleton|>
class OidcDeviceAuthorization:
"""Implementation for OAuth 2.0 Device Authorization Grant."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret=None, access_token_endpoint=None, device_authorization_endpoint=None, discovery_endpoint=None, code_challenge=None, code_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OidcDeviceAuthorization:
"""Implementation for OAuth 2.0 Device Authorization Grant."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret=None, access_token_endpoint=None, device_authorization_endpoint=None, discovery_endpoint=None, code_challenge=None, code_challenge_met... | the_stack_v2_python_sparse | keystoneauth1/identity/v3/oidc.py | openstack/keystoneauth | train | 51 |
4da2bd850498e9e926ba0fb5809dad54a38b6fa1 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"K = np.zeros((X1.shape[0], X2.shape[0]))\nfor i, x1 in enumerate(X1):\n for j, x2 in enumerate(X2):\n K[i, j] = np.exp(-0.5 / self.l ** 2 * (x1 - x2) ** 2)\nreturn self.sigma_f ** 2 * K",
"K_... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
K = np.zeros((X1.shape[0], X2.shape[0]))
for i, x1 in enumerate(X1):
for j, x2 in enumerate(X2):
... | class that represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""initialization"""
<|body_0|>
def kernel(self, X1, X2):
"""function that calculates the covariance kernel matrix between two matrice... | stack_v2_sparse_classes_36k_train_026338 | 1,782 | no_license | [
{
"docstring": "initialization",
"name": "__init__",
"signature": "def __init__(self, X_init, Y_init, l=1, sigma_f=1)"
},
{
"docstring": "function that calculates the covariance kernel matrix between two matrices",
"name": "kernel",
"signature": "def kernel(self, X1, X2)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_002621 | Implement the Python class `GaussianProcess` described below.
Class description:
class that represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): initialization
- def kernel(self, X1, X2): function that calculates the covariance kernel matri... | Implement the Python class `GaussianProcess` described below.
Class description:
class that represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): initialization
- def kernel(self, X1, X2): function that calculates the covariance kernel matri... | d45e18bcbe1898a1585e4b7b61f3a7af9f00e787 | <|skeleton|>
class GaussianProcess:
"""class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""initialization"""
<|body_0|>
def kernel(self, X1, X2):
"""function that calculates the covariance kernel matrix between two matrice... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""class that represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""initialization"""
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/2-gp.py | jlassi1/holbertonschool-machine_learning | train | 1 |
1207691c557dcb38529c7834eb078a369f7cf02e | [
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor c in coins:\n for n in range(c, amount + 1):\n dp[n] += dp[n - c]\nreturn dp[-1]",
"dp = [0] * (amount + 1)\nfor n in range(amount + 1):\n for coin in coins:\n if coin + n <= amount:\n dp[coin + n] = dp[n] + 1\n print(n, dp)\nreturn dp[-1]... | <|body_start_0|>
dp = [0] * (amount + 1)
dp[0] = 1
for c in coins:
for n in range(c, amount + 1):
dp[n] += dp[n - c]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
dp = [0] * (amount + 1)
for n in range(amount + 1):
for coin in coin... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_failed(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
def change_TLE(self, amount, co... | stack_v2_sparse_classes_36k_train_026339 | 2,466 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change_failed",
"signature": "def change_failed(self, amount, coins)"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_failed(self, amount, coins): :type amount: int :type coins: List[int] :rtype: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_failed(self, amount, coins): :type amount: int :type coins: List[int] :rtype: i... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_failed(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
def change_TLE(self, amount, co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
dp = [0] * (amount + 1)
dp[0] = 1
for c in coins:
for n in range(c, amount + 1):
dp[n] += dp[n - c]
return dp[-1]
def change_failed(sel... | the_stack_v2_python_sparse | src/lt_518.py | oxhead/CodingYourWay | train | 0 | |
211a0e89236e84b991bd07f5bb71ae1918370d0d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LocationConstraint()",
"from .location_constraint_item import LocationConstraintItem\nfrom .location_constraint_item import LocationConstraintItem\nfields: Dict[str, Callable[[Any], None]] = {'isRequired': lambda n: setattr(self, 'is_r... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LocationConstraint()
<|end_body_0|>
<|body_start_1|>
from .location_constraint_item import LocationConstraintItem
from .location_constraint_item import LocationConstraintItem
fie... | LocationConstraint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationConstraint:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraint:
"""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 obje... | stack_v2_sparse_classes_36k_train_026340 | 3,649 | 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: LocationConstraint",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `LocationConstraint` described below.
Class description:
Implement the LocationConstraint class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraint: Creates a new instance of the appropriate class based on disc... | Implement the Python class `LocationConstraint` described below.
Class description:
Implement the LocationConstraint class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraint: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LocationConstraint:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraint:
"""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 obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationConstraint:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraint:
"""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: Lo... | the_stack_v2_python_sparse | msgraph/generated/models/location_constraint.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b4d4c5c0f207a1f945ec7f2b1e9d7d8a8afbcc5d | [
"result = 0\nsorted_nums = sorted(nums)\ni = 0\nwhile i < len(sorted_nums):\n for j in range(i + 1, len(sorted_nums)):\n if sorted_nums[j] - sorted_nums[i] == k:\n result += 1\n break\n while i + 1 < len(sorted_nums) and sorted_nums[i] == sorted_nums[i + 1]:\n i += 1\n i... | <|body_start_0|>
result = 0
sorted_nums = sorted(nums)
i = 0
while i < len(sorted_nums):
for j in range(i + 1, len(sorted_nums)):
if sorted_nums[j] - sorted_nums[i] == k:
result += 1
break
while i + 1 < len(s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPairs_diff(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 0
... | stack_v2_sparse_classes_36k_train_026341 | 1,634 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs_diff",
"signature": "def findPairs_diff(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findPairs",
"signature": "def findPairs(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPairs_diff(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPairs_diff(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findPairs(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|>
cla... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def findPairs_diff(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findPairs(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPairs_diff(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
result = 0
sorted_nums = sorted(nums)
i = 0
while i < len(sorted_nums):
for j in range(i + 1, len(sorted_nums)):
if sorted_nums[j] - sorted_nums... | the_stack_v2_python_sparse | dbpointer_532.py | cainingning/leetcode | train | 1 | |
cdad07f5439fc88c0cf211d88719d8bc2954088d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CountryNamedLocation()",
"from .country_lookup_method_type import CountryLookupMethodType\nfrom .named_location import NamedLocation\nfrom .country_lookup_method_type import CountryLookupMethodType\nfrom .named_location import NamedLoc... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CountryNamedLocation()
<|end_body_0|>
<|body_start_1|>
from .country_lookup_method_type import CountryLookupMethodType
from .named_location import NamedLocation
from .country_loo... | CountryNamedLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""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 ... | stack_v2_sparse_classes_36k_train_026342 | 3,404 | 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: CountryNamedLocation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_006599 | Implement the Python class `CountryNamedLocation` described below.
Class description:
Implement the CountryNamedLocation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation: Creates a new instance of the appropriate class based o... | Implement the Python class `CountryNamedLocation` described below.
Class description:
Implement the CountryNamedLocation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountryNamedLocation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CountryNamedLocation:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/country_named_location.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fbc4c32688e15ca7b992f2096e5184ec6874175d | [
"if os.path.isdir(dir_path):\n return os.listdir(dir_path)\nelse:\n Exception_message = 'path {0} for directories search does not exist'.format(dir_path)\n raise Exception(Exception_message)",
"if os.path.isfile(file_path):\n try:\n with open(file_path, 'r+') as File_path:\n File_con... | <|body_start_0|>
if os.path.isdir(dir_path):
return os.listdir(dir_path)
else:
Exception_message = 'path {0} for directories search does not exist'.format(dir_path)
raise Exception(Exception_message)
<|end_body_0|>
<|body_start_1|>
if os.path.isfile(file_path... | wrapper class for python file functions | Py_Filling_Wrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Py_Filling_Wrapper:
"""wrapper class for python file functions"""
def get_dirs_names(self, dir_path):
"""get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories in the path"""
<|body_0|>
def read_file(self,... | stack_v2_sparse_classes_36k_train_026343 | 9,923 | no_license | [
{
"docstring": "get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories in the path",
"name": "get_dirs_names",
"signature": "def get_dirs_names(self, dir_path)"
},
{
"docstring": "read a file on a file path on disk Args :param fil... | 5 | stack_v2_sparse_classes_30k_train_020827 | Implement the Python class `Py_Filling_Wrapper` described below.
Class description:
wrapper class for python file functions
Method signatures and docstrings:
- def get_dirs_names(self, dir_path): get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories i... | Implement the Python class `Py_Filling_Wrapper` described below.
Class description:
wrapper class for python file functions
Method signatures and docstrings:
- def get_dirs_names(self, dir_path): get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories i... | eb8c55a4279b9c3f08e7f7af468731e7007450b0 | <|skeleton|>
class Py_Filling_Wrapper:
"""wrapper class for python file functions"""
def get_dirs_names(self, dir_path):
"""get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories in the path"""
<|body_0|>
def read_file(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Py_Filling_Wrapper:
"""wrapper class for python file functions"""
def get_dirs_names(self, dir_path):
"""get the directories names in a path Args :param dir_path: path to the dir Returns: :rtype list: a list of the dirctories in the path"""
if os.path.isdir(dir_path):
return o... | the_stack_v2_python_sparse | libs/utils/core_util_filling.py | Baronchibuikem/HealthInsuredbackend | train | 0 |
02e0e43e1231966465757a2095ded41fa8e41fc3 | [
"if event_id in [4624, 4634, 4647]:\n return self.getEventData(event, 'TargetLogonId')\nreturn self.getEventData(event, 'LogonID')",
"event_id = event.source.get('event_identifier')\nif event_id == 4624:\n account_name = self.getEventData(event, 'TargetUserName')\nelse:\n account_name = self.getEventData... | <|body_start_0|>
if event_id in [4624, 4634, 4647]:
return self.getEventData(event, 'TargetLogonId')
return self.getEventData(event, 'LogonID')
<|end_body_0|>
<|body_start_1|>
event_id = event.source.get('event_identifier')
if event_id == 4624:
account_name = sel... | Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event. | LogonSessionizerSketchPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
<|body_0|>
def getSes... | stack_v2_sparse_classes_36k_train_026344 | 7,451 | permissive | [
{
"docstring": "Retrieves the logon ID for an event.",
"name": "getLogonId",
"signature": "def getLogonId(self, event, event_id)"
},
{
"docstring": "Creates the session ID for an event.",
"name": "getSessionId",
"signature": "def getSessionId(self, event, session_num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014688 | Implement the Python class `LogonSessionizerSketchPlugin` described below.
Class description:
Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event.
Method signatures and docstrings:
- def getLogonId(self, event, event_id): Retrieves the log... | Implement the Python class `LogonSessionizerSketchPlugin` described below.
Class description:
Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event.
Method signatures and docstrings:
- def getLogonId(self, event, event_id): Retrieves the log... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
<|body_0|>
def getSes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogonSessionizerSketchPlugin:
"""Sessionizing sketch analyzer for logon sessions, where a session begins with a login event and ends with a logout or startup event."""
def getLogonId(self, event, event_id):
"""Retrieves the logon ID for an event."""
if event_id in [4624, 4634, 4647]:
... | the_stack_v2_python_sparse | timesketch/lib/analyzers/evtx_sessionizers.py | google/timesketch | train | 2,263 |
02cd8633c51b3ecd6cf4086d14c5984a7cdb34c5 | [
"processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid=ALI_APP_ID, app_notify_url=ALIPAY_NOTIFY_URL, app_private_key_path=PRIVATE_KEY_PATH, alipay_public_key_path=ALI_PUB_KEY_PATH, debug=DEBUG, return_url=ALIPAY_R... | <|body_start_0|>
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=ALI_APP_ID, app_notify_url=ALIPAY_NOTIFY_URL, app_private_key_path=PRIVATE_KEY_PATH, alipay_public_key_path=AL... | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""处理支付宝的notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processe... | stack_v2_sparse_classes_36k_train_026345 | 10,057 | no_license | [
{
"docstring": "处理支付宝的return_url返回 :param request: :return:",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "处理支付宝的notify_url :param request: :return:",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | null | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request, format=None): 处理支付宝的return_url返回 :param request: :return:
- def post(self, request, format=None): 处理支付宝的notify_url :param request: :return: | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request, format=None): 处理支付宝的return_url返回 :param request: :return:
- def post(self, request, format=None): 处理支付宝的notify_url :param request: :return:
<|skeleton... | 25a568c5203d05a00bce139d084da6d7622b9956 | <|skeleton|>
class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""处理支付宝的notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlipayView:
def get(self, request, format=None):
"""处理支付宝的return_url返回 :param request: :return:"""
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=ALI_APP_ID... | the_stack_v2_python_sparse | apps/trade/views.py | 846468230/store | train | 0 | |
cf817da16bfbc8051950ba689218f0b18b4f0a70 | [
"if type(X_init) is not np.ndarray or len(X_init.shape) != 2:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nt, one = X_init.shape\nif one != 1:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nif type(Y_init) is not np.ndarray or len(Y_init.shape) != 2:\n raise TypeEr... | <|body_start_0|>
if type(X_init) is not np.ndarray or len(X_init.shape) != 2:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
t, one = X_init.shape
if one != 1:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
if type(Y_init) is not ... | Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]: representing the outputs of t... | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_36k_train_026346 | 5,218 | no_license | [
{
"docstring": "Class constructor parameters: X_init [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y_init [numpy.ndarry of shape (t, 1)]: representing outputs of the black-box function for each input l [int or float]: length parameter for the k... | 3 | null | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]:... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
a458edf3cc29789a09326ebf0570b8c840d3321a | [
"AnyObject.setup_orientation(self)\nself.mtx = np.dot(self.rot_mtx.T, np.dot(self.mtx0, self.rot_mtx))\nself.rot_mtx_hc = gm.make_rotation_matrix_hc(self.rot_mtx)\nself.intersector.set_data(mtx=self.mtx)",
"self.centre = np.array(centre, dtype=np.float64)\nself.mtx_hc = self._get_matrix_hc()\nself.intersector.set... | <|body_start_0|>
AnyObject.setup_orientation(self)
self.mtx = np.dot(self.rot_mtx.T, np.dot(self.mtx0, self.rot_mtx))
self.rot_mtx_hc = gm.make_rotation_matrix_hc(self.rot_mtx)
self.intersector.set_data(mtx=self.mtx)
<|end_body_0|>
<|body_start_1|>
self.centre = np.array(centre,... | Base class of all geometrical objects to be sliced that are not compound (multi-object). | SingleObject | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation a... | stack_v2_sparse_classes_36k_train_026347 | 1,856 | permissive | [
{
"docstring": "Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation axis according to self.conf. Also update the intersector.",
"name": "setup_orientation",
"signature": "def setup_orientation(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_009932 | Implement the Python class `SingleObject` described below.
Class description:
Base class of all geometrical objects to be sliced that are not compound (multi-object).
Method signatures and docstrings:
- def setup_orientation(self): Sets rot_axis, the direction vector of rotation axis defining the orientation in space... | Implement the Python class `SingleObject` described below.
Class description:
Base class of all geometrical objects to be sliced that are not compound (multi-object).
Method signatures and docstrings:
- def setup_orientation(self): Sets rot_axis, the direction vector of rotation axis defining the orientation in space... | 8a8be511b545e1618a3140295a564b09001e095e | <|skeleton|>
class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation axis according... | the_stack_v2_python_sparse | gensei/single_object.py | ramosapf/gensei | train | 0 |
c0d6c096ee5257089331dfbfed998b8caeaad3f2 | [
"super().__init__(customer, bank, acnt, limit, balance)\nself._apr = apr\nself._calls = calls\nself._pay = pay",
"success = super().charge(price)\nif not success:\n self._set_balance(self._balance + 5)\nelif success and self._calls > 10:\n self._set_balance(self._balance + 1)\n self._calls += 1\nelse:\n ... | <|body_start_0|>
super().__init__(customer, bank, acnt, limit, balance)
self._apr = apr
self._calls = calls
self._pay = pay
<|end_body_0|>
<|body_start_1|>
success = super().charge(price)
if not success:
self._set_balance(self._balance + 5)
elif succe... | an extension to CreditCard class that compounds interests and fees | PredatoryCreditCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredatoryCreditCard:
"""an extension to CreditCard class that compounds interests and fees"""
def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0):
"""create a new predatory credit card instance apr: annual percentage rate (e.g., 0.0825 for 8.25% apr) calls... | stack_v2_sparse_classes_36k_train_026348 | 4,201 | no_license | [
{
"docstring": "create a new predatory credit card instance apr: annual percentage rate (e.g., 0.0825 for 8.25% apr) calls: how many calls (times) the customer has made to charge",
"name": "__init__",
"signature": "def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_008158 | Implement the Python class `PredatoryCreditCard` described below.
Class description:
an extension to CreditCard class that compounds interests and fees
Method signatures and docstrings:
- def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0): create a new predatory credit card instance apr: ... | Implement the Python class `PredatoryCreditCard` described below.
Class description:
an extension to CreditCard class that compounds interests and fees
Method signatures and docstrings:
- def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0): create a new predatory credit card instance apr: ... | f79b08021cebbfe0ff32abcc8e9dd56af32e4aad | <|skeleton|>
class PredatoryCreditCard:
"""an extension to CreditCard class that compounds interests and fees"""
def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0):
"""create a new predatory credit card instance apr: annual percentage rate (e.g., 0.0825 for 8.25% apr) calls... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredatoryCreditCard:
"""an extension to CreditCard class that compounds interests and fees"""
def __init__(self, customer, bank, acnt, limit, balance, apr=0, calls=0, pay=0):
"""create a new predatory credit card instance apr: annual percentage rate (e.g., 0.0825 for 8.25% apr) calls: how many ca... | the_stack_v2_python_sparse | exercises/ch02_object_oriented_programming/classes/CreditCard.py | rarezhang/data_structures_and_algorithms_in_python | train | 0 |
e35ec7abf6e7728b5d089da0380f237f9adfcb69 | [
"message.CopyFrom(union_message)\nuser = data.user.get(True)\nunion = data.union.get(True)\nmessage.user.user.user_id = user.id\nmessage.user.user.name = user.get_readable_name()\nmessage.user.user.headicon_id = user.icon_id\nmessage.user.left_attack_count = union.battle_attack_count_left\nmessage.user.refresh_atta... | <|body_start_0|>
message.CopyFrom(union_message)
user = data.user.get(True)
union = data.union.get(True)
message.user.user.user_id = user.id
message.user.user.name = user.get_readable_name()
message.user.user.headicon_id = user.icon_id
message.user.left_attack_cou... | 填充联盟战争信息,可能包括敌对联盟信息 | UnionBattlePatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnionBattlePatcher:
"""填充联盟战争信息,可能包括敌对联盟信息"""
def patch(self, message, union_message, data, now):
"""填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData] now[int]: 时间戳"""
<|body_0|>
def _patch_riv... | stack_v2_sparse_classes_36k_train_026349 | 8,396 | no_license | [
{
"docstring": "填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData] now[int]: 时间戳",
"name": "patch",
"signature": "def patch(self, message, union_message, data, now)"
},
{
"docstring": "填充敌对联盟的战争信息",
"name": "_patch_... | 5 | stack_v2_sparse_classes_30k_train_019852 | Implement the Python class `UnionBattlePatcher` described below.
Class description:
填充联盟战争信息,可能包括敌对联盟信息
Method signatures and docstrings:
- def patch(self, message, union_message, data, now): 填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData... | Implement the Python class `UnionBattlePatcher` described below.
Class description:
填充联盟战争信息,可能包括敌对联盟信息
Method signatures and docstrings:
- def patch(self, message, union_message, data, now): 填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData... | a16c872ba781855a8c891eff41e8e651cd565ebf | <|skeleton|>
class UnionBattlePatcher:
"""填充联盟战争信息,可能包括敌对联盟信息"""
def patch(self, message, union_message, data, now):
"""填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData] now[int]: 时间戳"""
<|body_0|>
def _patch_riv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnionBattlePatcher:
"""填充联盟战争信息,可能包括敌对联盟信息"""
def patch(self, message, union_message, data, now):
"""填充联盟战争信息 Args: message[protobuf UnionBattleInfo]: 需要打包的联盟信息 union_message[protobuf UnionBattleInfo]: 己方联盟返回的战斗信息 data[UserData] now[int]: 时间戳"""
message.CopyFrom(union_message)
use... | the_stack_v2_python_sparse | app/union_patcher.py | daxingyou/test-2 | train | 0 |
51633b24a1d87d27399ba133d3647e6e468df6cb | [
"self.body = {(0, 0)}\nself.food = food[::-1]\nself.snake = collections.deque([(0, 0)])\nself.score = 0\nself.dirs = dict(zip('ULRD', ((-1, 0), (0, -1), (0, 1), (1, 0))))\nself.C = width\nself.R = height",
"dr, dc = self.dirs[direction]\nr, c = self.snake[-1]\nnr, nc = (r + dr, c + dc)\nif nr < 0 or nr >= self.R ... | <|body_start_0|>
self.body = {(0, 0)}
self.food = food[::-1]
self.snake = collections.deque([(0, 0)])
self.score = 0
self.dirs = dict(zip('ULRD', ((-1, 0), (0, -1), (0, 1), (1, 0))))
self.C = width
self.R = height
<|end_body_0|>
<|body_start_1|>
dr, dc = ... | SnakeGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_026350 | 1,817 | permissive | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_005781 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | Python3/0353-Design-Snake-Game/soln-1.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
92b7e85c3726232f52a212ba133965134926bb68 | [
"try:\n from pynao import tddft_iter\nexcept ModuleNotFoundError as err:\n msg = 'running lrtddft with Siesta calculator requires pynao package'\n raise ModuleNotFoundError(msg) from err\nself.initialize = initialize\nself.lrtddft_params = kw\nself.tddft = None\nif 'iter_broadening' in self.lrtddft_params:... | <|body_start_0|>
try:
from pynao import tddft_iter
except ModuleNotFoundError as err:
msg = 'running lrtddft with Siesta calculator requires pynao package'
raise ModuleNotFoundError(msg) from err
self.initialize = initialize
self.lrtddft_params = kw
... | Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html) | SiestaLRTDDFT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiestaLRTDDFT:
"""Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)"""
def __init__(self, in... | stack_v2_sparse_classes_36k_train_026351 | 6,483 | no_license | [
{
"docstring": "Parameters ---------- initialize: bool To initialize the tddft calculations before calculating the polarizability Can be useful to calculate multiple frequency range without the need to recalculate the kernel kw: dictionary keywords for the tddft_iter function from PyNAO",
"name": "__init__"... | 3 | stack_v2_sparse_classes_30k_train_013894 | Implement the Python class `SiestaLRTDDFT` described below.
Class description:
Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/referen... | Implement the Python class `SiestaLRTDDFT` described below.
Class description:
Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/referen... | 6299b76c0504c5a7f7e94271aba9907a8ce77719 | <|skeleton|>
class SiestaLRTDDFT:
"""Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)"""
def __init__(self, in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SiestaLRTDDFT:
"""Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)"""
def __init__(self, initialize=Fals... | the_stack_v2_python_sparse | venv/Lib/site-packages/ase/calculators/siesta/siesta_lrtddft.py | Pratiksha1317/e-shop | train | 0 |
593f82349037a3161e93c124019e796d4e584fc4 | [
"self._task = task\nself._namespaces = task['learn']['namespaces'] or []\nself._quadratic = task['learn']['quadratic'] or []\nself._cubic = task['learn']['cubic'] or []\nself._separator = separator\nself._feature_separator = feature_separator\nself._join_ns = ns_join\nself._ns_join_sentinel = ns_join_sentinel\nself... | <|body_start_0|>
self._task = task
self._namespaces = task['learn']['namespaces'] or []
self._quadratic = task['learn']['quadratic'] or []
self._cubic = task['learn']['cubic'] or []
self._separator = separator
self._feature_separator = feature_separator
self._join... | FeatureEmitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureEmitter:
def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^'):
"""Args: task: config describing features"""
<|body_0|>
def __call__(self, example):
"""Args: example: line Returns: dict {"namespace1" : [f1, f2], "n... | stack_v2_sparse_classes_36k_train_026352 | 2,649 | no_license | [
{
"docstring": "Args: task: config describing features",
"name": "__init__",
"signature": "def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^')"
},
{
"docstring": "Args: example: line Returns: dict {\"namespace1\" : [f1, f2], \"namespace2,namespace3... | 2 | stack_v2_sparse_classes_30k_train_008025 | Implement the Python class `FeatureEmitter` described below.
Class description:
Implement the FeatureEmitter class.
Method signatures and docstrings:
- def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^'): Args: task: config describing features
- def __call__(self, examp... | Implement the Python class `FeatureEmitter` described below.
Class description:
Implement the FeatureEmitter class.
Method signatures and docstrings:
- def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^'): Args: task: config describing features
- def __call__(self, examp... | d0e6b6823347acc1fdfae04e90f9dfb56bd367ee | <|skeleton|>
class FeatureEmitter:
def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^'):
"""Args: task: config describing features"""
<|body_0|>
def __call__(self, example):
"""Args: example: line Returns: dict {"namespace1" : [f1, f2], "n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureEmitter:
def __init__(self, task, separator=',', feature_separator=' ', ns_join=False, ns_join_sentinel='^'):
"""Args: task: config describing features"""
self._task = task
self._namespaces = task['learn']['namespaces'] or []
self._quadratic = task['learn']['quadratic'] ... | the_stack_v2_python_sparse | outbrain/vw/feature.py | framr/challenge | train | 0 | |
3d24fd6755f714a54ea8a3c0add0fed752b9608c | [
"discount = 0.0\nif move_line.purchase_line_id.id:\n discount = move_line.purchase_line_id.discount\nelif move_line.sale_line_id.id:\n discount = move_line.sale_line_id.discount\nreturn discount",
"discount = 0.0\nif move_line.purchase_line_id.id:\n discount = move_line.purchase_line_id.discount2\nelif m... | <|body_start_0|>
discount = 0.0
if move_line.purchase_line_id.id:
discount = move_line.purchase_line_id.discount
elif move_line.sale_line_id.id:
discount = move_line.sale_line_id.discount
return discount
<|end_body_0|>
<|body_start_1|>
discount = 0.0
... | stock_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking:
def _get_discount_invoice(self, cr, uid, move_line):
"""Return the discount for the move line"""
<|body_0|>
def _get_discount2_invoice(self, cr, uid, move_line):
"""Return the discount for the move line"""
<|body_1|>
def _get_price_unit_in... | stack_v2_sparse_classes_36k_train_026353 | 3,397 | no_license | [
{
"docstring": "Return the discount for the move line",
"name": "_get_discount_invoice",
"signature": "def _get_discount_invoice(self, cr, uid, move_line)"
},
{
"docstring": "Return the discount for the move line",
"name": "_get_discount2_invoice",
"signature": "def _get_discount2_invoic... | 4 | stack_v2_sparse_classes_30k_train_006472 | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def _get_discount_invoice(self, cr, uid, move_line): Return the discount for the move line
- def _get_discount2_invoice(self, cr, uid, move_line): Return the discount f... | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def _get_discount_invoice(self, cr, uid, move_line): Return the discount for the move line
- def _get_discount2_invoice(self, cr, uid, move_line): Return the discount f... | 78fc164679b690bcf84866987266838de134bc2f | <|skeleton|>
class stock_picking:
def _get_discount_invoice(self, cr, uid, move_line):
"""Return the discount for the move line"""
<|body_0|>
def _get_discount2_invoice(self, cr, uid, move_line):
"""Return the discount for the move line"""
<|body_1|>
def _get_price_unit_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking:
def _get_discount_invoice(self, cr, uid, move_line):
"""Return the discount for the move line"""
discount = 0.0
if move_line.purchase_line_id.id:
discount = move_line.purchase_line_id.discount
elif move_line.sale_line_id.id:
discount = mov... | the_stack_v2_python_sparse | openforce_pricelist_discount_line/stock/stock_picking.py | alessandrocamilli/7-openforce-addons | train | 1 | |
97a5b26cca65adfb68b490538ea07b4e39e1cbd2 | [
"middle = len(nums) // 2\nif middle == 0:\n return nums[0]\nreturn min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))",
"if len(nums) == 2:\n return min(nums)\nmiddle = len(nums) // 2\nif middle == 0:\n return nums[0]\nif nums[middle] < nums[-1]:\n print('a', middle)\n return self.findMi... | <|body_start_0|>
middle = len(nums) // 2
if middle == 0:
return nums[0]
return min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))
<|end_body_0|>
<|body_start_1|>
if len(nums) == 2:
return min(nums)
middle = len(nums) // 2
if middle == 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_026354 | 1,068 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin3",
"signature": "def findMin3(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype:... | 2711bc08f15266bec4ca135e8e3e629df46713eb | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
middle = len(nums) // 2
if middle == 0:
return nums[0]
return min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))
def findMin3(self, nums):
""":type nums: List[int] :rt... | the_stack_v2_python_sparse | 0.算法/153_FindMinRotatedSortedArr.py | unlimitediw/CheckCode | train | 0 | |
4715db1c0ef4074b4fae27797cf2a6b3653fc989 | [
"if vis == 'public':\n return Visibility.PUBLIC\nelif vis == 'private':\n return Visibility.PRIVATE\nelif vis == 'protected':\n return Visibility.PROTECTED\nreturn Visibility.INVALID",
"if vis == Visibility.PUBLIC:\n return 'public'\nelif vis == Visibility.PRIVATE:\n return 'private'\nelif vis == V... | <|body_start_0|>
if vis == 'public':
return Visibility.PUBLIC
elif vis == 'private':
return Visibility.PRIVATE
elif vis == 'protected':
return Visibility.PROTECTED
return Visibility.INVALID
<|end_body_0|>
<|body_start_1|>
if vis == Visibility.... | Visibility | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Visibility:
def from_string(vis: str):
"""Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED otherwise Visibility.INVALID is returned"""
<|body_0|>
def to_string(vis):
"""C... | stack_v2_sparse_classes_36k_train_026355 | 1,550 | permissive | [
{
"docstring": "Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED otherwise Visibility.INVALID is returned",
"name": "from_string",
"signature": "def from_string(vis: str)"
},
{
"docstring": "Converts... | 2 | stack_v2_sparse_classes_30k_train_005379 | Implement the Python class `Visibility` described below.
Class description:
Implement the Visibility class.
Method signatures and docstrings:
- def from_string(vis: str): Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED o... | Implement the Python class `Visibility` described below.
Class description:
Implement the Visibility class.
Method signatures and docstrings:
- def from_string(vis: str): Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED o... | 416358301a274973ffc718c0cf7e48457119247f | <|skeleton|>
class Visibility:
def from_string(vis: str):
"""Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED otherwise Visibility.INVALID is returned"""
<|body_0|>
def to_string(vis):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Visibility:
def from_string(vis: str):
"""Converts a string to a Visibility type if 'public' -> Visibility.PUBLIC if 'private' -> Visibility.PRIVATE if 'protected' -> Visibility.PROTECTED otherwise Visibility.INVALID is returned"""
if vis == 'public':
return Visibility.PUBLIC
... | the_stack_v2_python_sparse | code/models/Visibility.py | mucsci-students/2020fa-420-CovidSurvivors | train | 11 | |
499d62fae37169d4f615d35183e14be80e9bdb85 | [
"if not settings.BSYNCR_SERVER_HOST:\n message = 'SEED instance is not configured to run bsyncr analysis. Please contact the server administrator.'\n self.fail(message, logger)\n raise AnalysisPipelineException(message)\nvalidation_errors = _validate_bsyncr_config(Analysis.objects.get(id=self._analysis_id)... | <|body_start_0|>
if not settings.BSYNCR_SERVER_HOST:
message = 'SEED instance is not configured to run bsyncr analysis. Please contact the server administrator.'
self.fail(message, logger)
raise AnalysisPipelineException(message)
validation_errors = _validate_bsyncr_c... | BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods. | BsyncrPipeline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BsyncrPipeline:
"""BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing bsyn... | stack_v2_sparse_classes_36k_train_026356 | 19,975 | permissive | [
{
"docstring": "Internal implementation for preparing bsyncr analysis",
"name": "_prepare_analysis",
"signature": "def _prepare_analysis(self, property_view_ids, start_analysis=False)"
},
{
"docstring": "Internal implementation for starting the bsyncr analysis",
"name": "_start_analysis",
... | 2 | stack_v2_sparse_classes_30k_train_010206 | Implement the Python class `BsyncrPipeline` described below.
Class description:
BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods.
Method signatures and docstrings:
- def _prepare_analysis(self, property_view_ids, start_an... | Implement the Python class `BsyncrPipeline` described below.
Class description:
BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods.
Method signatures and docstrings:
- def _prepare_analysis(self, property_view_ids, start_an... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class BsyncrPipeline:
"""BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing bsyn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BsyncrPipeline:
"""BsyncrPipeline is a class for preparing, running, and post processing the bsyncr analysis by implementing the AnalysisPipeline's abstract methods."""
def _prepare_analysis(self, property_view_ids, start_analysis=False):
"""Internal implementation for preparing bsyncr analysis""... | the_stack_v2_python_sparse | seed/analysis_pipelines/bsyncr.py | SEED-platform/seed | train | 108 |
380b284b9576b1501ec70f85c83acb0eaedfb50b | [
"user = self.model(is_staff=False, is_active=True, is_superuser=False, email=email, date_joined=datetime.utcnow().replace(tzinfo=timezone('UTC')))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.model(email=email, password=make_password(password), is_staff=True, is_active=True,... | <|body_start_0|>
user = self.model(is_staff=False, is_active=True, is_superuser=False, email=email, date_joined=datetime.utcnow().replace(tzinfo=timezone('UTC')))
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.model(... | Кастомный менеджер пользователя | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Кастомный менеджер пользователя"""
def create_user(self, email=None, password=None):
"""Создание и сохранение пользователя с указанным паролем"""
<|body_0|>
def create_superuser(self, email, password):
"""Создание и сохранение суперпользоват... | stack_v2_sparse_classes_36k_train_026357 | 2,940 | no_license | [
{
"docstring": "Создание и сохранение пользователя с указанным паролем",
"name": "create_user",
"signature": "def create_user(self, email=None, password=None)"
},
{
"docstring": "Создание и сохранение суперпользователя с указанным паролем",
"name": "create_superuser",
"signature": "def c... | 2 | stack_v2_sparse_classes_30k_train_015305 | Implement the Python class `CustomUserManager` described below.
Class description:
Кастомный менеджер пользователя
Method signatures and docstrings:
- def create_user(self, email=None, password=None): Создание и сохранение пользователя с указанным паролем
- def create_superuser(self, email, password): Создание и сохр... | Implement the Python class `CustomUserManager` described below.
Class description:
Кастомный менеджер пользователя
Method signatures and docstrings:
- def create_user(self, email=None, password=None): Создание и сохранение пользователя с указанным паролем
- def create_superuser(self, email, password): Создание и сохр... | 8b08e811fbe9fbd9c9d3cd45a0be44bdeea365f9 | <|skeleton|>
class CustomUserManager:
"""Кастомный менеджер пользователя"""
def create_user(self, email=None, password=None):
"""Создание и сохранение пользователя с указанным паролем"""
<|body_0|>
def create_superuser(self, email, password):
"""Создание и сохранение суперпользоват... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
"""Кастомный менеджер пользователя"""
def create_user(self, email=None, password=None):
"""Создание и сохранение пользователя с указанным паролем"""
user = self.model(is_staff=False, is_active=True, is_superuser=False, email=email, date_joined=datetime.utcnow().replace(... | the_stack_v2_python_sparse | peerocks/peerocks/apps/services/users/models.py | Sovushka-sever/peerocks | train | 0 |
3b1be573dd86c4f7d7ab714d67d36a4482c1077c | [
"self.logger = logging.getLogger('simple')\nself.cfg = cfg\nself.executor = executor\nself.tasklist = []\nfor key, anl_params in cfg['analysis'].items():\n try:\n self.tasklist.append(get_analysis_task(key, anl_params, cfg['storage']))\n except NameError as e:\n self.logger.error(f'Could not fin... | <|body_start_0|>
self.logger = logging.getLogger('simple')
self.cfg = cfg
self.executor = executor
self.tasklist = []
for key, anl_params in cfg['analysis'].items():
try:
self.tasklist.append(get_analysis_task(key, anl_params, cfg['storage']))
... | Defines an analysis task list. This class defines an task list that is executed in parallel on an executor. | tasklist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tasklist:
"""Defines an analysis task list. This class defines an task list that is executed in parallel on an executor."""
def __init__(self, executor, cfg):
"""Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instant... | stack_v2_sparse_classes_36k_train_026358 | 1,744 | no_license | [
{
"docstring": "Configures the analysis tasklist from a dictionary. For each key-value pair in \"cfg_analysis\", an analysis task is instantiated and appended to a list. On a call to execute, all tasks are launched with the current data. Args: executor (PEP-3148 style executor): Executor on which all analysis t... | 2 | stack_v2_sparse_classes_30k_test_000862 | Implement the Python class `tasklist` described below.
Class description:
Defines an analysis task list. This class defines an task list that is executed in parallel on an executor.
Method signatures and docstrings:
- def __init__(self, executor, cfg): Configures the analysis tasklist from a dictionary. For each key-... | Implement the Python class `tasklist` described below.
Class description:
Defines an analysis task list. This class defines an task list that is executed in parallel on an executor.
Method signatures and docstrings:
- def __init__(self, executor, cfg): Configures the analysis tasklist from a dictionary. For each key-... | 7ce63705e18c427f448c8d720c950a54add07966 | <|skeleton|>
class tasklist:
"""Defines an analysis task list. This class defines an task list that is executed in parallel on an executor."""
def __init__(self, executor, cfg):
"""Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instant... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tasklist:
"""Defines an analysis task list. This class defines an task list that is executed in parallel on an executor."""
def __init__(self, executor, cfg):
"""Configures the analysis tasklist from a dictionary. For each key-value pair in "cfg_analysis", an analysis task is instantiated and app... | the_stack_v2_python_sparse | delta/analysis/task_list.py | rkube/delta | train | 7 |
8ed818f03363a842d7789f30840b8c131cc62fe0 | [
"args = (name, 'address here', '987354312', 'test@test.com', card, '123', '2025-04-20')\nquery = self.generate_query('add_customer', args)\nres = self.execute_query(query)\nassert len(res) > 0, 'Customer not added correctly.'\nreturn res[0][0]",
"id = self._add_customer('Invoker', '1234123412341234')\nargs = (str... | <|body_start_0|>
args = (name, 'address here', '987354312', 'test@test.com', card, '123', '2025-04-20')
query = self.generate_query('add_customer', args)
res = self.execute_query(query)
assert len(res) > 0, 'Customer not added correctly.'
return res[0][0]
<|end_body_0|>
<|body_s... | EUpdateCreditCardTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EUpdateCreditCardTest:
def _add_customer(self, name: str, card: int) -> int:
"""Add a customer to the table"""
<|body_0|>
def test_update_success(self):
"""Update credit card for a person"""
<|body_1|>
def test_update_to_another_user_card_fail(self):
... | stack_v2_sparse_classes_36k_train_026359 | 3,222 | no_license | [
{
"docstring": "Add a customer to the table",
"name": "_add_customer",
"signature": "def _add_customer(self, name: str, card: int) -> int"
},
{
"docstring": "Update credit card for a person",
"name": "test_update_success",
"signature": "def test_update_success(self)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_013967 | Implement the Python class `EUpdateCreditCardTest` described below.
Class description:
Implement the EUpdateCreditCardTest class.
Method signatures and docstrings:
- def _add_customer(self, name: str, card: int) -> int: Add a customer to the table
- def test_update_success(self): Update credit card for a person
- def... | Implement the Python class `EUpdateCreditCardTest` described below.
Class description:
Implement the EUpdateCreditCardTest class.
Method signatures and docstrings:
- def _add_customer(self, name: str, card: int) -> int: Add a customer to the table
- def test_update_success(self): Update credit card for a person
- def... | 318693b3168b3cc99129e890d31fd1da01085b69 | <|skeleton|>
class EUpdateCreditCardTest:
def _add_customer(self, name: str, card: int) -> int:
"""Add a customer to the table"""
<|body_0|>
def test_update_success(self):
"""Update credit card for a person"""
<|body_1|>
def test_update_to_another_user_card_fail(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EUpdateCreditCardTest:
def _add_customer(self, name: str, card: int) -> int:
"""Add a customer to the table"""
args = (name, 'address here', '987354312', 'test@test.com', card, '123', '2025-04-20')
query = self.generate_query('add_customer', args)
res = self.execute_query(query... | the_stack_v2_python_sparse | SQL/testfiles/testclass/update_credit_card_test.py | Jh123x/cs2102-project | train | 2 | |
9ad57a251cdb7e76e23e230c304e9553e0906a8e | [
"self.k = k\nself.top_k_heap = nums\nheapify(self.top_k_heap)\nwhile len(self.top_k_heap) > k:\n heappop(self.top_k_heap)",
"if len(self.top_k_heap) < self.k:\n heappush(self.top_k_heap, val)\nelif val > self.top_k_heap[0]:\n heapreplace(self.top_k_heap, val)\nreturn self.top_k_heap[0]"
] | <|body_start_0|>
self.k = k
self.top_k_heap = nums
heapify(self.top_k_heap)
while len(self.top_k_heap) > k:
heappop(self.top_k_heap)
<|end_body_0|>
<|body_start_1|>
if len(self.top_k_heap) < self.k:
heappush(self.top_k_heap, val)
elif val > self.t... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.top_k_heap = nums
heapify(... | stack_v2_sparse_classes_36k_train_026360 | 776 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 0ceccdb262149f7916cb30fa5f3dae93aef9e9cd | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.top_k_heap = nums
heapify(self.top_k_heap)
while len(self.top_k_heap) > k:
heappop(self.top_k_heap)
def add(self, val):
""":type val: int :rtype: i... | the_stack_v2_python_sparse | easy/703_kth_largest_element_in_a_stream.py | esddse/leetcode | train | 0 | |
1451ccf5ff0951b9c8a222db4384a22ec0166fec | [
"super(FeedForwardModule, self).__init__()\nself.layer_norm = LayerNorm(input_feat)\nself.w_1 = torch.nn.Linear(input_feat, hidden_units, bias=bias)\nself.w_2 = torch.nn.Linear(hidden_units, input_feat, bias=bias)\nself.dropout1 = torch.nn.Dropout(dropout1)\nself.dropout2 = torch.nn.Dropout(dropout2)\nself.activati... | <|body_start_0|>
super(FeedForwardModule, self).__init__()
self.layer_norm = LayerNorm(input_feat)
self.w_1 = torch.nn.Linear(input_feat, hidden_units, bias=bias)
self.w_2 = torch.nn.Linear(hidden_units, input_feat, bias=bias)
self.dropout1 = torch.nn.Dropout(dropout1)
se... | Positionwise feed forward layer used in conformer | FeedForwardModule | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for ... | stack_v2_sparse_classes_36k_train_026361 | 9,087 | permissive | [
{
"docstring": "Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for layer1 dropout2: dropout value for layer2 activation_fn: Name of activation function bias: If linear layers should have bias",
"name": "__init__",
"signature": "def __init__(self, in... | 2 | stack_v2_sparse_classes_30k_train_016627 | Implement the Python class `FeedForwardModule` described below.
Class description:
Positionwise feed forward layer used in conformer
Method signatures and docstrings:
- def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True): Args: input_feat: Input feature dimension hidden_... | Implement the Python class `FeedForwardModule` described below.
Class description:
Positionwise feed forward layer used in conformer
Method signatures and docstrings:
- def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True): Args: input_feat: Input feature dimension hidden_... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedForwardModule:
"""Positionwise feed forward layer used in conformer"""
def __init__(self, input_feat, hidden_units, dropout1, dropout2, activation_fn='swish', bias=True):
"""Args: input_feat: Input feature dimension hidden_units: Hidden unit dimension dropout1: dropout value for layer1 dropou... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/conformer_layer.py | microsoft/unilm | train | 15,313 |
ee7e731ea65d9247b90afcf0268e36a468e7415e | [
"self.size = 0\nself.capacity = capacity\nself.node = dict()\nself.freq = collections.defaultdict(DLinkedList)\nself.minfreq = 0",
"freq = node.freq\nself.freq[freq].pop(node)\nif self.minfreq == freq and (not self.freq[freq]):\n self.minfreq += 1\nnode.freq += 1\nfreq = node.freq\nself.freq[freq].append(node)... | <|body_start_0|>
self.size = 0
self.capacity = capacity
self.node = dict()
self.freq = collections.defaultdict(DLinkedList)
self.minfreq = 0
<|end_body_0|>
<|body_start_1|>
freq = node.freq
self.freq[freq].pop(node)
if self.minfreq == freq and (not self.f... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
"""Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key. 2. Each frequency has a doubly linked list, store in `self.freq`, where key is the frequency, a... | stack_v2_sparse_classes_36k_train_026362 | 13,553 | no_license | [
{
"docstring": "Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key. 2. Each frequency has a doubly linked list, store in `self.freq`, where key is the frequency, and value is an object of `DLinkedList` 3. The min f... | 4 | stack_v2_sparse_classes_30k_train_007743 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key... | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key... | a4d8b54d3004866fd304e732707eef4401dfdb0a | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
"""Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key. 2. Each frequency has a doubly linked list, store in `self.freq`, where key is the frequency, a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
"""Three things to maintain: 1. a dict, named as `self.node`, for the reference of all nodes given key. That is, O(1) time to retrieve node given a key. 2. Each frequency has a doubly linked list, store in `self.freq`, where key is the frequency, and value is an... | the_stack_v2_python_sparse | LeetcodeNew/python/LC_460.py | derrickweiruluo/OptimizedLeetcode-1 | train | 0 | |
0274b01751006d51a8bc38374cbf35e82c018589 | [
"W = np.array([[1.0, 0.0], [0.0, -1.0]])\nself.W = normalization_all(W)\nself.a = a",
"z_layer = np.dot(self.W, x.T)\na_layer = sigmoid(z_layer)\nargmax = np.argmax(a_layer)\nreturn argmax",
"self.W[argmax] = self.a * (x - self.W[argmax])\nself.W[argmax] = normalization(self.W[argmax])\nself.a -= self.decay",
... | <|body_start_0|>
W = np.array([[1.0, 0.0], [0.0, -1.0]])
self.W = normalization_all(W)
self.a = a
<|end_body_0|>
<|body_start_1|>
z_layer = np.dot(self.W, x.T)
a_layer = sigmoid(z_layer)
argmax = np.argmax(a_layer)
return argmax
<|end_body_1|>
<|body_start_2|>
... | competitive_network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class competitive_network:
def __init__(self, x_dim, output_num, a):
"""类参数初始化"""
<|body_0|>
def forward_propagation(self, x):
"""前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针"""
<|body_1|>
def back_propagation(self, argmax, x):
... | stack_v2_sparse_classes_36k_train_026363 | 3,412 | no_license | [
{
"docstring": "类参数初始化",
"name": "__init__",
"signature": "def __init__(self, x_dim, output_num, a)"
},
{
"docstring": "前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针",
"name": "forward_propagation",
"signature": "def forward_propagation(self, x)"
},
{
"d... | 5 | stack_v2_sparse_classes_30k_train_006696 | Implement the Python class `competitive_network` described below.
Class description:
Implement the competitive_network class.
Method signatures and docstrings:
- def __init__(self, x_dim, output_num, a): 类参数初始化
- def forward_propagation(self, x): 前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针... | Implement the Python class `competitive_network` described below.
Class description:
Implement the competitive_network class.
Method signatures and docstrings:
- def __init__(self, x_dim, output_num, a): 类参数初始化
- def forward_propagation(self, x): 前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针... | 97e69c71af972f22c38b714b659a374d04c08b84 | <|skeleton|>
class competitive_network:
def __init__(self, x_dim, output_num, a):
"""类参数初始化"""
<|body_0|>
def forward_propagation(self, x):
"""前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针"""
<|body_1|>
def back_propagation(self, argmax, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class competitive_network:
def __init__(self, x_dim, output_num, a):
"""类参数初始化"""
W = np.array([[1.0, 0.0], [0.0, -1.0]])
self.W = normalization_all(W)
self.a = a
def forward_propagation(self, x):
"""前向传播 input:self(object):类参数 x(mat):一个训练样本 output:argmax(int):被激活的权重向量指针... | the_stack_v2_python_sparse | HW2/Letter_3.py | gavinatthu/ANN_course | train | 3 | |
f09174491a1962c1422dc7657e739981d44df171 | [
"pw = PrintWriter(socket.getOutputStream())\npw.print_('GET /' + URLEncoder.encode(data, 'UTF-8') + ' HTTP/1.0\\r\\n')\npw.print_('Accept: text/delim\\r\\n')\npw.print_('Host: ' + hostField + '\\r\\n')\npw.print_('Sender: GAMESERVER\\r\\n')\npw.print_('Receiver: ' + playerName + '\\r\\n')\npw.print_('\\r\\n')\npw.p... | <|body_start_0|>
pw = PrintWriter(socket.getOutputStream())
pw.print_('GET /' + URLEncoder.encode(data, 'UTF-8') + ' HTTP/1.0\r\n')
pw.print_('Accept: text/delim\r\n')
pw.print_('Host: ' + hostField + '\r\n')
pw.print_('Sender: GAMESERVER\r\n')
pw.print_('Receiver: ' + pl... | generated source for class HttpWriter | HttpWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpWriter:
"""generated source for class HttpWriter"""
def writeAsClientGET(cls, socket, hostField, data, playerName):
"""generated source for method writeAsClientGET"""
<|body_0|>
def writeAsClient(cls, socket, hostField, data, playerName):
"""generated source ... | stack_v2_sparse_classes_36k_train_026364 | 2,068 | permissive | [
{
"docstring": "generated source for method writeAsClientGET",
"name": "writeAsClientGET",
"signature": "def writeAsClientGET(cls, socket, hostField, data, playerName)"
},
{
"docstring": "generated source for method writeAsClient",
"name": "writeAsClient",
"signature": "def writeAsClient... | 3 | null | Implement the Python class `HttpWriter` described below.
Class description:
generated source for class HttpWriter
Method signatures and docstrings:
- def writeAsClientGET(cls, socket, hostField, data, playerName): generated source for method writeAsClientGET
- def writeAsClient(cls, socket, hostField, data, playerNam... | Implement the Python class `HttpWriter` described below.
Class description:
generated source for class HttpWriter
Method signatures and docstrings:
- def writeAsClientGET(cls, socket, hostField, data, playerName): generated source for method writeAsClientGET
- def writeAsClient(cls, socket, hostField, data, playerNam... | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | <|skeleton|>
class HttpWriter:
"""generated source for class HttpWriter"""
def writeAsClientGET(cls, socket, hostField, data, playerName):
"""generated source for method writeAsClientGET"""
<|body_0|>
def writeAsClient(cls, socket, hostField, data, playerName):
"""generated source ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpWriter:
"""generated source for class HttpWriter"""
def writeAsClientGET(cls, socket, hostField, data, playerName):
"""generated source for method writeAsClientGET"""
pw = PrintWriter(socket.getOutputStream())
pw.print_('GET /' + URLEncoder.encode(data, 'UTF-8') + ' HTTP/1.0\r... | the_stack_v2_python_sparse | ggpy/cruft/autocode/HttpWriter.py | hobson/ggpy | train | 1 |
73850ece6ea7fea6d0c3c338ed6e0f05a206f5ab | [
"for var, name in [(points, 'points'), (img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError('{} must be a list, but got {}'.format(name, type(var)))\nnum_augs = len(points)\nif num_augs != len(img_metas):\n raise ValueError('num of augmentations ({}) != num of image meta ({})'.f... | <|body_start_0|>
for var, name in [(points, 'points'), (img_metas, 'img_metas')]:
if not isinstance(var, list):
raise TypeError('{} must be a list, but got {}'.format(name, type(var)))
num_augs = len(points)
if num_augs != len(img_metas):
raise ValueError(... | Base class for detectors. | Base3DDetector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base3DDetector:
"""Base class for detectors."""
def forward_test(self, points, img_metas, img=None, **kwargs):
"""Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should have a shape NxC, which contains all points in the batch... | stack_v2_sparse_classes_36k_train_026365 | 5,565 | permissive | [
{
"docstring": "Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should have a shape NxC, which contains all points in the batch. img_metas (list[list[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates ... | 3 | stack_v2_sparse_classes_30k_train_017984 | Implement the Python class `Base3DDetector` described below.
Class description:
Base class for detectors.
Method signatures and docstrings:
- def forward_test(self, points, img_metas, img=None, **kwargs): Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should... | Implement the Python class `Base3DDetector` described below.
Class description:
Base class for detectors.
Method signatures and docstrings:
- def forward_test(self, points, img_metas, img=None, **kwargs): Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should... | f71858d02eb0fbd09860150ade67558d7984b1be | <|skeleton|>
class Base3DDetector:
"""Base class for detectors."""
def forward_test(self, points, img_metas, img=None, **kwargs):
"""Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should have a shape NxC, which contains all points in the batch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base3DDetector:
"""Base class for detectors."""
def forward_test(self, points, img_metas, img=None, **kwargs):
"""Args: points (list[torch.Tensor]): the outer list indicates test-time augmentations and inner torch.Tensor should have a shape NxC, which contains all points in the batch. img_metas (... | the_stack_v2_python_sparse | mmdet3d/models/detectors/base.py | HuangJunJie2017/BEVDet | train | 985 |
ab7379a4c9a97f98b95ce3f1338bd27c9e10e034 | [
"self.min_loss = float('inf')\nself.max_acc = -float('inf')\nself.min_delta = min_delta\nself.model_name = model_name\nself.path = str(os.path.join(model_dir, self.model_name + '.pth'))\nself.count = 0\nself.first_run = True\nself.best_model = None",
"print(f'Loss to beat: {self.min_loss - self.min_delta:.4f}')\n... | <|body_start_0|>
self.min_loss = float('inf')
self.max_acc = -float('inf')
self.min_delta = min_delta
self.model_name = model_name
self.path = str(os.path.join(model_dir, self.model_name + '.pth'))
self.count = 0
self.first_run = True
self.best_model = Non... | EarlyStopping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
def __init__(self, model_dir: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- `TODO` Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representin... | stack_v2_sparse_classes_36k_train_026366 | 29,312 | permissive | [
{
"docstring": "Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- `TODO` Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing the current fold. `min_delta` : `int`, `optional` Smallest number the given metric needs to change in... | 2 | stack_v2_sparse_classes_30k_train_019419 | Implement the Python class `EarlyStopping` described below.
Class description:
Implement the EarlyStopping class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, model_name: str, fold: int, min_delta=0): Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ----... | Implement the Python class `EarlyStopping` described below.
Class description:
Implement the EarlyStopping class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, model_name: str, fold: int, min_delta=0): Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ----... | d0ee019e5a573bf9b8e232786a9051cd54904487 | <|skeleton|>
class EarlyStopping:
def __init__(self, model_dir: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- `TODO` Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
def __init__(self, model_dir: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- `TODO` Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing the current ... | the_stack_v2_python_sparse | pytorch_vision_utils/TrainingUtilities.py | nclgbd/PyTorch-Utilities | train | 0 | |
af449fec888454e20774a2d7dea5b75688ebc09b | [
"if request.method == 'POST':\n validator = validate_list_of_ids(request.data, max_query=500)\n if validator['has_errors']:\n return Response({'message': validator['message'], 'data': request.data})\n result, qt = timeit(get_sequence_type, request.data['ids'], request.user)\n return self.formatte... | <|body_start_0|>
if request.method == 'POST':
validator = validate_list_of_ids(request.data, max_query=500)
if validator['has_errors']:
return Response({'message': validator['message'], 'data': request.data})
result, qt = timeit(get_sequence_type, request.data... | A simple ViewSet for listing or retrieving Samples. | MLSTViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
<|body_0|>
def blast_by_sample(self, request):
"""Given a list of sample IDs, return BLAST results."""... | stack_v2_sparse_classes_36k_train_026367 | 3,651 | no_license | [
{
"docstring": "Given a list of sample IDs, return MLST results.",
"name": "bulk_by_sample",
"signature": "def bulk_by_sample(self, request)"
},
{
"docstring": "Given a list of sample IDs, return BLAST results.",
"name": "blast_by_sample",
"signature": "def blast_by_sample(self, request)... | 3 | null | Implement the Python class `MLSTViewSet` described below.
Class description:
A simple ViewSet for listing or retrieving Samples.
Method signatures and docstrings:
- def bulk_by_sample(self, request): Given a list of sample IDs, return MLST results.
- def blast_by_sample(self, request): Given a list of sample IDs, ret... | Implement the Python class `MLSTViewSet` described below.
Class description:
A simple ViewSet for listing or retrieving Samples.
Method signatures and docstrings:
- def bulk_by_sample(self, request): Given a list of sample IDs, return MLST results.
- def blast_by_sample(self, request): Given a list of sample IDs, ret... | 2c35ee47e131a74642e60fae6f1cc23561d8b1a6 | <|skeleton|>
class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
<|body_0|>
def blast_by_sample(self, request):
"""Given a list of sample IDs, return BLAST results."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
if request.method == 'POST':
validator = validate_list_of_ids(request.data, max_query=500)
if validator[... | the_stack_v2_python_sparse | api/viewsets/sequence_types.py | staphopia/staphopia-web | train | 5 |
95f3531f3ae1ea29fd583b832f85de20d0c6523b | [
"fields = ['a.admin_id', 'a.name', 'account.account']\ncondition = '1 = 1'\nvalues = []\nif not self.util.is_empty('shop_id', params):\n condition += ' and a.shop_id = %s'\n values.append(params['shop_id'])\nif not self.util.is_empty('admin_id', params):\n condition += ' and a.admin_id = %s'\n values.ap... | <|body_start_0|>
fields = ['a.admin_id', 'a.name', 'account.account']
condition = '1 = 1'
values = []
if not self.util.is_empty('shop_id', params):
condition += ' and a.shop_id = %s'
values.append(params['shop_id'])
if not self.util.is_empty('admin_id', pa... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
async def query_one_and_account(self, params):
"""获取一条用户信息记录 :param params: :return: { id: admin_id: name: }"""
<|body_0|>
async def modify(self, params):
"""修改用户信息 @param params: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
field... | stack_v2_sparse_classes_36k_train_026368 | 1,846 | no_license | [
{
"docstring": "获取一条用户信息记录 :param params: :return: { id: admin_id: name: }",
"name": "query_one_and_account",
"signature": "async def query_one_and_account(self, params)"
},
{
"docstring": "修改用户信息 @param params: @return:",
"name": "modify",
"signature": "async def modify(self, params)"
... | 2 | stack_v2_sparse_classes_30k_train_003006 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- async def query_one_and_account(self, params): 获取一条用户信息记录 :param params: :return: { id: admin_id: name: }
- async def modify(self, params): 修改用户信息 @param params: @return: | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- async def query_one_and_account(self, params): 获取一条用户信息记录 :param params: :return: { id: admin_id: name: }
- async def modify(self, params): 修改用户信息 @param params: @return:
<|skeleton|>... | 9ab7dc87b678fc2a105cf883448cb7aada8494d2 | <|skeleton|>
class Model:
async def query_one_and_account(self, params):
"""获取一条用户信息记录 :param params: :return: { id: admin_id: name: }"""
<|body_0|>
async def modify(self, params):
"""修改用户信息 @param params: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
async def query_one_and_account(self, params):
"""获取一条用户信息记录 :param params: :return: { id: admin_id: name: }"""
fields = ['a.admin_id', 'a.name', 'account.account']
condition = '1 = 1'
values = []
if not self.util.is_empty('shop_id', params):
conditio... | the_stack_v2_python_sparse | src/module/v1/user/admin/model.py | yuiitsu/DSSP | train | 0 | |
6ed44dc4d3c3b37bb2488920b69b15840b97e6f1 | [
"assert isinstance(emb_io, NpEmbeddingIO)\nassert isinstance(rows_provider, NetworkSampleRowProvider)\nassert isinstance(save_embedding, bool)\nsuper(NetworksInputSerializerPipelineItem, self).__init__(rows_provider=rows_provider, samples_io=samples_io, save_labels_func=save_labels_func, balance_func=balance_func, ... | <|body_start_0|>
assert isinstance(emb_io, NpEmbeddingIO)
assert isinstance(rows_provider, NetworkSampleRowProvider)
assert isinstance(save_embedding, bool)
super(NetworksInputSerializerPipelineItem, self).__init__(rows_provider=rows_provider, samples_io=samples_io, save_labels_func=save... | NetworksInputSerializerPipelineItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworksInputSerializerPipelineItem:
def __init__(self, save_labels_func, rows_provider, samples_io, emb_io, balance_func, storage, save_embedding=True):
"""This pipeline item allows to perform a data preparation for neural network models. considering a list of the whole data_types with ... | stack_v2_sparse_classes_36k_train_026369 | 2,832 | permissive | [
{
"docstring": "This pipeline item allows to perform a data preparation for neural network models. considering a list of the whole data_types with the related pipelines, which are supported and required in a handler. It is necessary to know data_types in advance as it allows to create a complete vocabulary of i... | 2 | null | Implement the Python class `NetworksInputSerializerPipelineItem` described below.
Class description:
Implement the NetworksInputSerializerPipelineItem class.
Method signatures and docstrings:
- def __init__(self, save_labels_func, rows_provider, samples_io, emb_io, balance_func, storage, save_embedding=True): This pi... | Implement the Python class `NetworksInputSerializerPipelineItem` described below.
Class description:
Implement the NetworksInputSerializerPipelineItem class.
Method signatures and docstrings:
- def __init__(self, save_labels_func, rows_provider, samples_io, emb_io, balance_func, storage, save_embedding=True): This pi... | 1e1d354654f4f0a72090504663cc6d218f6aaf4a | <|skeleton|>
class NetworksInputSerializerPipelineItem:
def __init__(self, save_labels_func, rows_provider, samples_io, emb_io, balance_func, storage, save_embedding=True):
"""This pipeline item allows to perform a data preparation for neural network models. considering a list of the whole data_types with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworksInputSerializerPipelineItem:
def __init__(self, save_labels_func, rows_provider, samples_io, emb_io, balance_func, storage, save_embedding=True):
"""This pipeline item allows to perform a data preparation for neural network models. considering a list of the whole data_types with the related pi... | the_stack_v2_python_sparse | arekit/contrib/utils/pipelines/items/sampling/networks.py | nicolay-r/AREkit | train | 54 | |
a3db1d0459687568abe362c2bb57b18fb66ba13e | [
"with open_zip(path) as archive_file:\n for name in archive_file.namelist():\n if name.startswith(b'/') or name.startswith(b'..'):\n raise ValueError('Zip file contains unsafe path: {}'.format(name))\n if not filter_func or filter_func(name):\n archive_file.extract(name, outdi... | <|body_start_0|>
with open_zip(path) as archive_file:
for name in archive_file.namelist():
if name.startswith(b'/') or name.startswith(b'..'):
raise ValueError('Zip file contains unsafe path: {}'.format(name))
if not filter_func or filter_func(name... | An archiver that stores files in a zip file with optional compression. :API: public | ZipArchiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipArchiver:
"""An archiver that stores files in a zip file with optional compression. :API: public"""
def _extract(cls, path, outdir, filter_func=None, **kwargs):
"""Extract from a zip file, with an optional filter."""
<|body_0|>
def __init__(self, compression, extensio... | stack_v2_sparse_classes_36k_train_026370 | 7,148 | permissive | [
{
"docstring": "Extract from a zip file, with an optional filter.",
"name": "_extract",
"signature": "def _extract(cls, path, outdir, filter_func=None, **kwargs)"
},
{
"docstring": ":API: public",
"name": "__init__",
"signature": "def __init__(self, compression, extension)"
},
{
... | 3 | null | Implement the Python class `ZipArchiver` described below.
Class description:
An archiver that stores files in a zip file with optional compression. :API: public
Method signatures and docstrings:
- def _extract(cls, path, outdir, filter_func=None, **kwargs): Extract from a zip file, with an optional filter.
- def __in... | Implement the Python class `ZipArchiver` described below.
Class description:
An archiver that stores files in a zip file with optional compression. :API: public
Method signatures and docstrings:
- def _extract(cls, path, outdir, filter_func=None, **kwargs): Extract from a zip file, with an optional filter.
- def __in... | f0627cfa6ab05fc9a10686a499d1fb1d6ebdb68b | <|skeleton|>
class ZipArchiver:
"""An archiver that stores files in a zip file with optional compression. :API: public"""
def _extract(cls, path, outdir, filter_func=None, **kwargs):
"""Extract from a zip file, with an optional filter."""
<|body_0|>
def __init__(self, compression, extensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZipArchiver:
"""An archiver that stores files in a zip file with optional compression. :API: public"""
def _extract(cls, path, outdir, filter_func=None, **kwargs):
"""Extract from a zip file, with an optional filter."""
with open_zip(path) as archive_file:
for name in archive_... | the_stack_v2_python_sparse | src/python/pants/fs/archive.py | foursquare/pants | train | 1 |
7507b42bdf34b278f46632b261725fcead3e939f | [
"if not self.id:\n self.created = timezone.localtime(timezone.now())\nself.modified = timezone.localtime(timezone.now())\nself.calculate_date_next()\nreturn super(ScheduledOrder, self).save(*args, **kwargs)",
"now = timezone.localtime(timezone.now())\nif self.times > 0:\n self.date_next = now.date() + timez... | <|body_start_0|>
if not self.id:
self.created = timezone.localtime(timezone.now())
self.modified = timezone.localtime(timezone.now())
self.calculate_date_next()
return super(ScheduledOrder, self).save(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
now = timezone.lo... | ScheduledOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduledOrder:
def save(self, *args, **kwargs):
"""On save, update timestamps"""
<|body_0|>
def calculate_date_next(self):
"""if self.period == self.WEEKLY: self.days = 7 elif self.period == self.MONTHLY: self.days = 30"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_026371 | 13,890 | no_license | [
{
"docstring": "On save, update timestamps",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "if self.period == self.WEEKLY: self.days = 7 elif self.period == self.MONTHLY: self.days = 30",
"name": "calculate_date_next",
"signature": "def calculate_date_n... | 2 | stack_v2_sparse_classes_30k_train_004637 | Implement the Python class `ScheduledOrder` described below.
Class description:
Implement the ScheduledOrder class.
Method signatures and docstrings:
- def save(self, *args, **kwargs): On save, update timestamps
- def calculate_date_next(self): if self.period == self.WEEKLY: self.days = 7 elif self.period == self.MON... | Implement the Python class `ScheduledOrder` described below.
Class description:
Implement the ScheduledOrder class.
Method signatures and docstrings:
- def save(self, *args, **kwargs): On save, update timestamps
- def calculate_date_next(self): if self.period == self.WEEKLY: self.days = 7 elif self.period == self.MON... | c4f28a6080aa60b8248cfa4d6b36a083f24e7ccd | <|skeleton|>
class ScheduledOrder:
def save(self, *args, **kwargs):
"""On save, update timestamps"""
<|body_0|>
def calculate_date_next(self):
"""if self.period == self.WEEKLY: self.days = 7 elif self.period == self.MONTHLY: self.days = 30"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduledOrder:
def save(self, *args, **kwargs):
"""On save, update timestamps"""
if not self.id:
self.created = timezone.localtime(timezone.now())
self.modified = timezone.localtime(timezone.now())
self.calculate_date_next()
return super(ScheduledOrder, sel... | the_stack_v2_python_sparse | usuarios/models.py | InteractiveValley/djFarmApp | train | 0 | |
831041fa838f692f863f1f1f448cba013f1649c6 | [
"mol = Molecule()\nself.assertEqual(mol.to_smiles(), '')\nself.assertEqual(mol.to_inchi(), '')",
"mol = Molecule(smiles='[CH2-][N+]#N')\nwith self.assertRaisesRegex(ValueError, 'Unable to generate identifier type'):\n to_inchi(mol, backend='rdkit')\nmock_logging.error.assert_called_with('Unable to generate ide... | <|body_start_0|>
mol = Molecule()
self.assertEqual(mol.to_smiles(), '')
self.assertEqual(mol.to_inchi(), '')
<|end_body_0|>
<|body_start_1|>
mol = Molecule(smiles='[CH2-][N+]#N')
with self.assertRaisesRegex(ValueError, 'Unable to generate identifier type'):
to_inchi(... | TranslatorTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TranslatorTest:
def test_empty_molecule(self):
"""Test that we can safely return a blank identifier for an empty molecule."""
<|body_0|>
def test_failure_message(self, mock_logging):
"""Test that we log the molecule adjlist upon failure."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_026372 | 40,756 | permissive | [
{
"docstring": "Test that we can safely return a blank identifier for an empty molecule.",
"name": "test_empty_molecule",
"signature": "def test_empty_molecule(self)"
},
{
"docstring": "Test that we log the molecule adjlist upon failure.",
"name": "test_failure_message",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_020786 | Implement the Python class `TranslatorTest` described below.
Class description:
Implement the TranslatorTest class.
Method signatures and docstrings:
- def test_empty_molecule(self): Test that we can safely return a blank identifier for an empty molecule.
- def test_failure_message(self, mock_logging): Test that we l... | Implement the Python class `TranslatorTest` described below.
Class description:
Implement the TranslatorTest class.
Method signatures and docstrings:
- def test_empty_molecule(self): Test that we can safely return a blank identifier for an empty molecule.
- def test_failure_message(self, mock_logging): Test that we l... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TranslatorTest:
def test_empty_molecule(self):
"""Test that we can safely return a blank identifier for an empty molecule."""
<|body_0|>
def test_failure_message(self, mock_logging):
"""Test that we log the molecule adjlist upon failure."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TranslatorTest:
def test_empty_molecule(self):
"""Test that we can safely return a blank identifier for an empty molecule."""
mol = Molecule()
self.assertEqual(mol.to_smiles(), '')
self.assertEqual(mol.to_inchi(), '')
def test_failure_message(self, mock_logging):
"... | the_stack_v2_python_sparse | rmgpy/molecule/translatorTest.py | CanePan-cc/CanePanWorkshop | train | 2 | |
653172093b41a5424b4a2072c94755f2950719e6 | [
"self._config = config\nself._file_open_method = file_open_method\nself._archiver_data_source = archiver_data_source\nself._mkdir_for_file_fn = mkdir_for_file_fn\nself._make_file_readonly_fn = make_file_readonly\nself._filename = None\nself._first_line_written = False\nself._periodic_data_generator = None\nself._fi... | <|body_start_0|>
self._config = config
self._file_open_method = file_open_method
self._archiver_data_source = archiver_data_source
self._mkdir_for_file_fn = mkdir_for_file_fn
self._make_file_readonly_fn = make_file_readonly
self._filename = None
self._first_line_w... | Archive data file creator creates the log file based on the configuration. | ArchiveDataFileCreator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchiveDataFileCreator:
"""Archive data file creator creates the log file based on the configuration."""
def __init__(self, config, archiver_data_source, filename_template, file_open_method=open, mkdir_for_file_fn=mkdir_for_file, make_file_readonly=make_file_readonly_fn):
"""Construc... | stack_v2_sparse_classes_36k_train_026373 | 10,346 | permissive | [
{
"docstring": "Constructor Args: config(ArchiverAccess.archive_access_configuration.ArchiveAccessConfig): configuration for the archive data file to create archiver_data_source: archiver data source filename_template: template for the filename file_open_method: file like object that can be written to mkdir_for... | 6 | null | Implement the Python class `ArchiveDataFileCreator` described below.
Class description:
Archive data file creator creates the log file based on the configuration.
Method signatures and docstrings:
- def __init__(self, config, archiver_data_source, filename_template, file_open_method=open, mkdir_for_file_fn=mkdir_for_... | Implement the Python class `ArchiveDataFileCreator` described below.
Class description:
Archive data file creator creates the log file based on the configuration.
Method signatures and docstrings:
- def __init__(self, config, archiver_data_source, filename_template, file_open_method=open, mkdir_for_file_fn=mkdir_for_... | 2e605cbff1cfe071571a64bed61708d8c92dc204 | <|skeleton|>
class ArchiveDataFileCreator:
"""Archive data file creator creates the log file based on the configuration."""
def __init__(self, config, archiver_data_source, filename_template, file_open_method=open, mkdir_for_file_fn=mkdir_for_file, make_file_readonly=make_file_readonly_fn):
"""Construc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArchiveDataFileCreator:
"""Archive data file creator creates the log file based on the configuration."""
def __init__(self, config, archiver_data_source, filename_template, file_open_method=open, mkdir_for_file_fn=mkdir_for_file, make_file_readonly=make_file_readonly_fn):
"""Constructor Args: con... | the_stack_v2_python_sparse | ArchiverAccess/archive_data_file_creator.py | ISISComputingGroup/EPICS-inst_servers | train | 1 |
559dd9712697555b4f2cab101836dde80c9c6de8 | [
"dag = DAG()\ndag.Add(1, [2, 3, 4, 5])\ndag.Add(3, [4, 5])\ndag.Add(5, [])\ndag.Add(2, [3, 4, 5])\ndag.Add(4, [5])\nself.assertEqual(5, len(dag))\nl = list(dag)\nself.assertEqual(l, [5, 4, 3, 2, 1])",
"dag = DAG()\ndag.Add(1, [2, 3, 4, 5])\ndag.Add(3, [4, 5])\ndag.Add(5, [1])\ndag.Add(2, [3, 4, 5])\ndag.Add(4, [5... | <|body_start_0|>
dag = DAG()
dag.Add(1, [2, 3, 4, 5])
dag.Add(3, [4, 5])
dag.Add(5, [])
dag.Add(2, [3, 4, 5])
dag.Add(4, [5])
self.assertEqual(5, len(dag))
l = list(dag)
self.assertEqual(l, [5, 4, 3, 2, 1])
<|end_body_0|>
<|body_start_1|>
... | Test the DAG | TestDAG | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDAG:
"""Test the DAG"""
def testDAG(self):
"""Basic test - this should work"""
<|body_0|>
def testCircularDependency(self):
"""Circular dependency test, should fail"""
<|body_1|>
def testMissingDependency(self):
"""Missing dependency test... | stack_v2_sparse_classes_36k_train_026374 | 5,069 | no_license | [
{
"docstring": "Basic test - this should work",
"name": "testDAG",
"signature": "def testDAG(self)"
},
{
"docstring": "Circular dependency test, should fail",
"name": "testCircularDependency",
"signature": "def testCircularDependency(self)"
},
{
"docstring": "Missing dependency t... | 4 | stack_v2_sparse_classes_30k_train_006306 | Implement the Python class `TestDAG` described below.
Class description:
Test the DAG
Method signatures and docstrings:
- def testDAG(self): Basic test - this should work
- def testCircularDependency(self): Circular dependency test, should fail
- def testMissingDependency(self): Missing dependency test, should fail
-... | Implement the Python class `TestDAG` described below.
Class description:
Test the DAG
Method signatures and docstrings:
- def testDAG(self): Basic test - this should work
- def testCircularDependency(self): Circular dependency test, should fail
- def testMissingDependency(self): Missing dependency test, should fail
-... | c7389961bee3d8e5088c8c3c8c4bb7e273e4ec50 | <|skeleton|>
class TestDAG:
"""Test the DAG"""
def testDAG(self):
"""Basic test - this should work"""
<|body_0|>
def testCircularDependency(self):
"""Circular dependency test, should fail"""
<|body_1|>
def testMissingDependency(self):
"""Missing dependency test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDAG:
"""Test the DAG"""
def testDAG(self):
"""Basic test - this should work"""
dag = DAG()
dag.Add(1, [2, 3, 4, 5])
dag.Add(3, [4, 5])
dag.Add(5, [])
dag.Add(2, [3, 4, 5])
dag.Add(4, [5])
self.assertEqual(5, len(dag))
l = list(da... | the_stack_v2_python_sparse | csbuild/_utils/dag.py | SleepingCatGames/csbuild2 | train | 1 |
d590b4541ec2132e889949dfe59b7cff8a43d0eb | [
"self.__match_list = None\nreadline.set_history_length(50)\nhistory_file = os.path.join(os.environ['HOME'], '.dschistory')\nif os.path.exists(history_file):\n readline.read_history_file(history_file)\natexit.register(readline.write_history_file, history_file)\ntry:\n executer = service_manager.CommandExecuter... | <|body_start_0|>
self.__match_list = None
readline.set_history_length(50)
history_file = os.path.join(os.environ['HOME'], '.dschistory')
if os.path.exists(history_file):
readline.read_history_file(history_file)
atexit.register(readline.write_history_file, history_file... | This class can be use as a completer for the readline module. | ReadlineHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadlineHandler:
"""This class can be use as a completer for the readline module."""
def __init__(self):
"""Initializing the class by getting command list from the server."""
<|body_0|>
def completer(self, text, status):
"""The completer method. It returns the co... | stack_v2_sparse_classes_36k_train_026375 | 3,328 | no_license | [
{
"docstring": "Initializing the class by getting command list from the server.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "The completer method. It returns the commands that match the 'text'.",
"name": "completer",
"signature": "def completer(self, text, s... | 2 | null | Implement the Python class `ReadlineHandler` described below.
Class description:
This class can be use as a completer for the readline module.
Method signatures and docstrings:
- def __init__(self): Initializing the class by getting command list from the server.
- def completer(self, text, status): The completer meth... | Implement the Python class `ReadlineHandler` described below.
Class description:
This class can be use as a completer for the readline module.
Method signatures and docstrings:
- def __init__(self): Initializing the class by getting command list from the server.
- def completer(self, text, status): The completer meth... | a2ee333d2a4fe9821f3d24ee15d458f226ffcde5 | <|skeleton|>
class ReadlineHandler:
"""This class can be use as a completer for the readline module."""
def __init__(self):
"""Initializing the class by getting command list from the server."""
<|body_0|>
def completer(self, text, status):
"""The completer method. It returns the co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReadlineHandler:
"""This class can be use as a completer for the readline module."""
def __init__(self):
"""Initializing the class by getting command list from the server."""
self.__match_list = None
readline.set_history_length(50)
history_file = os.path.join(os.environ['H... | the_stack_v2_python_sparse | src/deltaconsole/readline_handler.py | hamed1361554/sportmagazine-server | train | 0 |
b720374348ac19f61edd1ad1c01900c3d1595e30 | [
"preO = [0]\npreE = [0]\nfor i, v in enumerate(nums):\n if i % 2 == 0:\n preO.append(preO[-1] + v)\n preE.append(preE[-1])\n else:\n preE.append(preE[-1] + v)\n preO.append(preO[-1])\nans = 0\nfor i in range(1, len(nums) + 1):\n sumO = preO[i - 1] - preO[0] + preE[-1] - preE[i]\... | <|body_start_0|>
preO = [0]
preE = [0]
for i, v in enumerate(nums):
if i % 2 == 0:
preO.append(preO[-1] + v)
preE.append(preE[-1])
else:
preE.append(preE[-1] + v)
preO.append(preO[-1])
ans = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def waysToMakeFairO1Space(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
preO = [0]
preE = [0]
... | stack_v2_sparse_classes_36k_train_026376 | 3,000 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "waysToMakeFair",
"signature": "def waysToMakeFair(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "waysToMakeFairO1Space",
"signature": "def waysToMakeFairO1Space(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToMakeFair(self, nums): :type nums: List[int] :rtype: int
- def waysToMakeFairO1Space(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToMakeFair(self, nums): :type nums: List[int] :rtype: int
- def waysToMakeFairO1Space(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
de... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def waysToMakeFairO1Space(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def waysToMakeFair(self, nums):
""":type nums: List[int] :rtype: int"""
preO = [0]
preE = [0]
for i, v in enumerate(nums):
if i % 2 == 0:
preO.append(preO[-1] + v)
preE.append(preE[-1])
else:
preE... | the_stack_v2_python_sparse | W/WaystoMakeaFairArray.py | bssrdf/pyleet | train | 2 | |
93293517ca2714bfcd07b740163164985db2eca7 | [
"while head is not None and head.val == val:\n head = head.next\nresult_head = head\nif result_head is None:\n return None\ncurrent_tmp_head = result_head\ncurrent_end_pointer = result_head.next\nwhile current_end_pointer is not None:\n while current_end_pointer.val == val:\n current_tmp_head.next =... | <|body_start_0|>
while head is not None and head.val == val:
head = head.next
result_head = head
if result_head is None:
return None
current_tmp_head = result_head
current_end_pointer = result_head.next
while current_end_pointer is not None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElements2(self, head, val):
"""双指针法 :type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_026377 | 1,997 | no_license | [
{
"docstring": "双指针法 :type head: ListNode :type val: int :rtype: ListNode",
"name": "removeElements2",
"signature": "def removeElements2(self, head, val)"
},
{
"docstring": ":type head: ListNode :type val: int :rtype: ListNode",
"name": "removeElements",
"signature": "def removeElements(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements2(self, head, val): 双指针法 :type head: ListNode :type val: int :rtype: ListNode
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements2(self, head, val): 双指针法 :type head: ListNode :type val: int :rtype: ListNode
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype:... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def removeElements2(self, head, val):
"""双指针法 :type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElements2(self, head, val):
"""双指针法 :type head: ListNode :type val: int :rtype: ListNode"""
while head is not None and head.val == val:
head = head.next
result_head = head
if result_head is None:
return None
current_tmp_head =... | the_stack_v2_python_sparse | 201-300/203. Remove Linked List Elements.py | SunnyMarkLiu/LeetCode | train | 1 | |
09576aa348035d8f1e17a44b150ffa3fe8b353f6 | [
"source = 'pipeline'\npipeline_resource_name = _LegacyExperimentService._get_experiment_or_pipeline_resource_name(name=pipeline, source=source, expected_schema=constants.SYSTEM_PIPELINE)\nreturn _LegacyExperimentService._query_runs_to_data_frame(context_id=pipeline, context_resource_name=pipeline_resource_name, sou... | <|body_start_0|>
source = 'pipeline'
pipeline_resource_name = _LegacyExperimentService._get_experiment_or_pipeline_resource_name(name=pipeline, source=source, expected_schema=constants.SYSTEM_PIPELINE)
return _LegacyExperimentService._query_runs_to_data_frame(context_id=pipeline, context_resourc... | Contains the exposed APIs to interact with the Managed Metadata Service. | _LegacyExperimentService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipelin... | stack_v2_sparse_classes_36k_train_026378 | 38,620 | permissive | [
{
"docstring": "Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipeline to filter results. Returns: Pandas Dataframe of Pipeline with metrics and parameters.",
"name": "get_pipeline_df",
"signature": "def get_pipeline_df(pipeline: str) ... | 4 | stack_v2_sparse_classes_30k_train_000198 | Implement the Python class `_LegacyExperimentService` described below.
Class description:
Contains the exposed APIs to interact with the Managed Metadata Service.
Method signatures and docstrings:
- def get_pipeline_df(pipeline: str) -> 'pd.DataFrame': Returns a Pandas DataFrame of the parameters and metrics associat... | Implement the Python class `_LegacyExperimentService` described below.
Class description:
Contains the exposed APIs to interact with the Managed Metadata Service.
Method signatures and docstrings:
- def get_pipeline_df(pipeline: str) -> 'pd.DataFrame': Returns a Pandas DataFrame of the parameters and metrics associat... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipelin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _LegacyExperimentService:
"""Contains the exposed APIs to interact with the Managed Metadata Service."""
def get_pipeline_df(pipeline: str) -> 'pd.DataFrame':
"""Returns a Pandas DataFrame of the parameters and metrics associated with one pipeline. Args: pipeline: Name of the Pipeline to filter r... | the_stack_v2_python_sparse | google/cloud/aiplatform/metadata/metadata.py | googleapis/python-aiplatform | train | 418 |
5395b86cb4f2e05b9b10d4e6b31f2bfac0a2df68 | [
"parser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the current project to be peered with the service')\nparser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', help='The service to connect to')\nparser.add_argument('--ranges', metavar='RA... | <|body_start_0|>
parser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the current project to be peered with the service')
parser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', help='The service to connect to')
parser.ad... | Update a private service connection to a service for a project network. | Update | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update a private service connection to a service for a project network."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this comman... | stack_v2_sparse_classes_36k_train_026379 | 4,097 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_020636 | Implement the Python class `Update` described below.
Class description:
Update a private service connection to a service for a project network.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to ad... | Implement the Python class `Update` described below.
Class description:
Update a private service connection to a service for a project network.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to ad... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Update:
"""Update a private service connection to a service for a project network."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this comman... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Update:
"""Update a private service connection to a service for a project network."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/services/vpc_peerings/update.py | bopopescu/socialliteapp | train | 0 |
1cbd42a9439d8a0ae321d906befc6e48993ecb12 | [
"im = cv2.imread('sample_images/exam_1.jpg')\nis_success, im_buf_arr = cv2.imencode('.jpg', im)\nbyte_im = im_buf_arr.tobytes()\nresult = conn.insert_values_test(age=20, gender=1, handedness=1, image=byte_im)\nself.assertEqual(type(result), int, 'Checking output type.')\nself.assertNotEqual(result, 0, 'Incorrect da... | <|body_start_0|>
im = cv2.imread('sample_images/exam_1.jpg')
is_success, im_buf_arr = cv2.imencode('.jpg', im)
byte_im = im_buf_arr.tobytes()
result = conn.insert_values_test(age=20, gender=1, handedness=1, image=byte_im)
self.assertEqual(type(result), int, 'Checking output type.... | Class to test mysql_connection. | MysqlConnectionTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MysqlConnectionTest:
"""Class to test mysql_connection."""
def test_insert_values_test(self):
"""Method to test insert_values_test method in mysql_connection."""
<|body_0|>
def test_insert_result_test_image(self):
"""Method to test insert_values_test_image method... | stack_v2_sparse_classes_36k_train_026380 | 5,327 | no_license | [
{
"docstring": "Method to test insert_values_test method in mysql_connection.",
"name": "test_insert_values_test",
"signature": "def test_insert_values_test(self)"
},
{
"docstring": "Method to test insert_values_test_image method in mysql_connection.",
"name": "test_insert_result_test_image"... | 4 | stack_v2_sparse_classes_30k_train_014495 | Implement the Python class `MysqlConnectionTest` described below.
Class description:
Class to test mysql_connection.
Method signatures and docstrings:
- def test_insert_values_test(self): Method to test insert_values_test method in mysql_connection.
- def test_insert_result_test_image(self): Method to test insert_val... | Implement the Python class `MysqlConnectionTest` described below.
Class description:
Class to test mysql_connection.
Method signatures and docstrings:
- def test_insert_values_test(self): Method to test insert_values_test method in mysql_connection.
- def test_insert_result_test_image(self): Method to test insert_val... | b4943fea82483c6910694d7c4c40e3715f65c3b5 | <|skeleton|>
class MysqlConnectionTest:
"""Class to test mysql_connection."""
def test_insert_values_test(self):
"""Method to test insert_values_test method in mysql_connection."""
<|body_0|>
def test_insert_result_test_image(self):
"""Method to test insert_values_test_image method... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MysqlConnectionTest:
"""Class to test mysql_connection."""
def test_insert_values_test(self):
"""Method to test insert_values_test method in mysql_connection."""
im = cv2.imread('sample_images/exam_1.jpg')
is_success, im_buf_arr = cv2.imencode('.jpg', im)
byte_im = im_buf_... | the_stack_v2_python_sparse | Backend/DetectPD/test_mysql_connection.py | RadhikaRanasinghe/Meraki | train | 5 |
a16b3f784f331609be375a5b80f404c52e5b19fd | [
"super().__init__()\nself.w = tf.get_variable('w', shape=(output_dim, head_dim, dep_dim), dtype=tf.float32)\nself.u = tf.get_variable('u', shape=(head_dim, output_dim), dtype=tf.float32)\nself.b = tf.get_variable('b', shape=(output_dim,), dtype=tf.float32, initializer=tf.initializers.zeros())\nself.use_dep_prior = ... | <|body_start_0|>
super().__init__()
self.w = tf.get_variable('w', shape=(output_dim, head_dim, dep_dim), dtype=tf.float32)
self.u = tf.get_variable('u', shape=(head_dim, output_dim), dtype=tf.float32)
self.b = tf.get_variable('b', shape=(output_dim,), dtype=tf.float32, initializer=tf.ini... | https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T_b, D_out] | BiLinear | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLinear:
"""https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T_b, D_out]"""
def __init__(self, h... | stack_v2_sparse_classes_36k_train_026381 | 9,477 | no_license | [
{
"docstring": "для coreference resolution в https://arxiv.org/pdf/1805.04893.pdf предлагается использовать prior на то, что у anaphora (head) есть antecedent (dep). такой реализации соответствует флаг use_dep_prior = False. :param head_dim: :param dep_dim: :param output_dim: :param use_dep_prior:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_006014 | Implement the Python class `BiLinear` described below.
Class description:
https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T... | Implement the Python class `BiLinear` described below.
Class description:
https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T... | 8be689c30eb62f573db2d6b66447db1787fd993a | <|skeleton|>
class BiLinear:
"""https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T_b, D_out]"""
def __init__(self, h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLinear:
"""https://arxiv.org/abs/1611.01734 https://arxiv.org/abs/1812.11275 Билинейная форма: x = a*w*b^T + a*u + b*v + bias, где tensor name shape a [N, T_a, D_a] b [N, T_b, D_b] w [D_out, D_a, D_b] u [D_a, D_out] v [D_b, D_out] bias [D_out] x [N, T_a, T_b, D_out]"""
def __init__(self, head_dim, dep_... | the_stack_v2_python_sparse | src/model/layers.py | ololo123321/nlu | train | 0 |
b8e6aaeb20d50a4216913d6592c3b612ef703f91 | [
"params = base.get_params(('event', 'from_date', 'to_date', 'on', 'unit', 'where', 'limit', 'type'), locals(), serialize_param)\nrequest = http.Request('GET', 'segmentation/', params)\nreturn (request, parsers.parse_json)",
"params = base.get_params(('event', 'from_date', 'to_date', 'on', 'buckets', 'unit', 'wher... | <|body_start_0|>
params = base.get_params(('event', 'from_date', 'to_date', 'on', 'unit', 'where', 'limit', 'type'), locals(), serialize_param)
request = http.Request('GET', 'segmentation/', params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_p... | Segmentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Segmentation:
def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None):
"""Fetch segmented and filtered data for an event."""
<|body_0|>
def numeric(self, event, from_date, to_date, on, buckets, unit=None, where=None, type=None):
... | stack_v2_sparse_classes_36k_train_026382 | 7,208 | permissive | [
{
"docstring": "Fetch segmented and filtered data for an event.",
"name": "get",
"signature": "def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None)"
},
{
"docstring": "Fetch segmented and filtered data for an event, sorted into numeric buckets.",
"n... | 5 | null | Implement the Python class `Segmentation` described below.
Class description:
Implement the Segmentation class.
Method signatures and docstrings:
- def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None): Fetch segmented and filtered data for an event.
- def numeric(self, event... | Implement the Python class `Segmentation` described below.
Class description:
Implement the Segmentation class.
Method signatures and docstrings:
- def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None): Fetch segmented and filtered data for an event.
- def numeric(self, event... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Segmentation:
def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None):
"""Fetch segmented and filtered data for an event."""
<|body_0|>
def numeric(self, event, from_date, to_date, on, buckets, unit=None, where=None, type=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Segmentation:
def get(self, event, from_date, to_date, on=None, unit=None, where=None, limit=None, type=None):
"""Fetch segmented and filtered data for an event."""
params = base.get_params(('event', 'from_date', 'to_date', 'on', 'unit', 'where', 'limit', 'type'), locals(), serialize_param)
... | the_stack_v2_python_sparse | libsaas/services/mixpanel/resources.py | piplcom/libsaas | train | 1 | |
07d568d5e587a2dd2964e0f5136993d1f8d8aa8d | [
"if xml_path == None:\n script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n xml_path = script_path + '/../robot_description/' + self.default_xml_file\nMjRobot.__init__(self, xml_path, object_names=object_names, render=render, g_comp=g_comp, tool_mass=tool_mass, tool_mass_... | <|body_start_0|>
if xml_path == None:
script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
xml_path = script_path + '/../robot_description/' + self.default_xml_file
MjRobot.__init__(self, xml_path, object_names=object_names, render=render, g_com... | The 7 DoF, 80V Barret WAM robot | MjWam7 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of ... | stack_v2_sparse_classes_36k_train_026383 | 22,293 | no_license | [
{
"docstring": "The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of the default xml description file object_names: states of the listed objects are included in recordings render: whether or not to render the simulation g_comp: whether or not ... | 2 | stack_v2_sparse_classes_30k_train_017087 | Implement the Python class `MjWam7` described below.
Class description:
The 7 DoF, 80V Barret WAM robot
Method signatures and docstrings:
- def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None): The 7 DoF, 80V Barret WAM robot xml_path: to change the robots en... | Implement the Python class `MjWam7` described below.
Class description:
The 7 DoF, 80V Barret WAM robot
Method signatures and docstrings:
- def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None): The 7 DoF, 80V Barret WAM robot xml_path: to change the robots en... | dd7c19b347e8167f9f5e1cd4ae32fbec194dc046 | <|skeleton|>
class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of the default x... | the_stack_v2_python_sparse | mujoco_robots/robots.py | kploeger/mujoco_robots | train | 0 |
cf29ac825c56c8789d445343e3aa4375d2413942 | [
"if not type(lst) is list:\n raise TypeError(f\"Parameter 'lst' is of type {type(lst)}. This parameter must be an instance of list.\")\nlist_of_str = all((isinstance(e, str) for e in lst))\nlist_of_dicts = all((isinstance(e, dict) for e in lst))\nif not list_of_dicts and (not list_of_str):\n raise TypeError(f... | <|body_start_0|>
if not type(lst) is list:
raise TypeError(f"Parameter 'lst' is of type {type(lst)}. This parameter must be an instance of list.")
list_of_str = all((isinstance(e, str) for e in lst))
list_of_dicts = all((isinstance(e, dict) for e in lst))
if not list_of_dicts... | A plugin that cleans up tweet content, buy removing links, hashtags and mentions | TweetCleanerPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetCleanerPlugin:
"""A plugin that cleans up tweet content, buy removing links, hashtags and mentions"""
def filter(self, lst, target_key=None):
"""Clears the text of tweet by removing urls, hashtags and mentions :param lst: texts contained in tweets :type lst: list of strings or l... | stack_v2_sparse_classes_36k_train_026384 | 2,838 | no_license | [
{
"docstring": "Clears the text of tweet by removing urls, hashtags and mentions :param lst: texts contained in tweets :type lst: list of strings or list of dictionaries :param target_key: a valid key that contains the tweet text. if the data parameter is a list of dictionaries, this parameter is mandatory. :ty... | 2 | stack_v2_sparse_classes_30k_train_012500 | Implement the Python class `TweetCleanerPlugin` described below.
Class description:
A plugin that cleans up tweet content, buy removing links, hashtags and mentions
Method signatures and docstrings:
- def filter(self, lst, target_key=None): Clears the text of tweet by removing urls, hashtags and mentions :param lst: ... | Implement the Python class `TweetCleanerPlugin` described below.
Class description:
A plugin that cleans up tweet content, buy removing links, hashtags and mentions
Method signatures and docstrings:
- def filter(self, lst, target_key=None): Clears the text of tweet by removing urls, hashtags and mentions :param lst: ... | 09186dc7edb3cd39d54969c33ddde6dd14c32ee6 | <|skeleton|>
class TweetCleanerPlugin:
"""A plugin that cleans up tweet content, buy removing links, hashtags and mentions"""
def filter(self, lst, target_key=None):
"""Clears the text of tweet by removing urls, hashtags and mentions :param lst: texts contained in tweets :type lst: list of strings or l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TweetCleanerPlugin:
"""A plugin that cleans up tweet content, buy removing links, hashtags and mentions"""
def filter(self, lst, target_key=None):
"""Clears the text of tweet by removing urls, hashtags and mentions :param lst: texts contained in tweets :type lst: list of strings or list of dictio... | the_stack_v2_python_sparse | plugins/tweet_cleaner_plugin.py | willsimoes/projeto-final | train | 0 |
51736f0c2ce8961e02cc2cf06318e6f0903acfad | [
"import apache_beam as beam\nfrom google.datalab.utils import LambdaJob\nfrom . import _preprocess\nif checkpoint is None:\n checkpoint = _util._DEFAULT_CHECKPOINT_GSURL\njob_id = 'preprocess-image-classification-' + datetime.datetime.now().strftime('%y%m%d-%H%M%S')\noptions = {'project': _util.default_project()... | <|body_start_0|>
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
job_id = 'preprocess-image-classification-' + datetime.datetime.now().strftime('%y%m%d-... | Class for local training, preprocessing and prediction. | Local | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Local:
"""Class for local training, preprocessing and prediction."""
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
<|body_0|>
def train(input_dir, batch_size, max_steps, output_dir, checkpoint):
"""Train model... | stack_v2_sparse_classes_36k_train_026385 | 3,681 | permissive | [
{
"docstring": "Preprocess data locally.",
"name": "preprocess",
"signature": "def preprocess(train_dataset, output_dir, eval_dataset, checkpoint)"
},
{
"docstring": "Train model locally.",
"name": "train",
"signature": "def train(input_dir, batch_size, max_steps, output_dir, checkpoint)... | 4 | stack_v2_sparse_classes_30k_train_019925 | Implement the Python class `Local` described below.
Class description:
Class for local training, preprocessing and prediction.
Method signatures and docstrings:
- def preprocess(train_dataset, output_dir, eval_dataset, checkpoint): Preprocess data locally.
- def train(input_dir, batch_size, max_steps, output_dir, che... | Implement the Python class `Local` described below.
Class description:
Class for local training, preprocessing and prediction.
Method signatures and docstrings:
- def preprocess(train_dataset, output_dir, eval_dataset, checkpoint): Preprocess data locally.
- def train(input_dir, batch_size, max_steps, output_dir, che... | 8bf007da3e43096aa3a3dca158fc56b286ba6f5c | <|skeleton|>
class Local:
"""Class for local training, preprocessing and prediction."""
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
<|body_0|>
def train(input_dir, batch_size, max_steps, output_dir, checkpoint):
"""Train model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Local:
"""Class for local training, preprocessing and prediction."""
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
... | the_stack_v2_python_sparse | solutionbox/image_classification/mltoolbox/image/classification/_local.py | googledatalab/pydatalab | train | 200 |
b7fc3864f6ec18eeba7ef69503ebe61464014d6c | [
"self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)\ntokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train)\nself.tokenizer_pt = tokenizer_pt\nself.tokenizer_en... | <|body_start_0|>
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
tokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train)
self.token... | Dataset class | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Dataset class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def tokenize_dataset(self, data):
"""Method that creates sub-word tokenizers for our dataset"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data_train = tfds.loa... | stack_v2_sparse_classes_36k_train_026386 | 1,165 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method that creates sub-word tokenizers for our dataset",
"name": "tokenize_dataset",
"signature": "def tokenize_dataset(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007289 | Implement the Python class `Dataset` described below.
Class description:
Dataset class
Method signatures and docstrings:
- def __init__(self): Constructor
- def tokenize_dataset(self, data): Method that creates sub-word tokenizers for our dataset | Implement the Python class `Dataset` described below.
Class description:
Dataset class
Method signatures and docstrings:
- def __init__(self): Constructor
- def tokenize_dataset(self, data): Method that creates sub-word tokenizers for our dataset
<|skeleton|>
class Dataset:
"""Dataset class"""
def __init__(... | 131be8fcf61aafb5a4ddc0b3853ba625560eb786 | <|skeleton|>
class Dataset:
"""Dataset class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def tokenize_dataset(self, data):
"""Method that creates sub-word tokenizers for our dataset"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Dataset class"""
def __init__(self):
"""Constructor"""
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
tokenizer_pt,... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/0-dataset.py | zahraaassaad/holbertonschool-machine_learning | train | 1 |
e0a26975717a4560f4f184dfd94261cb0577016c | [
"if len(names) == 0:\n self.leader = None\nelse:\n self.leader = Person(names[0])\n current_person = self.leader\n for name in names[1:]:\n current_person.next = Person(name)\n current_person = current_person.next",
"if not self.leader:\n raise ShortChainError\nelse:\n return self.... | <|body_start_0|>
if len(names) == 0:
self.leader = None
else:
self.leader = Person(names[0])
current_person = self.leader
for name in names[1:]:
current_person.next = Person(name)
current_person = current_person.next
<|end_b... | A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty. | PeopleChain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeopleChain:
"""A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty."""
def __init__(self, names: List[str]) -> None:
"""Create people linked together in the order provided in <names>. The leader of the chain is the... | stack_v2_sparse_classes_36k_train_026387 | 4,481 | no_license | [
{
"docstring": "Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>.",
"name": "__init__",
"signature": "def __init__(self, names: List[str]) -> None"
},
{
"docstring": "Return the name of the leader of the chain. Raise ShortChai... | 5 | stack_v2_sparse_classes_30k_test_000682 | Implement the Python class `PeopleChain` described below.
Class description:
A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.
Method signatures and docstrings:
- def __init__(self, names: List[str]) -> None: Create people linked together in the ... | Implement the Python class `PeopleChain` described below.
Class description:
A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.
Method signatures and docstrings:
- def __init__(self, names: List[str]) -> None: Create people linked together in the ... | b876b816ae2610ef18812371cd3ba7e92392b4f0 | <|skeleton|>
class PeopleChain:
"""A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty."""
def __init__(self, names: List[str]) -> None:
"""Create people linked together in the order provided in <names>. The leader of the chain is the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeopleChain:
"""A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty."""
def __init__(self, names: List[str]) -> None:
"""Create people linked together in the order provided in <names>. The leader of the chain is the first person... | the_stack_v2_python_sparse | mini-exercises/mini exercise 2/chain.py | ColeRichardson/CSC148 | train | 0 |
f79d13536f6781e9d62f88ef90a2a416eeb9cb48 | [
"if redirect_uri is None:\n redirect_uri = constants.DEFAULT_REDIRECT_URI\nif not redirect_uri.lower().startswith('http'):\n raise ValueError(\"'%s' is an invalid Redirect URI. Should be a valid http(s) URL.\" % redirect_uri)\nif session is None:\n session = _create_session()\nif not listen_addr:\n list... | <|body_start_0|>
if redirect_uri is None:
redirect_uri = constants.DEFAULT_REDIRECT_URI
if not redirect_uri.lower().startswith('http'):
raise ValueError("'%s' is an invalid Redirect URI. Should be a valid http(s) URL." % redirect_uri)
if session is None:
sessi... | TokenRequester | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenRequester:
def __init__(self, client_id, redirect_uri=None, session=None, listen_addr=None):
"""For completing the OAuth2 authorization flow. :param client_id: the client ID of the integration you created :type client_id: str :param redirect_uri: the URL to redirect to as part of th... | stack_v2_sparse_classes_36k_train_026388 | 2,480 | permissive | [
{
"docstring": "For completing the OAuth2 authorization flow. :param client_id: the client ID of the integration you created :type client_id: str :param redirect_uri: the URL to redirect to as part of the flow (this is http://localhost:33333 by default) :type redirect_uri: str :param session: optionally provide... | 2 | stack_v2_sparse_classes_30k_val_001126 | Implement the Python class `TokenRequester` described below.
Class description:
Implement the TokenRequester class.
Method signatures and docstrings:
- def __init__(self, client_id, redirect_uri=None, session=None, listen_addr=None): For completing the OAuth2 authorization flow. :param client_id: the client ID of the... | Implement the Python class `TokenRequester` described below.
Class description:
Implement the TokenRequester class.
Method signatures and docstrings:
- def __init__(self, client_id, redirect_uri=None, session=None, listen_addr=None): For completing the OAuth2 authorization flow. :param client_id: the client ID of the... | bece72d06b91de0e33afd2181c59b895dbe7ae1f | <|skeleton|>
class TokenRequester:
def __init__(self, client_id, redirect_uri=None, session=None, listen_addr=None):
"""For completing the OAuth2 authorization flow. :param client_id: the client ID of the integration you created :type client_id: str :param redirect_uri: the URL to redirect to as part of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenRequester:
def __init__(self, client_id, redirect_uri=None, session=None, listen_addr=None):
"""For completing the OAuth2 authorization flow. :param client_id: the client ID of the integration you created :type client_id: str :param redirect_uri: the URL to redirect to as part of the flow (this i... | the_stack_v2_python_sparse | basecampy3/token_requestor.py | phistrom/basecampy3 | train | 34 | |
18b2eb6df6638dfb3d04a9712927bd88d857471f | [
"try:\n cut = s.index(' ')\nexcept:\n return s[::-1]\nreturn s[:cut][::-1] + ' ' + self.reverseWords1(s[cut + 1:]) if s else ''",
"def driver(input):\n if not input:\n return ''\n elif len(input) == 1:\n return input[0][::-1]\n else:\n k = len(input) // 2\n return driver... | <|body_start_0|>
try:
cut = s.index(' ')
except:
return s[::-1]
return s[:cut][::-1] + ' ' + self.reverseWords1(s[cut + 1:]) if s else ''
<|end_body_0|>
<|body_start_1|>
def driver(input):
if not input:
return ''
elif len(i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords1(self, s):
"""OOM problem :type s: str :rtype: str"""
<|body_0|>
def reverseWords(self, s):
"""OOM problem :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
cut = s.index(' ')
... | stack_v2_sparse_classes_36k_train_026389 | 1,183 | no_license | [
{
"docstring": "OOM problem :type s: str :rtype: str",
"name": "reverseWords1",
"signature": "def reverseWords1(self, s)"
},
{
"docstring": "OOM problem :type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords1(self, s): OOM problem :type s: str :rtype: str
- def reverseWords(self, s): OOM problem :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords1(self, s): OOM problem :type s: str :rtype: str
- def reverseWords(self, s): OOM problem :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseW... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def reverseWords1(self, s):
"""OOM problem :type s: str :rtype: str"""
<|body_0|>
def reverseWords(self, s):
"""OOM problem :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords1(self, s):
"""OOM problem :type s: str :rtype: str"""
try:
cut = s.index(' ')
except:
return s[::-1]
return s[:cut][::-1] + ' ' + self.reverseWords1(s[cut + 1:]) if s else ''
def reverseWords(self, s):
"""OOM probl... | the_stack_v2_python_sparse | LeetCodes/Strings/ReverseWordsinaStringIII.py | chutianwen/LeetCodes | train | 0 | |
aecdd3ee5d1147336a8ade502f0d04ea2e1367bf | [
"assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nif rup.hypo_depth < 10:\n C = self.COEFFS_SHALLOW[imt]\nelse:\n C = self.COEFFS_DEEP[imt]\nmean = self._compute_mean(C, rup.mag, dists.rrup)\nstddevs = self._get_stddevs(C, stddev_types, dists.rrup.shape[0... | <|body_start_0|>
assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))
if rup.hypo_depth < 10:
C = self.COEFFS_SHALLOW[imt]
else:
C = self.COEFFS_DEEP[imt]
mean = self._compute_mean(C, rup.mag, dists.rrup)
s... | Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document available at: https://www.ga.gov.au/products/servlet/controller?event=GEOCA... | Allen2012 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Allen2012:
"""Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document available at: https://www.ga.gov.au/pr... | stack_v2_sparse_classes_36k_train_026390 | 11,196 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Compute mean value ... | 3 | null | Implement the Python class `Allen2012` described below.
Class description:
Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document... | Implement the Python class `Allen2012` described below.
Class description:
Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Allen2012:
"""Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document available at: https://www.ga.gov.au/pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Allen2012:
"""Implements GMPE developed by T. Allen and published as "Stochastic ground- motion prediction equations for southeastern Australian earthquakes using updated source and attenuation parameters", 2012, Geoscience Australia Record 2012/69. Document available at: https://www.ga.gov.au/products/servle... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/allen_2012.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
6dbc9413fe3b87e148c3443fc6e6a83fa98f9395 | [
"solvent_formula = cls._solvents.get(solvent.lower(), solvent.upper())\nif solvent_formula not in cls._solvents.values():\n raise SpecificationError(f'The solvent {solvent} is not supported please chose from the following solvents or formulas {cls._solvents.items()}')\nreturn solvent_formula",
"units = kwargs.... | <|body_start_0|>
solvent_formula = cls._solvents.get(solvent.lower(), solvent.upper())
if solvent_formula not in cls._solvents.values():
raise SpecificationError(f'The solvent {solvent} is not supported please chose from the following solvents or formulas {cls._solvents.items()}')
re... | SolventPsi4 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolventPsi4:
def _check_solvent(cls, solvent: str) -> str:
"""Make sure that a valid solvent from the list of supported values is passed."""
<|body_0|>
def __init__(self, **kwargs):
"""Fully validate the model making sure options are compatible and convert any defaul... | stack_v2_sparse_classes_36k_train_026391 | 6,833 | permissive | [
{
"docstring": "Make sure that a valid solvent from the list of supported values is passed.",
"name": "_check_solvent",
"signature": "def _check_solvent(cls, solvent: str) -> str"
},
{
"docstring": "Fully validate the model making sure options are compatible and convert any defaults to the give ... | 3 | null | Implement the Python class `SolventPsi4` described below.
Class description:
Implement the SolventPsi4 class.
Method signatures and docstrings:
- def _check_solvent(cls, solvent: str) -> str: Make sure that a valid solvent from the list of supported values is passed.
- def __init__(self, **kwargs): Fully validate the... | Implement the Python class `SolventPsi4` described below.
Class description:
Implement the SolventPsi4 class.
Method signatures and docstrings:
- def _check_solvent(cls, solvent: str) -> str: Make sure that a valid solvent from the list of supported values is passed.
- def __init__(self, **kwargs): Fully validate the... | bdccc28d1ad8c0fb4eeb01467bfe8365396c411c | <|skeleton|>
class SolventPsi4:
def _check_solvent(cls, solvent: str) -> str:
"""Make sure that a valid solvent from the list of supported values is passed."""
<|body_0|>
def __init__(self, **kwargs):
"""Fully validate the model making sure options are compatible and convert any defaul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolventPsi4:
def _check_solvent(cls, solvent: str) -> str:
"""Make sure that a valid solvent from the list of supported values is passed."""
solvent_formula = cls._solvents.get(solvent.lower(), solvent.upper())
if solvent_formula not in cls._solvents.values():
raise Specifi... | the_stack_v2_python_sparse | qubekit/charges/solvent_settings/psi.py | qubekit/QUBEKit | train | 89 | |
b6c6dbde6a0d1122f154b698d4be4fb36f2f5167 | [
"if not matrix:\n return True\nn = len(matrix[0])\nreturn self.binary_tree_search(matrix, 0, n - 1, target)",
"m = len(matrix)\nn = len(matrix[0])\nif 0 <= top < m and 0 <= right < n:\n if matrix[top][right] == target:\n return True\n elif matrix[top][right] > target:\n return self.binary_t... | <|body_start_0|>
if not matrix:
return True
n = len(matrix[0])
return self.binary_tree_search(matrix, 0, n - 1, target)
<|end_body_0|>
<|body_start_1|>
m = len(matrix)
n = len(matrix[0])
if 0 <= top < m and 0 <= right < n:
if matrix[top][right] ==... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNumberIn2DArray(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def binary_tree_search(self, matrix, top, right, target):
""":param matrix: :param top: :param right: :param target: :return:"""
... | stack_v2_sparse_classes_36k_train_026392 | 1,270 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "findNumberIn2DArray",
"signature": "def findNumberIn2DArray(self, matrix, target)"
},
{
"docstring": ":param matrix: :param top: :param right: :param target: :return:",
"name": "binary_tree_search",
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberIn2DArray(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def binary_tree_search(self, matrix, top, right, target): :param mat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberIn2DArray(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def binary_tree_search(self, matrix, top, right, target): :param mat... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|skeleton|>
class Solution:
def findNumberIn2DArray(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def binary_tree_search(self, matrix, top, right, target):
""":param matrix: :param top: :param right: :param target: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findNumberIn2DArray(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return True
n = len(matrix[0])
return self.binary_tree_search(matrix, 0, n - 1, target)
def binary_tree_search(self, matri... | the_stack_v2_python_sparse | leetcode/offer/code/4.py | skyxyz-lang/CS_Note | train | 0 | |
d8ce0555578fe7bfe276f8af5f251bb31db88080 | [
"assert isinstance(percentage, int)\nif 0 < percentage < 100:\n train_path = settings.GENERATED_FEATS_FILENAME_TEMPLATE.format('{}%_train'.format(percentage))\n test_path = settings.GENERATED_FEATS_FILENAME_TEMPLATE.format('{}%_test'.format(percentage))\nelse:\n train_path = settings.GENERATED_FEATS_FILENA... | <|body_start_0|>
assert isinstance(percentage, int)
if 0 < percentage < 100:
train_path = settings.GENERATED_FEATS_FILENAME_TEMPLATE.format('{}%_train'.format(percentage))
test_path = settings.GENERATED_FEATS_FILENAME_TEMPLATE.format('{}%_test'.format(percentage))
else:
... | Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().create_subsets(percentage=20, verbose=True) train_feats, train_labels, test_fea... | FeatsHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatsHandler:
"""Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().create_subsets(percentage=20, verbose=T... | stack_v2_sparse_classes_36k_train_026393 | 8,522 | permissive | [
{
"docstring": "Loads the training and testing datasets",
"name": "__init__",
"signature": "def __init__(self, percentage=0, verbose=False)"
},
{
"docstring": "Creates subsets of the spatial pyramid features training dataset considering the provided percentage as the percentage covered by the su... | 2 | stack_v2_sparse_classes_30k_train_001771 | Implement the Python class `FeatsHandler` described below.
Class description:
Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().... | Implement the Python class `FeatsHandler` described below.
Class description:
Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().... | 4e8d4b754a60daa410a45792ba2093864bc6f2b3 | <|skeleton|>
class FeatsHandler:
"""Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().create_subsets(percentage=20, verbose=T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatsHandler:
"""Handler for generated spatial pyramid features The format of the arrays are [features, samples] Usage: train_feats, train_labels, test_feats, test_labels = FeatsHandler()() # create a subdataset using a percentage and load it FeatsHandler().create_subsets(percentage=20, verbose=True) train_fe... | the_stack_v2_python_sparse | spfs/utils/datasets/handlers.py | QNZhang/spatial-pyramid-features | train | 0 |
ad1f07762309db0a5e75227f4add7fdf161cbddf | [
"super(DictTranslator, self).__init__(datatype)\nself.map_guesser = map_guesser\nself.parse_guesser = parse_guesser",
"res = {}\nfor key, val in value.items():\n guessed_dt = self.map_guesser.guess(key, val)\n res[key] = guessed_dt.translator.to_dynamodb(val)\nreturn res",
"res = {}\nfor key, nested_dict ... | <|body_start_0|>
super(DictTranslator, self).__init__(datatype)
self.map_guesser = map_guesser
self.parse_guesser = parse_guesser
<|end_body_0|>
<|body_start_1|>
res = {}
for key, val in value.items():
guessed_dt = self.map_guesser.guess(key, val)
res[key... | A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` to decide how to resolve and reconstruct each key/value pair. Attributes: datatype... | DictTranslator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictTranslator:
"""A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` to decide how to resolve and reconstruct... | stack_v2_sparse_classes_36k_train_026394 | 3,163 | permissive | [
{
"docstring": "constructor for the DictTranslator Parameters: datatype: a DynamoDataType object the translator is used with map_guesser: a MapGuesser object, typically associated with the datatype parse_guesser: A ParseGuesser object, typically associated with the datatype",
"name": "__init__",
"signat... | 3 | stack_v2_sparse_classes_30k_train_017672 | Implement the Python class `DictTranslator` described below.
Class description:
A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` t... | Implement the Python class `DictTranslator` described below.
Class description:
A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` t... | e97c0baa42c4bdfb10bbe3b4b859873e3d50aa3a | <|skeleton|>
class DictTranslator:
"""A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` to decide how to resolve and reconstruct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictTranslator:
"""A Translator class for Dicts This translator is typically used with the ``Map`` datatype. DynamoDB requires all nested values to also match their DynamoDB format when making requests. This class uses a ``MapGuesser`` and ``ParseGuesser`` to decide how to resolve and reconstruct each key/val... | the_stack_v2_python_sparse | cerami/datatype/translator/dict_translator.py | gummybuns/cerami | train | 0 |
96a055279e043c2c22f6d9762cd74471e4bfa8c4 | [
"self.L = L\nself.W = W\nself.obstacles = obstacles\nself.goal_x, self.goal_y = goal\nself.action_to_coords = {0: (1, 0), 1: (0, 1), 2: (-1, 0), 3: (0, -1)}",
"if not 0 <= x <= self.L - 1 or not 0 <= y <= self.W - 1:\n raise ValueError(\"That's not a valid position!\")\nif not 0 <= action <= 3:\n raise Valu... | <|body_start_0|>
self.L = L
self.W = W
self.obstacles = obstacles
self.goal_x, self.goal_y = goal
self.action_to_coords = {0: (1, 0), 1: (0, 1), 2: (-1, 0), 3: (0, -1)}
<|end_body_0|>
<|body_start_1|>
if not 0 <= x <= self.L - 1 or not 0 <= y <= self.W - 1:
r... | 2D grid world enviornment, example 8.3 in the book. | GridWorld | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridWorld:
"""2D grid world enviornment, example 8.3 in the book."""
def __init__(self, L, W, obstacles, goal):
"""Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obstacles: set[tuple] A set of tuples (x,y) denoting obstacle... | stack_v2_sparse_classes_36k_train_026395 | 9,439 | permissive | [
{
"docstring": "Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obstacles: set[tuple] A set of tuples (x,y) denoting obstacles at the location (x,y) on the grid. @type goal: tuple[int] A tuple (x, y) denoting the goal position on the grid.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_006744 | Implement the Python class `GridWorld` described below.
Class description:
2D grid world enviornment, example 8.3 in the book.
Method signatures and docstrings:
- def __init__(self, L, W, obstacles, goal): Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obst... | Implement the Python class `GridWorld` described below.
Class description:
2D grid world enviornment, example 8.3 in the book.
Method signatures and docstrings:
- def __init__(self, L, W, obstacles, goal): Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obst... | 127d3fe10fe5774be7f8db3b00f6737f3eed363d | <|skeleton|>
class GridWorld:
"""2D grid world enviornment, example 8.3 in the book."""
def __init__(self, L, W, obstacles, goal):
"""Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obstacles: set[tuple] A set of tuples (x,y) denoting obstacle... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridWorld:
"""2D grid world enviornment, example 8.3 in the book."""
def __init__(self, L, W, obstacles, goal):
"""Initializes the enviornment. @type L: int The length of the grid. @type W: int The width of the grid. @type obstacles: set[tuple] A set of tuples (x,y) denoting obstacles at the loca... | the_stack_v2_python_sparse | Ch8/dynaQ.py | lolcharles2/Reinforcement_learning_book_implementations | train | 0 |
1cdcace812271b3320d22458d63fafd1788ad9b9 | [
"nums1.sort()\nnums2.sort()\nlen_1 = len(nums1)\nlen_2 = len(nums2)\ni, j = (0, 0)\nres = []\nwhile i < len_1 and j < len_2:\n if nums1[i] < nums2[j]:\n i += 1\n elif nums2[j] < nums1[i]:\n j += 1\n elif nums2[j] == nums1[i]:\n res.append(nums1[i])\n i += 1\n j += 1\nretu... | <|body_start_0|>
nums1.sort()
nums2.sort()
len_1 = len(nums1)
len_2 = len(nums2)
i, j = (0, 0)
res = []
while i < len_1 and j < len_2:
if nums1[i] < nums2[j]:
i += 1
elif nums2[j] < nums1[i]:
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_026396 | 1,157 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(se... | 2 | stack_v2_sparse_classes_30k_train_007938 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[i... | 2ecaeed38178819480388b5742bc2ea12009ae16 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
nums1.sort()
nums2.sort()
len_1 = len(nums1)
len_2 = len(nums2)
i, j = (0, 0)
res = []
while i < len_1 and j < len_2:
i... | the_stack_v2_python_sparse | 350.intersection-of-two-arrays-ii.py | LouisYLWang/leetcode_python | train | 0 | |
12f8a1f84095c51a4ecaa2fab7a76fa787a593f0 | [
"for el in nums:\n if el in map:\n map[el] += 1\n else:\n map[el] = 1\nfor el in map:\n if map[el] < 2:\n return el",
"a = 0\nfor i in nums:\n a ^= i\nreturn a"
] | <|body_start_0|>
for el in nums:
if el in map:
map[el] += 1
else:
map[el] = 1
for el in map:
if map[el] < 2:
return el
<|end_body_0|>
<|body_start_1|>
a = 0
for i in nums:
a ^= i
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for el in nums:
if el in map:
... | stack_v2_sparse_classes_36k_train_026397 | 642 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011230 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def singleNu... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
for el in nums:
if el in map:
map[el] += 1
else:
map[el] = 1
for el in map:
if map[el] < 2:
return el
def singleNumbe... | the_stack_v2_python_sparse | Hash Table/136. Single Number.py | beninghton/notGivenUpToG | train | 0 | |
34c6355c069b2ed108718c6dbad8525fff44e104 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn VppToken()",
"from .entity import Entity\nfrom .vpp_token_account_type import VppTokenAccountType\nfrom .vpp_token_state import VppTokenState\nfrom .vpp_token_sync_status import VppTokenSyncStatus\nfrom .entity import Entity\nfrom .vpp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return VppToken()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .vpp_token_account_type import VppTokenAccountType
from .vpp_token_state import VppTokenState
f... | You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intune. You can then synchronize your volume purchase information with Intune a... | VppToken | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VppToken:
"""You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intune. You can then synchronize your volum... | stack_v2_sparse_classes_36k_train_026398 | 6,149 | 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: VppToken",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | null | Implement the Python class `VppToken` described below.
Class description:
You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intu... | Implement the Python class `VppToken` described below.
Class description:
You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intu... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class VppToken:
"""You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intune. You can then synchronize your volum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VppToken:
"""You purchase multiple licenses for iOS apps through the Apple Volume Purchase Program for Business or Education. This involves setting up an Apple VPP account from the Apple website and uploading the Apple VPP Business or Education token to Intune. You can then synchronize your volume purchase in... | the_stack_v2_python_sparse | msgraph/generated/models/vpp_token.py | microsoftgraph/msgraph-sdk-python | train | 135 |
1faddc9fc4c5c6850e9d6b8d3fe44867d7c747e8 | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2 and (password1 != password2):\n raise forms.ValidationError(_(\"Passwords don't match\"))\nreturn password2",
"user = super(UserCreationForm, self).save(commit=False)\nuser.set_password(s... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and (password1 != password2):
raise forms.ValidationError(_("Passwords don't match"))
return password2
<|end_body_0|>
<|body_start_1|>
... | A form for creating new users. Includes all the required fields, plus a repeated password. | UserCreationForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in... | stack_v2_sparse_classes_36k_train_026399 | 5,426 | permissive | [
{
"docstring": "Check that the two password entries match.",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save the provided password in hashed format.",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001120 | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match.
- def save(self, commit=True): Save the... | Implement the Python class `UserCreationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_password2(self): Check that the two password entries match.
- def save(self, commit=True): Save the... | 0df3033320619d787aab6c81c8445bdd9fb58a9b | <|skeleton|>
class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
<|body_0|>
def save(self, commit=True):
"""Save the provided password in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_password2(self):
"""Check that the two password entries match."""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password... | the_stack_v2_python_sparse | yaccounts/admin.py | andrecrt/django-yaccounts | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.