blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7bbeef02a0d77fd46d4c7646b6cbcae05f38993 | [
"self.nltktree = None\nself.string = p_string\nself.parseList = None\nself.nltkTree = None\nself.parseTree = None\nself.xml = None\nif p_string != None:\n self.parse(p_string)",
"self.nltktree = None\nself.string = p_string\n'\\n 1. Tokenize\\n ----------------------------------------------------... | <|body_start_0|>
self.nltktree = None
self.string = p_string
self.parseList = None
self.nltkTree = None
self.parseTree = None
self.xml = None
if p_string != None:
self.parse(p_string)
<|end_body_0|>
<|body_start_1|>
self.nltktree = None
... | Class to read and parse a paradigm visualisation query | ParadigmQuery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParadigmQuery:
"""Class to read and parse a paradigm visualisation query"""
def __init__(self, p_string=None):
"""Construct a query. Setup various attributes and parse given string"""
<|body_0|>
def parse(self, p_string):
"""Parses a string and stores the resulti... | stack_v2_sparse_classes_75kplus_train_071300 | 11,130 | permissive | [
{
"docstring": "Construct a query. Setup various attributes and parse given string",
"name": "__init__",
"signature": "def __init__(self, p_string=None)"
},
{
"docstring": "Parses a string and stores the resulting hierarchy of \"domains\" \"hierarchies\" and \"tables\" For the sake of NLP I've p... | 4 | stack_v2_sparse_classes_30k_train_052513 | Implement the Python class `ParadigmQuery` described below.
Class description:
Class to read and parse a paradigm visualisation query
Method signatures and docstrings:
- def __init__(self, p_string=None): Construct a query. Setup various attributes and parse given string
- def parse(self, p_string): Parses a string a... | Implement the Python class `ParadigmQuery` described below.
Class description:
Class to read and parse a paradigm visualisation query
Method signatures and docstrings:
- def __init__(self, p_string=None): Construct a query. Setup various attributes and parse given string
- def parse(self, p_string): Parses a string a... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class ParadigmQuery:
"""Class to read and parse a paradigm visualisation query"""
def __init__(self, p_string=None):
"""Construct a query. Setup various attributes and parse given string"""
<|body_0|>
def parse(self, p_string):
"""Parses a string and stores the resulti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParadigmQuery:
"""Class to read and parse a paradigm visualisation query"""
def __init__(self, p_string=None):
"""Construct a query. Setup various attributes and parse given string"""
self.nltktree = None
self.string = p_string
self.parseList = None
self.nltkTree =... | the_stack_v2_python_sparse | GIT-USERS/amitness/nodebox_linguistics_extended/nodebox_linguistics_extended/parser/nltk_lite/contrib/paradigmquery.py | bgoonz/UsefulResourceRepo2.0 | train | 10 |
d37a3b546b684a37a6d66cae793aac786b13a612 | [
"super(NeuralFingerprint, self).__init__()\nself.num_layers = len(conv_layer_sizes)\nself.output_size = output_size\nself.batch_type = type_map['batch']\nself.ntype = type_map['node']\nself.etype = type_map['edge']\nself.degree_list = degree_list\nself.conv_layers = nn.ModuleList()\nself.out_layers = nn.ModuleList(... | <|body_start_0|>
super(NeuralFingerprint, self).__init__()
self.num_layers = len(conv_layer_sizes)
self.output_size = output_size
self.batch_type = type_map['batch']
self.ntype = type_map['node']
self.etype = type_map['edge']
self.degree_list = degree_list
... | NeuralFingerprint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the leng... | stack_v2_sparse_classes_75kplus_train_071301 | 6,911 | no_license | [
{
"docstring": "Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the lengths of the output vectors of convolutional layers output_size (int): length of the finger print vector type_map (dict string:string): type of the ba... | 2 | stack_v2_sparse_classes_30k_train_050374 | Implement the Python class `NeuralFingerprint` described below.
Class description:
Implement the NeuralFingerprint class.
Method signatures and docstrings:
- def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True): Args: node_size (int): dimension of node r... | Implement the Python class `NeuralFingerprint` described below.
Class description:
Implement the NeuralFingerprint class.
Method signatures and docstrings:
- def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True): Args: node_size (int): dimension of node r... | e034dc60d156a577c16fa4217c00202030f1b6dc | <|skeleton|>
class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the leng... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralFingerprint:
def __init__(self, node_size, edge_size, conv_layer_sizes, output_size, type_map, degree_list, batch_normalize=True):
"""Args: node_size (int): dimension of node representations edge_size (int): dimension of edge representations conv_layer_sizes (list of int): the lengths of the out... | the_stack_v2_python_sparse | DrugTargetInteraction/methods/protein_ensemble/fingerprint/models.py | hansaimlim/thesis-works | train | 1 | |
0670e3c6c8cf4576effc01a6d76e614c73b7bf12 | [
"self.set = set()\nself.list = []\nself.label = True",
"if val not in self.set:\n self.set.add(val)\n self.list.append(val)\n return True\nelse:\n return False",
"if val in self.set:\n self.set.remove(val)\n self.label = False\n return True\nelse:\n return False",
"if self.label is Fal... | <|body_start_0|>
self.set = set()
self.list = []
self.label = True
<|end_body_0|>
<|body_start_1|>
if val not in self.set:
self.set.add(val)
self.list.append(val)
return True
else:
return False
<|end_body_1|>
<|body_start_2|>
... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_071302 | 1,619 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_004948 | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | 0c4c38849309124121b03cc0b4bf39071b5d1c8c | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.set = set()
self.list = []
self.label = True
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: i... | the_stack_v2_python_sparse | 380.py | zhangchizju2012/LeetCode | train | 7 | |
dadfeee090c1454fb5b734e098f9945beab516f8 | [
"PlotMicrobursts.__init__(self, catalog_version, plot_width=plot_width, plot_width_flag=False, make_plt_dir_flag=False)\nself.t0_times = t0_times\nreturn",
"rows = [None] * len(self.t0_times)\nfor i in range(len(rows)):\n idx = np.where(self.t0_times[i] == self.catalog.dateTime)[0]\n if len(idx) != 1:\n ... | <|body_start_0|>
PlotMicrobursts.__init__(self, catalog_version, plot_width=plot_width, plot_width_flag=False, make_plt_dir_flag=False)
self.t0_times = t0_times
return
<|end_body_0|>
<|body_start_1|>
rows = [None] * len(self.t0_times)
for i in range(len(rows)):
idx =... | PlotExamples | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotExamples:
def __init__(self, catalog_version, plot_width, t0_times):
"""This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots."""
<|body_0|>
def plot_examples(self):
"""This method"""
<|body_1|>
def _plot_s... | stack_v2_sparse_classes_75kplus_train_071303 | 4,074 | no_license | [
{
"docstring": "This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots.",
"name": "__init__",
"signature": "def __init__(self, catalog_version, plot_width, t0_times)"
},
{
"docstring": "This method",
"name": "plot_examples",
"signature": "def pl... | 3 | stack_v2_sparse_classes_30k_train_010490 | Implement the Python class `PlotExamples` described below.
Class description:
Implement the PlotExamples class.
Method signatures and docstrings:
- def __init__(self, catalog_version, plot_width, t0_times): This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots.
- def plot_e... | Implement the Python class `PlotExamples` described below.
Class description:
Implement the PlotExamples class.
Method signatures and docstrings:
- def __init__(self, catalog_version, plot_width, t0_times): This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots.
- def plot_e... | 81761d96947d4794e71efff9d9965c4e320f7b1a | <|skeleton|>
class PlotExamples:
def __init__(self, catalog_version, plot_width, t0_times):
"""This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots."""
<|body_0|>
def plot_examples(self):
"""This method"""
<|body_1|>
def _plot_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotExamples:
def __init__(self, catalog_version, plot_width, t0_times):
"""This class is a child of the PlotMicrobursts class and makes time-aligned and space-aligned plots."""
PlotMicrobursts.__init__(self, catalog_version, plot_width=plot_width, plot_width_flag=False, make_plt_dir_flag=Fals... | the_stack_v2_python_sparse | figs/fig2_plot_microbursts.py | mshumko/ac6_microburst_scale_sizes | train | 0 | |
57123a3979a91f44fab4a987790e3edbb472b151 | [
"Process.__init__(self)\nself.patron = patron\nself.referencia = referencia\nself.inicio = inicio\nself.similitud = similitud\nself.q = q",
"coincidencias = distancias_Hamming(self.referencia, self.patron, self.similitud)\nfor c in coincidencias:\n self.q.put(c + self.inicio)"
] | <|body_start_0|>
Process.__init__(self)
self.patron = patron
self.referencia = referencia
self.inicio = inicio
self.similitud = similitud
self.q = q
<|end_body_0|>
<|body_start_1|>
coincidencias = distancias_Hamming(self.referencia, self.patron, self.similitud)
... | CalculaDistancias | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculaDistancias:
def __init__(self, referencia, patron, inicio, similitud, q):
"""Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en ... | stack_v2_sparse_classes_75kplus_train_071304 | 7,566 | no_license | [
{
"docstring": "Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en la cadena de referencia. - inicio (tipo integer): posición absoluta de la secuencia en la qu... | 2 | stack_v2_sparse_classes_30k_train_048606 | Implement the Python class `CalculaDistancias` described below.
Class description:
Implement the CalculaDistancias class.
Method signatures and docstrings:
- def __init__(self, referencia, patron, inicio, similitud, q): Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo strin... | Implement the Python class `CalculaDistancias` described below.
Class description:
Implement the CalculaDistancias class.
Method signatures and docstrings:
- def __init__(self, referencia, patron, inicio, similitud, q): Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo strin... | bb906dcdaa39c0580f14bb6cef0956e7acd536ea | <|skeleton|>
class CalculaDistancias:
def __init__(self, referencia, patron, inicio, similitud, q):
"""Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalculaDistancias:
def __init__(self, referencia, patron, inicio, similitud, q):
"""Se inicializa la instancia de clase. Esta clase hereda de Process. INPUTS: - secuencia (tipo string): cadena sobre la que se va a buscar el patrón. - patron (tipo string): subcadena que estás buscando en la cadena de r... | the_stack_v2_python_sparse | search-distances/distancias.py | nevinwu/IT-code | train | 0 | |
3f50cdff9d0323d2880ddeaf534eb66b5046d6ca | [
"self.n1, self.n2 = (self.initialize_ngram(ngram_file_name1, sep), self.initialize_ngram(ngram_file_name2, sep))\nself.ngrams1, self.floor1, self.L1 = (self.n1[0], self.n1[1], self.n1[2])\nself.ngrams2, self.floor2, self.L2 = (self.n2[0], self.n2[1], self.n2[2])",
"log_score = 0\nfor i in range(len(text) - self.L... | <|body_start_0|>
self.n1, self.n2 = (self.initialize_ngram(ngram_file_name1, sep), self.initialize_ngram(ngram_file_name2, sep))
self.ngrams1, self.floor1, self.L1 = (self.n1[0], self.n1[1], self.n1[2])
self.ngrams2, self.floor2, self.L2 = (self.n2[0], self.n2[1], self.n2[2])
<|end_body_0|>
<|b... | ngram_score | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (leng... | stack_v2_sparse_classes_75kplus_train_071305 | 12,572 | permissive | [
{
"docstring": "Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (length of ngram) . self.L1 should be of length one shorter than self.L2, e.g. trigram and qua... | 3 | stack_v2_sparse_classes_30k_train_029067 | Implement the Python class `ngram_score` described below.
Class description:
Implement the ngram_score class.
Method signatures and docstrings:
- def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '): Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probabi... | Implement the Python class `ngram_score` described below.
Class description:
Implement the ngram_score class.
Method signatures and docstrings:
- def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '): Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probabi... | afac5a4b3c31ec78e6c8ef211ba9dd664a4070f7 | <|skeleton|>
class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (leng... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ngram_score:
def __init__(self, ngram_file_name1, ngram_file_name2, sep=' '):
"""Generally - scorer = ngram_score('english_trigrams.txt', 'english_quadgrams.txt') Initializes log10 probability dictionaries self.ngrams1 & 2, as well as corresponding self.floors1 & 2, and self.L1 & 2 (length of ngram) .... | the_stack_v2_python_sparse | basics_less_old.py | BenjiDayan/national_cipher_challenge | train | 0 | |
5ff5c10aaa745d32b60a640bd36f75a2f6afed6a | [
"if params.getboolean('Multiprocessing', 'measures'):\n logger.debug('Measuring the average fingerprint size using multiprocessing...')\n self._execute_using_multiprocessing()\nelse:\n logger.debug('Measuring the average fingerprint on a single process...')\n self._result = _compute_attribute_avg_size(s... | <|body_start_0|>
if params.getboolean('Multiprocessing', 'measures'):
logger.debug('Measuring the average fingerprint size using multiprocessing...')
self._execute_using_multiprocessing()
else:
logger.debug('Measuring the average fingerprint on a single process...')
... | Measure the average fingerprint size of the attributes of a dataset. | AverageFingerprintSize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AverageFingerprintSize:
"""Measure the average fingerprint size of the attributes of a dataset."""
def execute(self):
"""Measure the average fingerprint size of the attributes."""
<|body_0|>
def _execute_using_multiprocessing(self):
"""Measure the average fingerp... | stack_v2_sparse_classes_75kplus_train_071306 | 5,221 | permissive | [
{
"docstring": "Measure the average fingerprint size of the attributes.",
"name": "execute",
"signature": "def execute(self)"
},
{
"docstring": "Measure the average fingerprint size using multiprocessing.",
"name": "_execute_using_multiprocessing",
"signature": "def _execute_using_multip... | 3 | stack_v2_sparse_classes_30k_train_034483 | Implement the Python class `AverageFingerprintSize` described below.
Class description:
Measure the average fingerprint size of the attributes of a dataset.
Method signatures and docstrings:
- def execute(self): Measure the average fingerprint size of the attributes.
- def _execute_using_multiprocessing(self): Measur... | Implement the Python class `AverageFingerprintSize` described below.
Class description:
Measure the average fingerprint size of the attributes of a dataset.
Method signatures and docstrings:
- def execute(self): Measure the average fingerprint size of the attributes.
- def _execute_using_multiprocessing(self): Measur... | b687a356acc813d45dbaf5b5eb0f360df181904a | <|skeleton|>
class AverageFingerprintSize:
"""Measure the average fingerprint size of the attributes of a dataset."""
def execute(self):
"""Measure the average fingerprint size of the attributes."""
<|body_0|>
def _execute_using_multiprocessing(self):
"""Measure the average fingerp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AverageFingerprintSize:
"""Measure the average fingerprint size of the attributes of a dataset."""
def execute(self):
"""Measure the average fingerprint size of the attributes."""
if params.getboolean('Multiprocessing', 'measures'):
logger.debug('Measuring the average fingerpr... | the_stack_v2_python_sparse | brfast/measures/usability_cost/memory.py | trinhvanvuong/BrFAST | train | 0 |
f7c481bc8fc0fae473da3a99ffb0cb45f61a9501 | [
"response = self.client.get(reverse('accounts:password_reset'))\nself.assertEqual(response.status_code, 200)\nself.assertTrue('form' in response.context)",
"form_data = {'email': 'invalid@invalid.com'}\nresponse = self.client.post(reverse('accounts:password_reset'), form_data)\nself.assertFormError(response, 'for... | <|body_start_0|>
response = self.client.get(reverse('accounts:password_reset'))
self.assertEqual(response.status_code, 200)
self.assertTrue('form' in response.context)
<|end_body_0|>
<|body_start_1|>
form_data = {'email': 'invalid@invalid.com'}
response = self.client.post(revers... | PasswordResetView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetView:
def test_get(self):
"""Test that the password reset page contains the form."""
<|body_0|>
def test_invalid(self):
"""Test that invalid email addresses will be caught."""
<|body_1|>
def test_valid(self):
"""Test that the valid e... | stack_v2_sparse_classes_75kplus_train_071307 | 9,129 | permissive | [
{
"docstring": "Test that the password reset page contains the form.",
"name": "test_get",
"signature": "def test_get(self)"
},
{
"docstring": "Test that invalid email addresses will be caught.",
"name": "test_invalid",
"signature": "def test_invalid(self)"
},
{
"docstring": "Tes... | 3 | stack_v2_sparse_classes_30k_train_008399 | Implement the Python class `PasswordResetView` described below.
Class description:
Implement the PasswordResetView class.
Method signatures and docstrings:
- def test_get(self): Test that the password reset page contains the form.
- def test_invalid(self): Test that invalid email addresses will be caught.
- def test_... | Implement the Python class `PasswordResetView` described below.
Class description:
Implement the PasswordResetView class.
Method signatures and docstrings:
- def test_get(self): Test that the password reset page contains the form.
- def test_invalid(self): Test that invalid email addresses will be caught.
- def test_... | cb54d8bddb184b35f6d62c17b44b311617b76b4f | <|skeleton|>
class PasswordResetView:
def test_get(self):
"""Test that the password reset page contains the form."""
<|body_0|>
def test_invalid(self):
"""Test that invalid email addresses will be caught."""
<|body_1|>
def test_valid(self):
"""Test that the valid e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordResetView:
def test_get(self):
"""Test that the password reset page contains the form."""
response = self.client.get(reverse('accounts:password_reset'))
self.assertEqual(response.status_code, 200)
self.assertTrue('form' in response.context)
def test_invalid(self):
... | the_stack_v2_python_sparse | accounts/tests.py | kmollee/gallery | train | 3 | |
8b20623c8052aa52c4548f58fdf9cec5ee44555b | [
"if not self.subdomain:\n raise errors.ErrorMessage(400, 'No subdomain specified.')\nif self.request.get('hub.mode') in ['subscribe', 'unsubscribe']:\n topic = self.request.get('hub.topic')\n signature = self.request.get('hub.verify_token')\n if not crypto.verify('hub_verify', topic, signature):\n ... | <|body_start_0|>
if not self.subdomain:
raise errors.ErrorMessage(400, 'No subdomain specified.')
if self.request.get('hub.mode') in ['subscribe', 'unsubscribe']:
topic = self.request.get('hub.topic')
signature = self.request.get('hub.verify_token')
if not... | Feed | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Feed:
def get(self):
"""Emits entries in the delta feed; also handles subscription checks."""
<|body_0|>
def post(self):
"""Feed update notification from hub."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.subdomain:
raise e... | stack_v2_sparse_classes_75kplus_train_071308 | 7,401 | permissive | [
{
"docstring": "Emits entries in the delta feed; also handles subscription checks.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Feed update notification from hub.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011552 | Implement the Python class `Feed` described below.
Class description:
Implement the Feed class.
Method signatures and docstrings:
- def get(self): Emits entries in the delta feed; also handles subscription checks.
- def post(self): Feed update notification from hub. | Implement the Python class `Feed` described below.
Class description:
Implement the Feed class.
Method signatures and docstrings:
- def get(self): Emits entries in the delta feed; also handles subscription checks.
- def post(self): Feed update notification from hub.
<|skeleton|>
class Feed:
def get(self):
... | 7715276b3c588f7c457de04944559052c8170f7e | <|skeleton|>
class Feed:
def get(self):
"""Emits entries in the delta feed; also handles subscription checks."""
<|body_0|>
def post(self):
"""Feed update notification from hub."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Feed:
def get(self):
"""Emits entries in the delta feed; also handles subscription checks."""
if not self.subdomain:
raise errors.ErrorMessage(400, 'No subdomain specified.')
if self.request.get('hub.mode') in ['subscribe', 'unsubscribe']:
topic = self.request.g... | the_stack_v2_python_sparse | app/feeds_delta.py | Princessgladys/googleresourcefinder | train | 0 | |
1ecba3b803f18e740eb13291702c6f5237f01ab5 | [
"super().__init__(name=name, verbose=verbose)\nassert 0 <= clip_fraction <= 1\nself.levels_path = levels_path\nself.mip = int(mip)\nself.clip_fraction = float(clip_fraction)\nself.minval = minval\nself.maxval = maxval",
"assert chunk.ndim == 3\nimage = np.transpose(chunk).astype(np.float32)\noffset = Vec(*chunk.g... | <|body_start_0|>
super().__init__(name=name, verbose=verbose)
assert 0 <= clip_fraction <= 1
self.levels_path = levels_path
self.mip = int(mip)
self.clip_fraction = float(clip_fraction)
self.minval = minval
self.maxval = maxval
<|end_body_0|>
<|body_start_1|>
... | Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735 | NormalizeSectionContrastOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizeSectionContrastOperator:
"""Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735"""
def __init__(self, levels_path: str, ... | stack_v2_sparse_classes_75kplus_train_071309 | 4,858 | permissive | [
{
"docstring": "levels_path: (str) path of section histogram files. mip: (int) the mip level of section histogram. clip_fraction: (float) the fraction of intensity to be clamped. minval: (float)",
"name": "__init__",
"signature": "def __init__(self, levels_path: str, mip: int, clip_fraction: float, minv... | 4 | stack_v2_sparse_classes_30k_val_002301 | Implement the Python class `NormalizeSectionContrastOperator` described below.
Class description:
Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735
Metho... | Implement the Python class `NormalizeSectionContrastOperator` described below.
Class description:
Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735
Metho... | c7e78eb9798e88e398e6f56469a00ff26cff9232 | <|skeleton|>
class NormalizeSectionContrastOperator:
"""Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735"""
def __init__(self, levels_path: str, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NormalizeSectionContrastOperator:
"""Contrast Correction based on LuminanceLevelsTask output. Note that this operator was modified from Will's ContrastNormalizationTask in igneous: https://github.com/seung-lab/igneous/blob/master/igneous/tasks.py#L735"""
def __init__(self, levels_path: str, mip: int, cli... | the_stack_v2_python_sparse | chunkflow/flow/normalize_section_contrast.py | aixioma/chunkflow | train | 0 |
b6406b49efaf235b9fd538f58aa48d91d908550f | [
"if isinstance(im_gens, morphism.RingHomomorphism_from_quotient):\n return morphism.RingHomomorphism_from_quotient(self, im_gens._phi())\ntry:\n pi = self.domain().cover()\n phi = pi.domain().hom(im_gens, check=check)\n return morphism.RingHomomorphism_from_quotient(self, phi)\nexcept (NotImplementedErr... | <|body_start_0|>
if isinstance(im_gens, morphism.RingHomomorphism_from_quotient):
return morphism.RingHomomorphism_from_quotient(self, im_gens._phi())
try:
pi = self.domain().cover()
phi = pi.domain().hom(im_gens, check=check)
return morphism.RingHomomorph... | Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) Defn: a |--> b... | RingHomset_quo_ring | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RingHomset_quo_ring:
"""Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rationa... | stack_v2_sparse_classes_75kplus_train_071310 | 10,274 | no_license | [
{
"docstring": "Create a homomorphism. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: H = S.Hom(R) sage: phi = H([b,a]); phi Ring morphism: From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) To: Multivariate Polynomia... | 2 | null | Implement the Python class `RingHomset_quo_ring` described below.
Class description:
Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivaria... | Implement the Python class `RingHomset_quo_ring` described below.
Class description:
Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivaria... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class RingHomset_quo_ring:
"""Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rationa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RingHomset_quo_ring:
"""Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rational Field by th... | the_stack_v2_python_sparse | sage/src/sage/rings/homset.py | bopopescu/geosci | train | 0 |
ece9333bb2b582bf1c3f5a010b8dc75bc1641ad6 | [
"super(ConvNet1D, self).__init__(params=params, model_name=model_name, expand_dims=False)\ninput_shape = (None, None, None)\nself.conv_1 = tf.keras.layers.Conv1D(64, 2, input_shape=input_shape, padding='same', activation='relu')\nself.conv_2 = tf.keras.layers.Conv1D(64, 2, padding='same', activation='relu')\nself.c... | <|body_start_0|>
super(ConvNet1D, self).__init__(params=params, model_name=model_name, expand_dims=False)
input_shape = (None, None, None)
self.conv_1 = tf.keras.layers.Conv1D(64, 2, input_shape=input_shape, padding='same', activation='relu')
self.conv_2 = tf.keras.layers.Conv1D(64, 2, p... | A simple 1-dimensional CNN model. | ConvNet1D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvNet1D:
"""A simple 1-dimensional CNN model."""
def __init__(self, params, model_name='ConvNet1D'):
"""Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for initialising the model. :param model_name: the name of the mo... | stack_v2_sparse_classes_75kplus_train_071311 | 2,817 | permissive | [
{
"docstring": "Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for initialising the model. :param model_name: the name of the model.",
"name": "__init__",
"signature": "def __init__(self, params, model_name='ConvNet1D')"
},
{
"doc... | 3 | null | Implement the Python class `ConvNet1D` described below.
Class description:
A simple 1-dimensional CNN model.
Method signatures and docstrings:
- def __init__(self, params, model_name='ConvNet1D'): Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for init... | Implement the Python class `ConvNet1D` described below.
Class description:
A simple 1-dimensional CNN model.
Method signatures and docstrings:
- def __init__(self, params, model_name='ConvNet1D'): Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for init... | 9ca6d5588bf025ae6feb848412261c10ac012e1f | <|skeleton|>
class ConvNet1D:
"""A simple 1-dimensional CNN model."""
def __init__(self, params, model_name='ConvNet1D'):
"""Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for initialising the model. :param model_name: the name of the mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvNet1D:
"""A simple 1-dimensional CNN model."""
def __init__(self, params, model_name='ConvNet1D'):
"""Initialises the model. Calls the initialise method of the super class. :param params: the global hyperparameters for initialising the model. :param model_name: the name of the model."""
... | the_stack_v2_python_sparse | src/models_embedding/conv_net_1d.py | dhockaday/deep-embedded-music | train | 0 |
d20646d560e273c3e86319dd707e4e97cd063a68 | [
"l = len(matrix)\ndp_row = [[0] * l for _ in range(l)]\ndp_col = [[0] * l for _ in range(l)]\nfor i in range(l):\n for j in range(l):\n if matrix[i][j] == 0:\n dp_row[i][j] = dp_row[i][j - 1] + 1\n dp_col[i][j] = dp_col[i - 1][j] + 1\nres = []\nfor i in range(l - 1, -1, -1):\n for... | <|body_start_0|>
l = len(matrix)
dp_row = [[0] * l for _ in range(l)]
dp_col = [[0] * l for _ in range(l)]
for i in range(l):
for j in range(l):
if matrix[i][j] == 0:
dp_row[i][j] = dp_row[i][j - 1] + 1
dp_col[i][j] = dp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSquare(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findSquare_2(self, matrix):
"""实现找到最大的边为全0的方阵,看做卷积运算,但是会超时 :type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findSquare_3(self, m... | stack_v2_sparse_classes_75kplus_train_071312 | 4,012 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findSquare",
"signature": "def findSquare(self, matrix)"
},
{
"docstring": "实现找到最大的边为全0的方阵,看做卷积运算,但是会超时 :type matrix: List[List[int]] :rtype: List[int]",
"name": "findSquare_2",
"signature": "def findSquare_2(self... | 3 | stack_v2_sparse_classes_30k_train_011939 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSquare(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findSquare_2(self, matrix): 实现找到最大的边为全0的方阵,看做卷积运算,但是会超时 :type matrix: List[List[int]] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSquare(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findSquare_2(self, matrix): 实现找到最大的边为全0的方阵,看做卷积运算,但是会超时 :type matrix: List[List[int]] :rtype: ... | 64bc823e2a7325f36d09fd282b13da56962d8218 | <|skeleton|>
class Solution:
def findSquare(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findSquare_2(self, matrix):
"""实现找到最大的边为全0的方阵,看做卷积运算,但是会超时 :type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findSquare_3(self, m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findSquare(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
l = len(matrix)
dp_row = [[0] * l for _ in range(l)]
dp_col = [[0] * l for _ in range(l)]
for i in range(l):
for j in range(l):
if matrix[i][j] == 0... | the_stack_v2_python_sparse | LCCI/0928M最大黑方阵.py | Kittyuzu1207/Leecode | train | 0 | |
4986d7562765fae465ddffef852a0071fca82fc4 | [
"apply_ipaddr, apply_port = System.get_apply_ip_and_port()\ntry:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n send_data = json.dumps(send_data)\n send_data = send_data.encode()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket... | <|body_start_0|>
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
send_data = json.dumps(send_data)
send_data = send_data.encode()
sock.setsockopt(socket.SOL_SOCKET, ... | RequestToApply | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_75kplus_train_071313 | 9,642 | permissive | [
{
"docstring": "[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ",
"name": "_request",
"signature": "def _request(cls, send_data, request=None)"
},
{
"docstring": "[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue, 異常ならFalse msg : 受信メッセージ",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000693 | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/common.py | exastro-suite/oase | train | 10 | |
e85f607203fbb8bbbe3bec658cd2bada382d920a | [
"self.valid = ValidatorLab()\nself.lab_rau1 = Laborator('ab', 'oop', '1.12.2020')\nself.lab_rau2 = Laborator('1_1', '', '12.12.2020')\nself.lab_rau3 = Laborator('1_1', 'test', 'asd.12.2020')\nself.lab_rau4 = Laborator('a_1', '', '12.12.2020')\nself.lab_rau5 = Laborator('1_1', '', '45.12.2020')\nself.lab_rau6 = Labo... | <|body_start_0|>
self.valid = ValidatorLab()
self.lab_rau1 = Laborator('ab', 'oop', '1.12.2020')
self.lab_rau2 = Laborator('1_1', '', '12.12.2020')
self.lab_rau3 = Laborator('1_1', 'test', 'asd.12.2020')
self.lab_rau4 = Laborator('a_1', '', '12.12.2020')
self.lab_rau5 = L... | clasa care testeaza functionalitatile din clasa ValidatorLaborator | TestCaseValidatorLaborator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCaseValidatorLaborator:
"""clasa care testeaza functionalitatile din clasa ValidatorLaborator"""
def setUp(self):
"""codul executat inainte de fiecare testi"""
<|body_0|>
def testValidator(self):
"""testarea functiei valideaza din ValidatorLaborator cu metoda... | stack_v2_sparse_classes_75kplus_train_071314 | 4,135 | no_license | [
{
"docstring": "codul executat inainte de fiecare testi",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "testarea functiei valideaza din ValidatorLaborator cu metoda blackbox",
"name": "testValidator",
"signature": "def testValidator(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051000 | Implement the Python class `TestCaseValidatorLaborator` described below.
Class description:
clasa care testeaza functionalitatile din clasa ValidatorLaborator
Method signatures and docstrings:
- def setUp(self): codul executat inainte de fiecare testi
- def testValidator(self): testarea functiei valideaza din Validat... | Implement the Python class `TestCaseValidatorLaborator` described below.
Class description:
clasa care testeaza functionalitatile din clasa ValidatorLaborator
Method signatures and docstrings:
- def setUp(self): codul executat inainte de fiecare testi
- def testValidator(self): testarea functiei valideaza din Validat... | b14a02ac3e4f2a126306b0a89fc196c3af847614 | <|skeleton|>
class TestCaseValidatorLaborator:
"""clasa care testeaza functionalitatile din clasa ValidatorLaborator"""
def setUp(self):
"""codul executat inainte de fiecare testi"""
<|body_0|>
def testValidator(self):
"""testarea functiei valideaza din ValidatorLaborator cu metoda... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCaseValidatorLaborator:
"""clasa care testeaza functionalitatile din clasa ValidatorLaborator"""
def setUp(self):
"""codul executat inainte de fiecare testi"""
self.valid = ValidatorLab()
self.lab_rau1 = Laborator('ab', 'oop', '1.12.2020')
self.lab_rau2 = Laborator('1_... | the_stack_v2_python_sparse | testare/testeValidator.py | SavaTudor/StudentsLabsGrades | train | 0 |
cd81149eb09663da0f05505c52c051ed7981f3aa | [
"super().__init__(parent=parent)\nself.plotWidget: Optional['PlotWidget'] = None\nself.data: Optional[DataDictBase] = None\nlayout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout(self)\nlayout.setContentsMargins(0, 0, 0, 0)\nself.setLayout(layout)",
"if widget is self.plotWidget:\n return\nif self.plotWidget is... | <|body_start_0|>
super().__init__(parent=parent)
self.plotWidget: Optional['PlotWidget'] = None
self.data: Optional[DataDictBase] = None
layout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
<|end_body_0|>... | This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementing widgets that can be added to this container. | PlotWidgetContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotWidgetContainer:
"""This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementi... | stack_v2_sparse_classes_75kplus_train_071315 | 23,346 | permissive | [
{
"docstring": "Constructor for :class:`PlotWidgetContainer`.",
"name": "__init__",
"signature": "def __init__(self, parent: Optional[QtWidgets.QWidget]=None)"
},
{
"docstring": "Set the plot widget. Makes sure that the added widget receives new data. :param widget: plot widget",
"name": "se... | 3 | stack_v2_sparse_classes_30k_train_021068 | Implement the Python class `PlotWidgetContainer` described below.
Class description:
This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :cl... | Implement the Python class `PlotWidgetContainer` described below.
Class description:
This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :cl... | 0ccdeb76d44fcc57e5b986c8b75cb0696fbff03b | <|skeleton|>
class PlotWidgetContainer:
"""This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotWidgetContainer:
"""This is the base widget for Plots, derived from `QWidget`. This widget does not implement any plotting. It merely is a wrapping widget that contains the actual plot widget in it. This actual plot widget can be set dynamically. Use :class:`PlotWidget` as base for implementing widgets th... | the_stack_v2_python_sparse | plottr/plot/base.py | labist/plottr | train | 0 |
fc8ce66af9d5f2b30661a3d226956c910065b16e | [
"if 'date' in column_type and value != None:\n if custom_date:\n value = custom_date(value)\n else:\n value = datetime.strptime(value, DATE_FORMAT)\nif value == 'true':\n value = True\nelif value == 'false':\n value = False\nif 'int' in column_type:\n value = int(value)\nreturn value",
... | <|body_start_0|>
if 'date' in column_type and value != None:
if custom_date:
value = custom_date(value)
else:
value = datetime.strptime(value, DATE_FORMAT)
if value == 'true':
value = True
elif value == 'false':
valu... | Base model class that includes CRUD convenience methods. | Model | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""Base model class that includes CRUD convenience methods."""
def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str:
"""handle special filter cases such bool value or date value"""
<|body_0|>
def _filter_data... | stack_v2_sparse_classes_75kplus_train_071316 | 8,064 | permissive | [
{
"docstring": "handle special filter cases such bool value or date value",
"name": "_handle_special_cases",
"signature": "def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str"
},
{
"docstring": "get column and filter strings and return fil... | 5 | stack_v2_sparse_classes_30k_train_006822 | Implement the Python class `Model` described below.
Class description:
Base model class that includes CRUD convenience methods.
Method signatures and docstrings:
- def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str: handle special filter cases such bool value ... | Implement the Python class `Model` described below.
Class description:
Base model class that includes CRUD convenience methods.
Method signatures and docstrings:
- def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str: handle special filter cases such bool value ... | 21708382b9bdf0c231b01fb6c161b6db0e26cb36 | <|skeleton|>
class Model:
"""Base model class that includes CRUD convenience methods."""
def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str:
"""handle special filter cases such bool value or date value"""
<|body_0|>
def _filter_data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
"""Base model class that includes CRUD convenience methods."""
def _handle_special_cases(column: str, value: str, custom_date: callable=None, column_type: str=None) -> str:
"""handle special filter cases such bool value or date value"""
if 'date' in column_type and value != None:
... | the_stack_v2_python_sparse | server/api/database/mixins.py | Data4ITBV/Dryvo | train | 0 |
3c7a89fd6c25f688db1b3c9f92e9b02bd5fcad35 | [
"self.ad_special_parameters = ad_special_parameters\nself.exchange_special_parameters = exchange_special_parameters\nself.oracle_special_parameters = oracle_special_parameters\nself.physical_special_parameters = physical_special_parameters\nself.skip_indexing = skip_indexing\nself.source_id = source_id\nself.sql_sp... | <|body_start_0|>
self.ad_special_parameters = ad_special_parameters
self.exchange_special_parameters = exchange_special_parameters
self.oracle_special_parameters = oracle_special_parameters
self.physical_special_parameters = physical_special_parameters
self.skip_indexing = skip_i... | Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (ApplicationSpecialParameters): Specifies additional special parameters that are applicable only to P... | SourceSpecialParameter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceSpecialParameter:
"""Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (ApplicationSpecialParameters): Specifies additiona... | stack_v2_sparse_classes_75kplus_train_071317 | 7,702 | permissive | [
{
"docstring": "Constructor for the SourceSpecialParameter class",
"name": "__init__",
"signature": "def __init__(self, ad_special_parameters=None, exchange_special_parameters=None, oracle_special_parameters=None, physical_special_parameters=None, skip_indexing=None, source_id=None, sql_special_paramete... | 2 | stack_v2_sparse_classes_30k_train_044359 | Implement the Python class `SourceSpecialParameter` described below.
Class description:
Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (Application... | Implement the Python class `SourceSpecialParameter` described below.
Class description:
Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (Application... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SourceSpecialParameter:
"""Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (ApplicationSpecialParameters): Specifies additiona... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SourceSpecialParameter:
"""Implementation of the 'SourceSpecialParameter' model. Specifies additional special settings for a single Source in a Protection Job. This Source must be a leaf node in the Source tree. Attributes: ad_special_parameters (ApplicationSpecialParameters): Specifies additional special par... | the_stack_v2_python_sparse | cohesity_management_sdk/models/source_special_parameter.py | cohesity/management-sdk-python | train | 24 |
3ce2495efc5d5b97ba92d2eca3e1b8c5eee3f9db | [
"super(DpkgLocal, self).__init__()\nself._release = release\nself._arch = arch\nself._executor = executor",
"root = self._executor.root_filesystem_directory()\ndirectory.safe_makedirs(os.path.join(root, 'var', 'cache', 'apt', 'archives', 'partial'))\ndirectory.safe_makedirs(os.path.join(root, 'var', 'lib', 'apt',... | <|body_start_0|>
super(DpkgLocal, self).__init__()
self._release = release
self._arch = arch
self._executor = executor
<|end_body_0|>
<|body_start_1|>
root = self._executor.root_filesystem_directory()
directory.safe_makedirs(os.path.join(root, 'var', 'cache', 'apt', 'arc... | Debian packaging system, installing packages to local directory. | DpkgLocal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DpkgLocal:
"""Debian packaging system, installing packages to local directory."""
def __init__(self, release, arch, executor):
"""Initialize this PackageSystem."""
<|body_0|>
def _initialize_directories(self):
"""Ensure that all APT and Dpkg directories are initi... | stack_v2_sparse_classes_75kplus_train_071318 | 19,882 | permissive | [
{
"docstring": "Initialize this PackageSystem.",
"name": "__init__",
"signature": "def __init__(self, release, arch, executor)"
},
{
"docstring": "Ensure that all APT and Dpkg directories are initialized.",
"name": "_initialize_directories",
"signature": "def _initialize_directories(self... | 4 | stack_v2_sparse_classes_30k_train_052502 | Implement the Python class `DpkgLocal` described below.
Class description:
Debian packaging system, installing packages to local directory.
Method signatures and docstrings:
- def __init__(self, release, arch, executor): Initialize this PackageSystem.
- def _initialize_directories(self): Ensure that all APT and Dpkg ... | Implement the Python class `DpkgLocal` described below.
Class description:
Debian packaging system, installing packages to local directory.
Method signatures and docstrings:
- def __init__(self, release, arch, executor): Initialize this PackageSystem.
- def _initialize_directories(self): Ensure that all APT and Dpkg ... | bb31302cfc48f55da56c12ab27b88644380209b9 | <|skeleton|>
class DpkgLocal:
"""Debian packaging system, installing packages to local directory."""
def __init__(self, release, arch, executor):
"""Initialize this PackageSystem."""
<|body_0|>
def _initialize_directories(self):
"""Ensure that all APT and Dpkg directories are initi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DpkgLocal:
"""Debian packaging system, installing packages to local directory."""
def __init__(self, release, arch, executor):
"""Initialize this PackageSystem."""
super(DpkgLocal, self).__init__()
self._release = release
self._arch = arch
self._executor = executor... | the_stack_v2_python_sparse | psqtraviscontainer/package_system.py | violethaze74/polysquare-travis-container | train | 0 |
fb5d5a312c10b95b1b3e15bab0bec8f5e2d9d512 | [
"super(AndroidTarget, self).__init__(address=address, **kwargs)\nself.add_labels('android')\nself.build_tools_version = build_tools_version\nself._spec_path = address.spec_path\nself._manifest_file = manifest",
"if self._manifest_file is None:\n self._manifest_file = 'AndroidManifest.xml'\nmanifest_path = os.p... | <|body_start_0|>
super(AndroidTarget, self).__init__(address=address, **kwargs)
self.add_labels('android')
self.build_tools_version = build_tools_version
self._spec_path = address.spec_path
self._manifest_file = manifest
<|end_body_0|>
<|body_start_1|>
if self._manifest_... | A base class for all Android targets. | AndroidTarget | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidTarget:
"""A base class for all Android targets."""
def __init__(self, address=None, build_tools_version='19.1.0', manifest=None, **kwargs):
""":param build_tools_version: API for the Build Tools (separate from SDK version). Defaults to the latest full release. :param manifest... | stack_v2_sparse_classes_75kplus_train_071319 | 2,242 | permissive | [
{
"docstring": ":param build_tools_version: API for the Build Tools (separate from SDK version). Defaults to the latest full release. :param manifest: path/to/file of 'AndroidManifest.xml' (required name). Paths are relative to the BUILD file's directory.",
"name": "__init__",
"signature": "def __init__... | 2 | null | Implement the Python class `AndroidTarget` described below.
Class description:
A base class for all Android targets.
Method signatures and docstrings:
- def __init__(self, address=None, build_tools_version='19.1.0', manifest=None, **kwargs): :param build_tools_version: API for the Build Tools (separate from SDK versi... | Implement the Python class `AndroidTarget` described below.
Class description:
A base class for all Android targets.
Method signatures and docstrings:
- def __init__(self, address=None, build_tools_version='19.1.0', manifest=None, **kwargs): :param build_tools_version: API for the Build Tools (separate from SDK versi... | f65bc3d8e3445afc996db3fea8c6d2577aefec3b | <|skeleton|>
class AndroidTarget:
"""A base class for all Android targets."""
def __init__(self, address=None, build_tools_version='19.1.0', manifest=None, **kwargs):
""":param build_tools_version: API for the Build Tools (separate from SDK version). Defaults to the latest full release. :param manifest... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AndroidTarget:
"""A base class for all Android targets."""
def __init__(self, address=None, build_tools_version='19.1.0', manifest=None, **kwargs):
""":param build_tools_version: API for the Build Tools (separate from SDK version). Defaults to the latest full release. :param manifest: path/to/fil... | the_stack_v2_python_sparse | contrib/android/src/python/pants/contrib/android/targets/android_target.py | kayak/pants | train | 1 |
3bf1959854ae5f75c4671b1bddceed05115ca1d4 | [
"d = self.Wire('d-wire')\ne = self.Wire('e-wire')\nself.OrGate(a, b, d)\nself.AndGate(a, b, c)\nself.Inverter(c, e)\nself.AndGate(d, e, s)\nreturn 'ok'",
"d = self.Wire()\nc1 = self.Wire()\nc2 = self.Wire()\nself.HalfAdder(b, c_in, d, c1)\nself.HalfAdder(a, d, s, c2)\nself.OrGate(c1, c2, c_out)\nreturn 'ok'",
"... | <|body_start_0|>
d = self.Wire('d-wire')
e = self.Wire('e-wire')
self.OrGate(a, b, d)
self.AndGate(a, b, c)
self.Inverter(c, e)
self.AndGate(d, e, s)
return 'ok'
<|end_body_0|>
<|body_start_1|>
d = self.Wire()
c1 = self.Wire()
c2 = self.Wi... | A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire object, that can be passed as an input to logic gates functions - AndGate(a1, a2, out):... | MyPrettySimulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPrettySimulator:
"""A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire object, that can be passed as an input to ... | stack_v2_sparse_classes_75kplus_train_071320 | 10,524 | no_license | [
{
"docstring": "The half-adder (see Rosen, figure 8, p. 827). Other, equivalent circuits are possible -f.i. involving an XOR gate-, but this is the most straightforward one.",
"name": "HalfAdder",
"signature": "def HalfAdder(self, a, b, s, c)"
},
{
"docstring": "The full-adder (see Rosen, figure... | 4 | stack_v2_sparse_classes_30k_train_028109 | Implement the Python class `MyPrettySimulator` described below.
Class description:
A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire obj... | Implement the Python class `MyPrettySimulator` described below.
Class description:
A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire obj... | 46dcbccf220da8c4b0be1c6e9ff4185017c91a15 | <|skeleton|>
class MyPrettySimulator:
"""A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire object, that can be passed as an input to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyPrettySimulator:
"""A class skeleton for the digital circuit implementation of <Blake Prescott> - <CS124> The class extends the Simulator class, that contains the core simulation code. It inherits the following methods: - Wire( [name] ): creates a Wire object, that can be passed as an input to logic gates f... | the_stack_v2_python_sparse | cs124task4BlakePrescott.py | bwprescott/2015-Assignments-and-Projects | train | 0 |
91ffc8556fcbb01df524da42470cead0cb32c307 | [
"super(DomainNet, self).__init__()\nself.rgb_features = Features(num_channels=num_channels)\nself.lwir_features = Features(num_channels=num_channels)\nself.correlation_cls = Classifier(num_channels=256)\nself.concat_cls = Classifier(num_channels=512)",
"rgb = self.rgb_features(rgb)\nlwir = self.lwir_features(lwir... | <|body_start_0|>
super(DomainNet, self).__init__()
self.rgb_features = Features(num_channels=num_channels)
self.lwir_features = Features(num_channels=num_channels)
self.correlation_cls = Classifier(num_channels=256)
self.concat_cls = Classifier(num_channels=512)
<|end_body_0|>
<... | DomainNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainNet:
def __init__(self, num_channels: int):
"""represents the architecture of the proposed model. :param num_channels: number of channels of the input image."""
<|body_0|>
def forward(self, rgb: torch.Tensor, lwir: torch.Tensor) -> (torch.Tensor, torch.Tensor):
... | stack_v2_sparse_classes_75kplus_train_071321 | 1,680 | permissive | [
{
"docstring": "represents the architecture of the proposed model. :param num_channels: number of channels of the input image.",
"name": "__init__",
"signature": "def __init__(self, num_channels: int)"
},
{
"docstring": "forward pass implementation of both correlation and concatenation branches.... | 2 | stack_v2_sparse_classes_30k_train_013143 | Implement the Python class `DomainNet` described below.
Class description:
Implement the DomainNet class.
Method signatures and docstrings:
- def __init__(self, num_channels: int): represents the architecture of the proposed model. :param num_channels: number of channels of the input image.
- def forward(self, rgb: t... | Implement the Python class `DomainNet` described below.
Class description:
Implement the DomainNet class.
Method signatures and docstrings:
- def __init__(self, num_channels: int): represents the architecture of the proposed model. :param num_channels: number of channels of the input image.
- def forward(self, rgb: t... | 583e6868864582f081f18689124e74e9ca169f28 | <|skeleton|>
class DomainNet:
def __init__(self, num_channels: int):
"""represents the architecture of the proposed model. :param num_channels: number of channels of the input image."""
<|body_0|>
def forward(self, rgb: torch.Tensor, lwir: torch.Tensor) -> (torch.Tensor, torch.Tensor):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DomainNet:
def __init__(self, num_channels: int):
"""represents the architecture of the proposed model. :param num_channels: number of channels of the input image."""
super(DomainNet, self).__init__()
self.rgb_features = Features(num_channels=num_channels)
self.lwir_features = ... | the_stack_v2_python_sparse | models/domainnet.py | beaupreda/domain-networks | train | 1 | |
6a0ffe02ae5f97cef4054f4e0f3c2740bb190ffe | [
"queryset = self.get_queryset().values_list('accountid', flat=True)\npage = self.paginate_queryset(queryset)\nif page is not None:\n return self.get_paginated_response({'accountid': page})\nserializer = self.get_serializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = self.queryset\nacco... | <|body_start_0|>
queryset = self.get_queryset().values_list('accountid', flat=True)
page = self.paginate_queryset(queryset)
if page is not None:
return self.get_paginated_response({'accountid': page})
serializer = self.get_serializer(queryset, many=True)
return Respon... | ViewSet for /api/accounts/ | AccountViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountViewSet:
"""ViewSet for /api/accounts/"""
def list(self, request):
"""List Accounts."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get one Account."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = self.get_queryset().va... | stack_v2_sparse_classes_75kplus_train_071322 | 4,903 | no_license | [
{
"docstring": "List Accounts.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Get one Account.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021206 | Implement the Python class `AccountViewSet` described below.
Class description:
ViewSet for /api/accounts/
Method signatures and docstrings:
- def list(self, request): List Accounts.
- def retrieve(self, request, pk=None): Get one Account. | Implement the Python class `AccountViewSet` described below.
Class description:
ViewSet for /api/accounts/
Method signatures and docstrings:
- def list(self, request): List Accounts.
- def retrieve(self, request, pk=None): Get one Account.
<|skeleton|>
class AccountViewSet:
"""ViewSet for /api/accounts/"""
... | a8593884641b3aa1411260d0be572dde7ae0ae58 | <|skeleton|>
class AccountViewSet:
"""ViewSet for /api/accounts/"""
def list(self, request):
"""List Accounts."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get one Account."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountViewSet:
"""ViewSet for /api/accounts/"""
def list(self, request):
"""List Accounts."""
queryset = self.get_queryset().values_list('accountid', flat=True)
page = self.paginate_queryset(queryset)
if page is not None:
return self.get_paginated_response({'a... | the_stack_v2_python_sparse | rest/rest/api/views.py | ucb-rit/mybrc-not-user-portal | train | 0 |
2d6cb9dec1ccb65fd98b9f757115453ee88b091d | [
"user = auth(session, required=True)\nif not user.can('see_all') and (not user.can('review_downloads')):\n return ({}, 403)\nif not network:\n routes = app.routes._default\nelse:\n routes = app.routes.get(network, None)\n if not routes:\n return ({}, 404)\nreturn [f for f in routes.protocol.downl... | <|body_start_0|>
user = auth(session, required=True)
if not user.can('see_all') and (not user.can('review_downloads')):
return ({}, 403)
if not network:
routes = app.routes._default
else:
routes = app.routes.get(network, None)
if not routes... | RevisionDownloadsResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevisionDownloadsResource:
def get(self, network):
"""Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has no need for a "hash" parameter."""
<|body_0|>
def post(self, network):
"""Decrements a peers... | stack_v2_sparse_classes_75kplus_train_071323 | 7,437 | permissive | [
{
"docstring": "Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has no need for a \"hash\" parameter.",
"name": "get",
"signature": "def get(self, network)"
},
{
"docstring": "Decrements a peers trust rating and deletes the off... | 2 | stack_v2_sparse_classes_30k_test_000730 | Implement the Python class `RevisionDownloadsResource` described below.
Class description:
Implement the RevisionDownloadsResource class.
Method signatures and docstrings:
- def get(self, network): Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has... | Implement the Python class `RevisionDownloadsResource` described below.
Class description:
Implement the RevisionDownloadsResource class.
Method signatures and docstrings:
- def get(self, network): Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has... | 3a179d01e7eb60642b403d11e11b7103d08d466f | <|skeleton|>
class RevisionDownloadsResource:
def get(self, network):
"""Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has no need for a "hash" parameter."""
<|body_0|>
def post(self, network):
"""Decrements a peers... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RevisionDownloadsResource:
def get(self, network):
"""Provides an overview of revisions fetched via overlay network. Would be part of RevisionFeedbackResource except this has no need for a "hash" parameter."""
user = auth(session, required=True)
if not user.can('see_all') and (not user... | the_stack_v2_python_sparse | synchrony/resources/revisions.py | Psybernetics/Synchrony | train | 36 | |
f49141147313ac7856cebd21a8914c5e9957e92c | [
"await super()._get_source_responses(*urls)\nstats_api = URL(f'{await self._api_url()}/cxrestapi/sast/scans/{self._scan_id}/resultsStatistics')\nreturn await SourceCollector._get_source_responses(self, stats_api)",
"stats = await responses[0].json()\nseverities = self._parameter('severities')\nreturn str(sum((sta... | <|body_start_0|>
await super()._get_source_responses(*urls)
stats_api = URL(f'{await self._api_url()}/cxrestapi/sast/scans/{self._scan_id}/resultsStatistics')
return await SourceCollector._get_source_responses(self, stats_api)
<|end_body_0|>
<|body_start_1|>
stats = await responses[0].j... | Collector class to measure the number of security warnings in a Checkmarx CxSAST scan. | CxSASTSecurityWarnings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CxSASTSecurityWarnings:
"""Collector class to measure the number of security warnings in a Checkmarx CxSAST scan."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to get the scan results."""
<|body_0|>
async def _parse_value(self, respon... | stack_v2_sparse_classes_75kplus_train_071324 | 1,092 | permissive | [
{
"docstring": "Extend to get the scan results.",
"name": "_get_source_responses",
"signature": "async def _get_source_responses(self, *urls: URL) -> SourceResponses"
},
{
"docstring": "Override to parse the number of security warnings from the scan results.",
"name": "_parse_value",
"si... | 2 | stack_v2_sparse_classes_30k_train_030116 | Implement the Python class `CxSASTSecurityWarnings` described below.
Class description:
Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.
Method signatures and docstrings:
- async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to get the scan results.
- asy... | Implement the Python class `CxSASTSecurityWarnings` described below.
Class description:
Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.
Method signatures and docstrings:
- async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to get the scan results.
- asy... | 5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3 | <|skeleton|>
class CxSASTSecurityWarnings:
"""Collector class to measure the number of security warnings in a Checkmarx CxSAST scan."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to get the scan results."""
<|body_0|>
async def _parse_value(self, respon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CxSASTSecurityWarnings:
"""Collector class to measure the number of security warnings in a Checkmarx CxSAST scan."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to get the scan results."""
await super()._get_source_responses(*urls)
stats_api = U... | the_stack_v2_python_sparse | components/collector/src/source_collectors/cxsast/security_warnings.py | ICTU/quality-time | train | 43 |
92eefe700a58dd9ded49125a17f3a50c9472e724 | [
"self._input_model_blueprint = input_model_blueprint\nif 'galaxy_selection_func' in kwargs.keys():\n self.galaxy_selection_func = kwargs['galaxy_selection_func']",
"if hasattr(self, 'mock'):\n self.mock.populate()\nelse:\n if 'snapshot' in kwargs.keys():\n snapshot = kwargs['snapshot']\n de... | <|body_start_0|>
self._input_model_blueprint = input_model_blueprint
if 'galaxy_selection_func' in kwargs.keys():
self.galaxy_selection_func = kwargs['galaxy_selection_func']
<|end_body_0|>
<|body_start_1|>
if hasattr(self, 'mock'):
self.mock.populate()
else:
... | Abstract container class used to build any composite model of the galaxy-halo connection. | ModelFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelFactory:
"""Abstract container class used to build any composite model of the galaxy-halo connection."""
def __init__(self, input_model_blueprint, **kwargs):
"""Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite mod... | stack_v2_sparse_classes_75kplus_train_071325 | 28,353 | permissive | [
{
"docstring": "Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite model from a set of components. galaxy_selection_func : function object, optional keyword argument Function object that imposes a cut on the mock galaxies. Function should take an A... | 2 | stack_v2_sparse_classes_30k_train_015608 | Implement the Python class `ModelFactory` described below.
Class description:
Abstract container class used to build any composite model of the galaxy-halo connection.
Method signatures and docstrings:
- def __init__(self, input_model_blueprint, **kwargs): Parameters ---------- input_model_blueprint : dict Blueprint ... | Implement the Python class `ModelFactory` described below.
Class description:
Abstract container class used to build any composite model of the galaxy-halo connection.
Method signatures and docstrings:
- def __init__(self, input_model_blueprint, **kwargs): Parameters ---------- input_model_blueprint : dict Blueprint ... | f63988f7e1d66c7c19d7c2b4d628ed2524b7aec1 | <|skeleton|>
class ModelFactory:
"""Abstract container class used to build any composite model of the galaxy-halo connection."""
def __init__(self, input_model_blueprint, **kwargs):
"""Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelFactory:
"""Abstract container class used to build any composite model of the galaxy-halo connection."""
def __init__(self, input_model_blueprint, **kwargs):
"""Parameters ---------- input_model_blueprint : dict Blueprint providing instructions for how to build the composite model from a set... | the_stack_v2_python_sparse | halotools/empirical_models/model_factories.py | lanakurdi/halotools | train | 1 |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/admissions-cost/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)",
"url = '/admissions-cost/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.statu... | <|body_start_0|>
url = '/admissions-cost/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
url = '/admissions-cost/'
self.client.login(username=self.adminUN, password='pass')
response... | AdmissionsCostTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdmissionsCostTestCase:
def test_not_logged_in(self):
"""Test that the admissions costs view will not load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the admissions costs view will load whilst logged in as admin."""
<|bod... | stack_v2_sparse_classes_75kplus_train_071326 | 26,818 | permissive | [
{
"docstring": "Test that the admissions costs view will not load whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the admissions costs view will load whilst logged in as admin.",
"name": "test_logged_in_admin",
... | 3 | stack_v2_sparse_classes_30k_train_018096 | Implement the Python class `AdmissionsCostTestCase` described below.
Class description:
Implement the AdmissionsCostTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the admissions costs view will not load whilst not logged in.
- def test_logged_in_admin(self): Test that the ... | Implement the Python class `AdmissionsCostTestCase` described below.
Class description:
Implement the AdmissionsCostTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the admissions costs view will not load whilst not logged in.
- def test_logged_in_admin(self): Test that the ... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class AdmissionsCostTestCase:
def test_not_logged_in(self):
"""Test that the admissions costs view will not load whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the admissions costs view will load whilst logged in as admin."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdmissionsCostTestCase:
def test_not_logged_in(self):
"""Test that the admissions costs view will not load whilst not logged in."""
url = '/admissions-cost/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
def test_lo... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
0b0a299a2615580e74bd93e29d8c0ffeefdc7cfd | [
"serial = ''\n\ndef helper(nd):\n if nd == None:\n return 'None,'\n return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)\nreturn helper(root)",
"lst = data.split(',')\n\ndef helper(lst):\n if lst[0] == 'None':\n lst.pop(0)\n return None\n root = TreeNode(lst[0])\n lst.... | <|body_start_0|>
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return helper(root)
<|end_body_0|>
<|body_start_1|>
lst = data.split(',')
def helper(lst):
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071327 | 1,477 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_052183 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return he... | the_stack_v2_python_sparse | leetcode/297.py | liuweilin17/algorithm | train | 3 | |
62e1b3920cfb42c82371c959dcab2fee493d3d9a | [
"self.n_rows = n_rows\nself.n_cols = n_cols\nself.num = []\nfor i in range(n_rows):\n self.num.append([0] * n_cols)",
"sum_num = sum((sum(i) for i in self.num))\nif sum_num == self.n_rows * self.n_cols:\n return\nimport random\nwhile True:\n x = random.randint(0, self.n_rows - 1)\n y = random.randint(... | <|body_start_0|>
self.n_rows = n_rows
self.n_cols = n_cols
self.num = []
for i in range(n_rows):
self.num.append([0] * n_cols)
<|end_body_0|>
<|body_start_1|>
sum_num = sum((sum(i) for i in self.num))
if sum_num == self.n_rows * self.n_cols:
retur... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
<|body_0|>
def flip(self):
""":rtype: List[int]"""
<|body_1|>
def reset(self):
""":rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071328 | 1,777 | no_license | [
{
"docstring": ":type n_rows: int :type n_cols: int",
"name": "__init__",
"signature": "def __init__(self, n_rows, n_cols)"
},
{
"docstring": ":rtype: List[int]",
"name": "flip",
"signature": "def flip(self)"
},
{
"docstring": ":rtype: None",
"name": "reset",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_045135 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, n_rows, n_cols): :type n_rows: int :type n_cols: int
- def flip(self): :rtype: List[int]
- def reset(self): :rtype: None | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, n_rows, n_cols): :type n_rows: int :type n_cols: int
- def flip(self): :rtype: List[int]
- def reset(self): :rtype: None
<|skeleton|>
class Solution1:
... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
<|body_0|>
def flip(self):
""":rtype: List[int]"""
<|body_1|>
def reset(self):
""":rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
self.n_rows = n_rows
self.n_cols = n_cols
self.num = []
for i in range(n_rows):
self.num.append([0] * n_cols)
def flip(self):
""":rtype: List[int]"""
... | the_stack_v2_python_sparse | 2019/sampling/random_flip_matrix_519.py | yehongyu/acode | train | 0 | |
246c70d89036368a2ebd2027b7546e71348a3e80 | [
"d = {}\nfor n in nums:\n v = d.get(n)\n if not v:\n d[n] = 1\n else:\n d = n\n break\nl = sum(range(len(nums) + 1)) - sum(nums) + d\nreturn [d, l]",
"total = sum(range(len(nums) + 1))\nl = total - sum(set(nums))\nd = sum(nums) + l - total\nreturn [d, l]",
"bitmap = [0] * 10001\nfo... | <|body_start_0|>
d = {}
for n in nums:
v = d.get(n)
if not v:
d[n] = 1
else:
d = n
break
l = sum(range(len(nums) + 1)) - sum(nums) + d
return [d, l]
<|end_body_0|>
<|body_start_1|>
total = sum(ra... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def __findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findErrorNums(self, nums):
""":type nums: List[int] :... | stack_v2_sparse_classes_75kplus_train_071329 | 2,020 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "_findErrorNums",
"signature": "def _findErrorNums(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "__findErrorNums",
"signature": "def __findErrorNums(self, nums)"
},
{
"docstring... | 3 | stack_v2_sparse_classes_30k_train_040193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def __findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def findErrorNums(self, nums)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def __findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def findErrorNums(self, nums)... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def __findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findErrorNums(self, nums):
""":type nums: List[int] :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
d = {}
for n in nums:
v = d.get(n)
if not v:
d[n] = 1
else:
d = n
break
l = sum(range(len(nums) + 1)) - su... | the_stack_v2_python_sparse | 645.set-mismatch.py | windard/leeeeee | train | 0 | |
7e62e6c49f8f2778fee55552069eed9614fe3032 | [
"def int_to_str(num):\n sb = [chr(num >> i * 8 & 255) for i in range(4)]\n sb.reverse()\n return ''.join(sb)\npreorder = []\n\ndef helper(node):\n if node:\n preorder.append(int_to_str(node.val))\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn ''.join(preorder)",
"d... | <|body_start_0|>
def int_to_str(num):
sb = [chr(num >> i * 8 & 255) for i in range(4)]
sb.reverse()
return ''.join(sb)
preorder = []
def helper(node):
if node:
preorder.append(int_to_str(node.val))
helper(node.left)... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def int_to_str... | stack_v2_sparse_classes_75kplus_train_071330 | 4,762 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_033263 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def int_to_str(num):
sb = [chr(num >> i * 8 & 255) for i in range(4)]
sb.reverse()
return ''.join(sb)
preorder = []
def helper(node):
if ... | the_stack_v2_python_sparse | leet/amazon/trees_and_graphs/449_serialize_and_deserialize_BST.py | arsamigullin/problem_solving_python | train | 0 | |
45cfc0a87baed79af5a973d82283a4eaab4b0b5e | [
"ethernet_interfaces_mac = list(self._get_mac_address(task).values())\ninspect_utils.create_ports_if_not_exist(task, ethernet_interfaces_mac)\nreturn super(DracRedfishInspect, self).inspect_hardware(task)",
"system = redfish_utils.get_system(task.node)\nif system.ethernet_interfaces and system.ethernet_interfaces... | <|body_start_0|>
ethernet_interfaces_mac = list(self._get_mac_address(task).values())
inspect_utils.create_ports_if_not_exist(task, ethernet_interfaces_mac)
return super(DracRedfishInspect, self).inspect_hardware(task)
<|end_body_0|>
<|body_start_1|>
system = redfish_utils.get_system(ta... | iDRAC Redfish interface for inspection-related actions. | DracRedfishInspect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DracRedfishInspect:
"""iDRAC Redfish interface for inspection-related actions."""
def inspect_hardware(self, task):
"""Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails if any of the essential properties are not received from... | stack_v2_sparse_classes_75kplus_train_071331 | 14,244 | permissive | [
{
"docstring": "Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails if any of the essential properties are not received from the node. :param task: a TaskManager instance. :raises: HardwareInspectionFailure if essential properties could not be retrieved s... | 3 | null | Implement the Python class `DracRedfishInspect` described below.
Class description:
iDRAC Redfish interface for inspection-related actions.
Method signatures and docstrings:
- def inspect_hardware(self, task): Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails... | Implement the Python class `DracRedfishInspect` described below.
Class description:
iDRAC Redfish interface for inspection-related actions.
Method signatures and docstrings:
- def inspect_hardware(self, task): Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails... | ab76ff12e1c3c2208455e917f1a40d4000b4e990 | <|skeleton|>
class DracRedfishInspect:
"""iDRAC Redfish interface for inspection-related actions."""
def inspect_hardware(self, task):
"""Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails if any of the essential properties are not received from... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DracRedfishInspect:
"""iDRAC Redfish interface for inspection-related actions."""
def inspect_hardware(self, task):
"""Inspect hardware to get the hardware properties. Inspects hardware to get the essential properties. It fails if any of the essential properties are not received from the node. :p... | the_stack_v2_python_sparse | ironic/drivers/modules/drac/inspect.py | openstack/ironic | train | 411 |
4c9ddc920fa1098aa98105789cdcbdd77a00f072 | [
"self.driver.get(url)\ntime.sleep(1)\nself.driver.find_element_by_xpath(clean_close).click()\ntime.sleep(1)\nself.driver.find_element_by_xpath(add_data).click()\nwindows = self.driver.window_handles\nself.driver.switch_to_window(windows[-1])\ntime.sleep(1)\nvalue = self.driver.find_element_by_id(requiredDom).is_ena... | <|body_start_0|>
self.driver.get(url)
time.sleep(1)
self.driver.find_element_by_xpath(clean_close).click()
time.sleep(1)
self.driver.find_element_by_xpath(add_data).click()
windows = self.driver.window_handles
self.driver.switch_to_window(windows[-1])
time... | DataCleaningTrigger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCleaningTrigger:
def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom):
"""数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__data_source_jumpetl' :return: 布尔,True/False;存在/不存在"""
<|body_0|>
def get_datacleaning_trigger_p... | stack_v2_sparse_classes_75kplus_train_071332 | 2,612 | no_license | [
{
"docstring": "数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__data_source_jumpetl' :return: 布尔,True/False;存在/不存在",
"name": "get_datacleaning_trigger_jumpetl_id",
"signature": "def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_048524 | Implement the Python class `DataCleaningTrigger` described below.
Class description:
Implement the DataCleaningTrigger class.
Method signatures and docstrings:
- def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom): 数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__... | Implement the Python class `DataCleaningTrigger` described below.
Class description:
Implement the DataCleaningTrigger class.
Method signatures and docstrings:
- def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom): 数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__... | 22927e1101efa219e526dcd9b70f519bb6bd9553 | <|skeleton|>
class DataCleaningTrigger:
def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom):
"""数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__data_source_jumpetl' :return: 布尔,True/False;存在/不存在"""
<|body_0|>
def get_datacleaning_trigger_p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataCleaningTrigger:
def get_datacleaning_trigger_jumpetl_id(self, url, requiredDom):
"""数据源—触发器,打开浏览器,访问url获取元素值 :param url: 触发器请求接口后,访问url地址 :param requiredDom: Dom树中id值 新增数据:'__data_source_jumpetl' :return: 布尔,True/False;存在/不存在"""
self.driver.get(url)
time.sleep(1)
self.driv... | the_stack_v2_python_sparse | apm_modules/data_cleaning_trigger.py | mentgmery/interface_testing | train | 0 | |
6fd479b4ad064a3851a7abe08fe12bea95a3690a | [
"if logger is None:\n logger = InferLogger(args.log_path)\noutput_data_dir = None\nmodel_path = args.model_file\nparam_path = args.params_file\ncfg = CommonFunc.get_framework_config(model_path, args)\nif args.input_data_file is not None:\n input_data_map = np.load(args.input_data_file, allow_pickle=True).item... | <|body_start_0|>
if logger is None:
logger = InferLogger(args.log_path)
output_data_dir = None
model_path = args.model_file
param_path = args.params_file
cfg = CommonFunc.get_framework_config(model_path, args)
if args.input_data_file is not None:
i... | functions for model easy infer | EasyInfer | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EasyInfer:
"""functions for model easy infer"""
def easy_infer(args, logger=None):
"""model easy infer"""
<|body_0|>
def ms_dynamic_input_infer(args, logger=None):
"""conduct dynamic shape mindspore lite model infer"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_071333 | 3,725 | permissive | [
{
"docstring": "model easy infer",
"name": "easy_infer",
"signature": "def easy_infer(args, logger=None)"
},
{
"docstring": "conduct dynamic shape mindspore lite model infer",
"name": "ms_dynamic_input_infer",
"signature": "def ms_dynamic_input_infer(args, logger=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023425 | Implement the Python class `EasyInfer` described below.
Class description:
functions for model easy infer
Method signatures and docstrings:
- def easy_infer(args, logger=None): model easy infer
- def ms_dynamic_input_infer(args, logger=None): conduct dynamic shape mindspore lite model infer | Implement the Python class `EasyInfer` described below.
Class description:
functions for model easy infer
Method signatures and docstrings:
- def easy_infer(args, logger=None): model easy infer
- def ms_dynamic_input_infer(args, logger=None): conduct dynamic shape mindspore lite model infer
<|skeleton|>
class EasyIn... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class EasyInfer:
"""functions for model easy infer"""
def easy_infer(args, logger=None):
"""model easy infer"""
<|body_0|>
def ms_dynamic_input_infer(args, logger=None):
"""conduct dynamic shape mindspore lite model infer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EasyInfer:
"""functions for model easy infer"""
def easy_infer(args, logger=None):
"""model easy infer"""
if logger is None:
logger = InferLogger(args.log_path)
output_data_dir = None
model_path = args.model_file
param_path = args.params_file
cf... | the_stack_v2_python_sparse | mindspore/lite/tools/mslite_bench/mslite_bench/tools/easy_infer.py | mindspore-ai/mindspore | train | 4,178 |
e3c4badf4b9945bcaf8736aff07cdead5ee2474f | [
"self.data = data\nself.max_counters = data.IntAt(8)\nself.max_threads = data.IntAt(12)\nself.counter_names_offset = self._HEADER_SIZE + self.max_threads * (self._THREAD_NAME_SIZE + 2 * 4)\nself.counter_values_offset = self.counter_names_offset + self.max_counters * self._COUNTER_NAME_SIZE",
"for i in range(self.... | <|body_start_0|>
self.data = data
self.max_counters = data.IntAt(8)
self.max_threads = data.IntAt(12)
self.counter_names_offset = self._HEADER_SIZE + self.max_threads * (self._THREAD_NAME_SIZE + 2 * 4)
self.counter_values_offset = self.counter_names_offset + self.max_counters * s... | An overlay over a counters file that provides access to the individual counters contained in the file. | ChromeCounterCollection | [
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChromeCounterCollection:
"""An overlay over a counters file that provides access to the individual counters contained in the file."""
def __init__(self, data):
"""Create a new instance. Args: data: the shared data access object"""
<|body_0|>
def CountersInUse(self):
... | stack_v2_sparse_classes_75kplus_train_071334 | 15,097 | permissive | [
{
"docstring": "Create a new instance. Args: data: the shared data access object",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Return the number of counters in active use.",
"name": "CountersInUse",
"signature": "def CountersInUse(self)"
},
{
"d... | 3 | null | Implement the Python class `ChromeCounterCollection` described below.
Class description:
An overlay over a counters file that provides access to the individual counters contained in the file.
Method signatures and docstrings:
- def __init__(self, data): Create a new instance. Args: data: the shared data access object... | Implement the Python class `ChromeCounterCollection` described below.
Class description:
An overlay over a counters file that provides access to the individual counters contained in the file.
Method signatures and docstrings:
- def __init__(self, data): Create a new instance. Args: data: the shared data access object... | 43c40535cee37fc7349a21793dc33b1833735af5 | <|skeleton|>
class ChromeCounterCollection:
"""An overlay over a counters file that provides access to the individual counters contained in the file."""
def __init__(self, data):
"""Create a new instance. Args: data: the shared data access object"""
<|body_0|>
def CountersInUse(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChromeCounterCollection:
"""An overlay over a counters file that provides access to the individual counters contained in the file."""
def __init__(self, data):
"""Create a new instance. Args: data: the shared data access object"""
self.data = data
self.max_counters = data.IntAt(8)... | the_stack_v2_python_sparse | 3rdParty/V8/v7.9.317/tools/stats-viewer.py | arangodb/arangodb | train | 13,385 |
ac62250893662331f6163344df03bcaf5c3fd14d | [
"ssh = SSH()\nssh.connect(node)\ncmd = u\"cat /proc/`pidof vpp`/task/*/stat | grep -i vpp_wk | awk '{print $1}'\"\nfor _ in range(3):\n ret, out, _ = ssh.exec_command_sudo(cmd)\n if ret == 0:\n try:\n if not out:\n raise ValueError\n except ValueError:\n prin... | <|body_start_0|>
ssh = SSH()
ssh.connect(node)
cmd = u"cat /proc/`pidof vpp`/task/*/stat | grep -i vpp_wk | awk '{print $1}'"
for _ in range(3):
ret, out, _ = ssh.exec_command_sudo(cmd)
if ret == 0:
try:
if not out:
... | General class for any linux scheduler related methods/functions. | SchedUtils | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedUtils:
"""General class for any linux scheduler related methods/functions."""
def set_vpp_scheduling_rr(node):
"""Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node with running VPP. :type node: dict :raises RuntimeError:... | stack_v2_sparse_classes_75kplus_train_071335 | 3,772 | permissive | [
{
"docstring": "Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node with running VPP. :type node: dict :raises RuntimeError: Failed to retrieve PID for VPP worker threads.",
"name": "set_vpp_scheduling_rr",
"signature": "def set_vpp_scheduling_rr(... | 3 | stack_v2_sparse_classes_30k_train_054162 | Implement the Python class `SchedUtils` described below.
Class description:
General class for any linux scheduler related methods/functions.
Method signatures and docstrings:
- def set_vpp_scheduling_rr(node): Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node... | Implement the Python class `SchedUtils` described below.
Class description:
General class for any linux scheduler related methods/functions.
Method signatures and docstrings:
- def set_vpp_scheduling_rr(node): Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class SchedUtils:
"""General class for any linux scheduler related methods/functions."""
def set_vpp_scheduling_rr(node):
"""Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node with running VPP. :type node: dict :raises RuntimeError:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchedUtils:
"""General class for any linux scheduler related methods/functions."""
def set_vpp_scheduling_rr(node):
"""Set real-time scheduling attributes of VPP worker threads to SCHED_RR with priority 1. :param node: DUT node with running VPP. :type node: dict :raises RuntimeError: Failed to re... | the_stack_v2_python_sparse | resources/libraries/python/SchedUtils.py | FDio/csit | train | 28 |
401f469d870af734a199eb7395b4c9fd190a5245 | [
"logger.info(f'Trainer arguments: {pl_trainer_args}')\nif pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):\n pl_trainer_args['resume_from_checkpoint'] = None\npl_trainer_args['callbacks'] = {'model_checkpoint_callback': {'save_top_k': pl... | <|body_start_0|>
logger.info(f'Trainer arguments: {pl_trainer_args}')
if pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):
pl_trainer_args['resume_from_checkpoint'] = None
pl_trainer_args['callbacks'] = {'mode... | gflownet training pipelines. | GFlowNetTrainingPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_75kplus_train_071336 | 16,893 | permissive | [
{
"docstring": "Generic training function for PyTorch Lightning-based training. Args: pl_trainer_args: pytorch lightning trainer arguments passed to the configuration. model_args: model arguments passed to the configuration. dataset_args: dataset arguments passed to the configuration. dataset: dataset to be use... | 2 | stack_v2_sparse_classes_30k_train_026698 | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvContext, task: GF... | the_stack_v2_python_sparse | src/gt4sd/training_pipelines/pytorch_lightning/gflownet/core.py | GT4SD/gt4sd-core | train | 239 |
4e3ff0902128eeca767484bca9c075a864c45dc7 | [
"adm = Businesslogic()\nproposal = Studentprofile.from_dict(api.payload)\nif proposal is not None:\n p = adm.create_profile(proposal.get_first_name(), proposal.get_last_name(), proposal.get_age(), proposal.get_semester(), proposal.get_major(), proposal.get_hobbys(), proposal.get_interests(), proposal.get_persona... | <|body_start_0|>
adm = Businesslogic()
proposal = Studentprofile.from_dict(api.payload)
if proposal is not None:
p = adm.create_profile(proposal.get_first_name(), proposal.get_last_name(), proposal.get_age(), proposal.get_semester(), proposal.get_major(), proposal.get_hobbys(), propo... | ProfilOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilOperations:
def post(self):
"""Anlegen eines neuen Profil-Objekts"""
<|body_0|>
def get(self):
"""Auslesen aller Profil Objekte"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = Businesslogic()
proposal = Studentprofile.from_dict(a... | stack_v2_sparse_classes_75kplus_train_071337 | 21,726 | no_license | [
{
"docstring": "Anlegen eines neuen Profil-Objekts",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Auslesen aller Profil Objekte",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052095 | Implement the Python class `ProfilOperations` described below.
Class description:
Implement the ProfilOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Profil-Objekts
- def get(self): Auslesen aller Profil Objekte | Implement the Python class `ProfilOperations` described below.
Class description:
Implement the ProfilOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Profil-Objekts
- def get(self): Auslesen aller Profil Objekte
<|skeleton|>
class ProfilOperations:
def post(self):
... | 875be28ff076447b7dee8bf1e603ed72d3b767bc | <|skeleton|>
class ProfilOperations:
def post(self):
"""Anlegen eines neuen Profil-Objekts"""
<|body_0|>
def get(self):
"""Auslesen aller Profil Objekte"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfilOperations:
def post(self):
"""Anlegen eines neuen Profil-Objekts"""
adm = Businesslogic()
proposal = Studentprofile.from_dict(api.payload)
if proposal is not None:
p = adm.create_profile(proposal.get_first_name(), proposal.get_last_name(), proposal.get_age(),... | the_stack_v2_python_sparse | Software-Praktikum/src/main.py | khadidja-kebaili/Software-Praktikum | train | 1 | |
8765421593f2c705f1caf58fbb3f6bc67c327a8e | [
"best_value = -1.0\nactions = state.actions()\nif not actions:\n actions = [None]\nbest_move = actions[0]\nfor action in actions:\n result_state = state.result(action)\n value = self.evaluate(result_state, state.player_row)\n if value > best_value:\n best_value = value\n best_move = action... | <|body_start_0|>
best_value = -1.0
actions = state.actions()
if not actions:
actions = [None]
best_move = actions[0]
for action in actions:
result_state = state.result(action)
value = self.evaluate(result_state, state.player_row)
if... | EvaluationPlayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluationPlayer:
def move(self, state):
"""Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :return: Action, the next move"""
<|body_0|>
def evaluate(self, state, my_row):
"""Eva... | stack_v2_sparse_classes_75kplus_train_071338 | 2,039 | no_license | [
{
"docstring": "Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :return: Action, the next move",
"name": "move",
"signature": "def move(self, state)"
},
{
"docstring": "Evaluates the state for the player wit... | 2 | stack_v2_sparse_classes_30k_train_036118 | Implement the Python class `EvaluationPlayer` described below.
Class description:
Implement the EvaluationPlayer class.
Method signatures and docstrings:
- def move(self, state): Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :r... | Implement the Python class `EvaluationPlayer` described below.
Class description:
Implement the EvaluationPlayer class.
Method signatures and docstrings:
- def move(self, state): Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :r... | 87d22f90da3cfcf2c9ba5aa6bb7fc6a5d9ec9633 | <|skeleton|>
class EvaluationPlayer:
def move(self, state):
"""Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :return: Action, the next move"""
<|body_0|>
def evaluate(self, state, my_row):
"""Eva... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvaluationPlayer:
def move(self, state):
"""Calculates the best move after 1-step look-ahead with a simple evaluation function. :param state: State, the current state of the board. :return: Action, the next move"""
best_value = -1.0
actions = state.actions()
if not actions:
... | the_stack_v2_python_sparse | assignment2/solutions/p3_evaluation_player.py | darmadoo/cse150 | train | 0 | |
a6acebb61291716f567fc716a84334a0552fcf38 | [
"if not request.user.is_superuser:\n return HttpResponseForbidden()\nreturn super(ConfigureView, self).get(request)",
"if not request.user.is_superuser:\n return HttpResponseForbidden()\nextension = ReviewBotExtension.instance\nshould_save = False\nnew_user = request.POST.get('reviewbot_user')\nif new_user:... | <|body_start_0|>
if not request.user.is_superuser:
return HttpResponseForbidden()
return super(ConfigureView, self).get(request)
<|end_body_0|>
<|body_start_1|>
if not request.user.is_superuser:
return HttpResponseForbidden()
extension = ReviewBotExtension.instan... | The basic "Configure" page for Review Bot. | ConfigureView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_75kplus_train_071339 | 11,244 | permissive | [
{
"docstring": "Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save the extension configuration. Args: request (django.http.Htt... | 3 | stack_v2_sparse_classes_30k_train_047925 | Implement the Python class `ConfigureView` described below.
Class description:
The basic "Configure" page for Review Bot.
Method signatures and docstrings:
- def get(self, request): Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The resp... | Implement the Python class `ConfigureView` described below.
Class description:
The basic "Configure" page for Review Bot.
Method signatures and docstrings:
- def get(self, request): Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The resp... | b59b566e127b5ef1b08f3189f1aa0194b7437d94 | <|skeleton|>
class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
if not request.user.is_superuser:
return ... | the_stack_v2_python_sparse | extension/reviewbotext/views.py | reviewboard/ReviewBot | train | 110 |
2e3eeca649645ee982fd26b56870a9d195479c91 | [
"with self._sync as sync:\n sync(_map(lambda x, y: self._call(*x, **y), sync.iterable))\nreturn self",
"_caller = _mc(name, *self._args, **self._kw)\n_call = partial(_invoke, caller=_caller)\nwith self._sync as sync:\n sync(_map(_call, sync.iterable))\nreturn self",
"with self._sync as sync:\n sync(_s(... | <|body_start_0|>
with self._sync as sync:
sync(_map(lambda x, y: self._call(*x, **y), sync.iterable))
return self
<|end_body_0|>
<|body_start_1|>
_caller = _mc(name, *self._args, **self._kw)
_call = partial(_invoke, caller=_caller)
with self._sync as sync:
... | map mixin | MappingMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MappingMixin:
"""map mixin"""
def each(self, _map=it.starmap):
"""invoke call with passed arguments, keywords in incoming things"""
<|body_0|>
def invoke(self, name, _mc=mc, _invoke=invoke, _map=ct.map):
"""invoke call on each incoming thing with passed arguments... | stack_v2_sparse_classes_75kplus_train_071340 | 7,294 | permissive | [
{
"docstring": "invoke call with passed arguments, keywords in incoming things",
"name": "each",
"signature": "def each(self, _map=it.starmap)"
},
{
"docstring": "invoke call on each incoming thing with passed arguments, keywords but return incoming thing instead if call returns None @param name... | 5 | stack_v2_sparse_classes_30k_val_000753 | Implement the Python class `MappingMixin` described below.
Class description:
map mixin
Method signatures and docstrings:
- def each(self, _map=it.starmap): invoke call with passed arguments, keywords in incoming things
- def invoke(self, name, _mc=mc, _invoke=invoke, _map=ct.map): invoke call on each incoming thing ... | Implement the Python class `MappingMixin` described below.
Class description:
map mixin
Method signatures and docstrings:
- def each(self, _map=it.starmap): invoke call with passed arguments, keywords in incoming things
- def invoke(self, name, _mc=mc, _invoke=invoke, _map=ct.map): invoke call on each incoming thing ... | c63a1a07a6df3371b56b616fcfbd717def7cdbc6 | <|skeleton|>
class MappingMixin:
"""map mixin"""
def each(self, _map=it.starmap):
"""invoke call with passed arguments, keywords in incoming things"""
<|body_0|>
def invoke(self, name, _mc=mc, _invoke=invoke, _map=ct.map):
"""invoke call on each incoming thing with passed arguments... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MappingMixin:
"""map mixin"""
def each(self, _map=it.starmap):
"""invoke call with passed arguments, keywords in incoming things"""
with self._sync as sync:
sync(_map(lambda x, y: self._call(*x, **y), sync.iterable))
return self
def invoke(self, name, _mc=mc, _inv... | the_stack_v2_python_sparse | twoq/mixins/mapping.py | pombredanne/twoq | train | 0 |
7cc907ffef8895ab5cfe319fa167da9ae290a35e | [
"super(ImportHaresFilesThread, self).__init__(parent)\nself.parent = parent\nself.update_progress_signal.connect(self.update_progress)\nself.update_tableview_signal.connect(self.parent.tableview.model.layoutChanged.emit)\nself.progress_bar = self.parent.import_progress\nself.error_signal.connect(show_thread_error)\... | <|body_start_0|>
super(ImportHaresFilesThread, self).__init__(parent)
self.parent = parent
self.update_progress_signal.connect(self.update_progress)
self.update_tableview_signal.connect(self.parent.tableview.model.layoutChanged.emit)
self.progress_bar = self.parent.import_progres... | Thread for importing Hares output files | ImportHaresFilesThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportHaresFilesThread:
"""Thread for importing Hares output files"""
def __init__(self, parent=None):
"""Construct"""
<|body_0|>
def update_progress(self, add_value):
"""Update progress bar"""
<|body_1|>
def run(self):
"""Method to: 1. Run i... | stack_v2_sparse_classes_75kplus_train_071341 | 12,561 | no_license | [
{
"docstring": "Construct",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Update progress bar",
"name": "update_progress",
"signature": "def update_progress(self, add_value)"
},
{
"docstring": "Method to: 1. Run import 2. Re-sort the tablev... | 3 | null | Implement the Python class `ImportHaresFilesThread` described below.
Class description:
Thread for importing Hares output files
Method signatures and docstrings:
- def __init__(self, parent=None): Construct
- def update_progress(self, add_value): Update progress bar
- def run(self): Method to: 1. Run import 2. Re-sor... | Implement the Python class `ImportHaresFilesThread` described below.
Class description:
Thread for importing Hares output files
Method signatures and docstrings:
- def __init__(self, parent=None): Construct
- def update_progress(self, add_value): Update progress bar
- def run(self): Method to: 1. Run import 2. Re-sor... | 2969cc0b61dc66c1a20236188cd9d85154bda48d | <|skeleton|>
class ImportHaresFilesThread:
"""Thread for importing Hares output files"""
def __init__(self, parent=None):
"""Construct"""
<|body_0|>
def update_progress(self, add_value):
"""Update progress bar"""
<|body_1|>
def run(self):
"""Method to: 1. Run i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportHaresFilesThread:
"""Thread for importing Hares output files"""
def __init__(self, parent=None):
"""Construct"""
super(ImportHaresFilesThread, self).__init__(parent)
self.parent = parent
self.update_progress_signal.connect(self.update_progress)
self.update_ta... | the_stack_v2_python_sparse | hbhavens/ui/threads.py | MPBenit/HB-Havens | train | 0 |
8eabd4e708ce7cbd5f206d1e084283d4ee98c391 | [
"self.node_1 = BinaryTree(1)\nself.node_2 = BinaryTree(2)\nself.node_3 = BinaryTree(3)\nself.node_4 = BinaryTree(4)\nself.node_5 = BinaryTree(5)\nself.node_6 = BinaryTree(6)\nself.node_7 = BinaryTree(7)\nself.node_8 = BinaryTree(8)\nself.node_1.left = self.node_2\nself.node_1.right = self.node_3\nself.node_2.left =... | <|body_start_0|>
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = BinaryTree(5)
self.node_6 = BinaryTree(6)
self.node_7 = BinaryTree(7)
self.node_8 = BinaryTree(8)
self.no... | Class with unittests for FindNodesDistanceK.py | test_FindNodesDistanceK | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.no... | stack_v2_sparse_classes_75kplus_train_071342 | 1,497 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if method works properly.",
"name": "test_user_input",
"signature": "def test_user_input(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034249 | Implement the Python class `test_FindNodesDistanceK` described below.
Class description:
Class with unittests for FindNodesDistanceK.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. | Implement the Python class `test_FindNodesDistanceK` described below.
Class description:
Class with unittests for FindNodesDistanceK.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly.
<|skeleton|>
class test_FindNodesDistanceK:
"""... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_FindNodesDistanceK:
"""Class with unittests for FindNodesDistanceK.py"""
def setUp(self):
"""Sets up input."""
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = BinaryTree(5)
... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/FindNodesDistanceK/test_FindNodesDIstanceK.py | JakubKazimierski/PythonPortfolio | train | 9 |
374ddb0a5cedf29a556d296713e528965e190400 | [
"self.app_data = {}\nfor pkg_index in app_dict:\n result = defaultdict(int)\n keywords = app_dict[pkg_index][0]\n for occupation, words_list in job_tags.items():\n for word in words_list:\n if keywords.find(word) >= 0:\n result[occupation] += 1\n break\n i... | <|body_start_0|>
self.app_data = {}
for pkg_index in app_dict:
result = defaultdict(int)
keywords = app_dict[pkg_index][0]
for occupation, words_list in job_tags.items():
for word in words_list:
if keywords.find(word) >= 0:
... | 职业预测 | JobPredict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobPredict:
"""职业预测"""
def __init__(self, job_tags, app_dict):
"""初始化 :param job_tags: {"sale": [], ....... "driver": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
<|body_0|>
def check_user(self, user_pkg_index_list):
"""检查一个用户的职业 :ret... | stack_v2_sparse_classes_75kplus_train_071343 | 1,656 | no_license | [
{
"docstring": "初始化 :param job_tags: {\"sale\": [], ....... \"driver\": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}",
"name": "__init__",
"signature": "def __init__(self, job_tags, app_dict)"
},
{
"docstring": "检查一个用户的职业 :return result: job",
"name": "check_user",
... | 2 | stack_v2_sparse_classes_30k_train_033244 | Implement the Python class `JobPredict` described below.
Class description:
职业预测
Method signatures and docstrings:
- def __init__(self, job_tags, app_dict): 初始化 :param job_tags: {"sale": [], ....... "driver": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}
- def check_user(self, user_pkg_index_... | Implement the Python class `JobPredict` described below.
Class description:
职业预测
Method signatures and docstrings:
- def __init__(self, job_tags, app_dict): 初始化 :param job_tags: {"sale": [], ....... "driver": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}
- def check_user(self, user_pkg_index_... | 2693b1262a15b66365ec6f1ffc3b6673a9d9760d | <|skeleton|>
class JobPredict:
"""职业预测"""
def __init__(self, job_tags, app_dict):
"""初始化 :param job_tags: {"sale": [], ....... "driver": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
<|body_0|>
def check_user(self, user_pkg_index_list):
"""检查一个用户的职业 :ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobPredict:
"""职业预测"""
def __init__(self, job_tags, app_dict):
"""初始化 :param job_tags: {"sale": [], ....... "driver": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
self.app_data = {}
for pkg_index in app_dict:
result = defaultdict(int)
... | the_stack_v2_python_sparse | predict/predict_job.py | walleleung/DemoGraphy | train | 0 |
5848c7a3291277a235b4ac8796a9afad7c07b358 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file | StockExchangeInformatorServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockExchangeInformatorServicer:
"""Missing associated documentation comment in .proto file"""
def observe(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def ping(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_75kplus_train_071344 | 3,896 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "observe",
"signature": "def observe(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "ping",
"signature": "def ping(self, request, context)"
}... | 2 | stack_v2_sparse_classes_30k_val_001082 | Implement the Python class `StockExchangeInformatorServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def observe(self, request, context): Missing associated documentation comment in .proto file
- def ping(self, request, context): ... | Implement the Python class `StockExchangeInformatorServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def observe(self, request, context): Missing associated documentation comment in .proto file
- def ping(self, request, context): ... | 5f40b562e3f757cd7892ff276b5875a16f9e313f | <|skeleton|>
class StockExchangeInformatorServicer:
"""Missing associated documentation comment in .proto file"""
def observe(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def ping(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StockExchangeInformatorServicer:
"""Missing associated documentation comment in .proto file"""
def observe(self, request, context):
"""Missing associated documentation comment in .proto file"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not impleme... | the_stack_v2_python_sparse | 4_1_stock_exchange/Server/generated/stock_exchange_pb2_grpc.py | j-adamczyk/Distributed_systems | train | 8 |
fa6d68732a5bbff555a03869f7a9515c91ccd8da | [
"logging.info('Opening file %s', filename)\nwith open(filename, 'r') as file:\n return list(map(str.strip, file.readlines()))",
"logging.info('Opening file %s', filename)\nwith open(filename, 'r') as file:\n return file.read()"
] | <|body_start_0|>
logging.info('Opening file %s', filename)
with open(filename, 'r') as file:
return list(map(str.strip, file.readlines()))
<|end_body_0|>
<|body_start_1|>
logging.info('Opening file %s', filename)
with open(filename, 'r') as file:
return file.read... | FileReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileReader:
def read_input_as_list(filename=DEFAULT_FILE_NAME):
"""This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: relative path to file"""
<|body_0|>
def read_input_as_string(filename=DEFAULT_FILE_NAME):... | stack_v2_sparse_classes_75kplus_train_071345 | 853 | permissive | [
{
"docstring": "This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: relative path to file",
"name": "read_input_as_list",
"signature": "def read_input_as_list(filename=DEFAULT_FILE_NAME)"
},
{
"docstring": "This method assumes we... | 2 | stack_v2_sparse_classes_30k_train_020287 | Implement the Python class `FileReader` described below.
Class description:
Implement the FileReader class.
Method signatures and docstrings:
- def read_input_as_list(filename=DEFAULT_FILE_NAME): This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: rel... | Implement the Python class `FileReader` described below.
Class description:
Implement the FileReader class.
Method signatures and docstrings:
- def read_input_as_list(filename=DEFAULT_FILE_NAME): This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: rel... | 7c67a07eccc6e07f56fc448e463c557c937a4aaa | <|skeleton|>
class FileReader:
def read_input_as_list(filename=DEFAULT_FILE_NAME):
"""This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: relative path to file"""
<|body_0|>
def read_input_as_string(filename=DEFAULT_FILE_NAME):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileReader:
def read_input_as_list(filename=DEFAULT_FILE_NAME):
"""This method assumes we are reading from the working directory, will return a list of the file's lines :param filename: relative path to file"""
logging.info('Opening file %s', filename)
with open(filename, 'r') as file:... | the_stack_v2_python_sparse | readers/file_reader.py | nbalas/advent_of_code | train | 0 | |
4f036063e42308c6850eda263cc318ee00187468 | [
"class TestPage(object):\n\n def index(self):\n return ''\nself.assertTrue(interfaces.has_index_method(TestPage()))",
"class TestPage(object):\n\n def action(self):\n pass\nself.assertFalse(interfaces.has_index_method(TestPage()))",
"class TestObject(object):\n pass\nself.assertFalse(inte... | <|body_start_0|>
class TestPage(object):
def index(self):
return ''
self.assertTrue(interfaces.has_index_method(TestPage()))
<|end_body_0|>
<|body_start_1|>
class TestPage(object):
def action(self):
pass
self.assertFalse(interfac... | TestHasIndexMethod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHasIndexMethod:
def test_has_index_method_true_index_method(self):
"""``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method."""
<|body_0|>
def test_has_index_method_false_action_method(self):
"""``has_index_method()`` shoul... | stack_v2_sparse_classes_75kplus_train_071346 | 9,745 | no_license | [
{
"docstring": "``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method.",
"name": "test_has_index_method_true_index_method",
"signature": "def test_has_index_method_true_index_method(self)"
},
{
"docstring": "``has_index_method()`` should return ``False`` i... | 3 | null | Implement the Python class `TestHasIndexMethod` described below.
Class description:
Implement the TestHasIndexMethod class.
Method signatures and docstrings:
- def test_has_index_method_true_index_method(self): ``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method.
- def test_h... | Implement the Python class `TestHasIndexMethod` described below.
Class description:
Implement the TestHasIndexMethod class.
Method signatures and docstrings:
- def test_has_index_method_true_index_method(self): ``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method.
- def test_h... | 001dcb8e7476b4ee2b3b8d734910829f2bd907bc | <|skeleton|>
class TestHasIndexMethod:
def test_has_index_method_true_index_method(self):
"""``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method."""
<|body_0|>
def test_has_index_method_false_action_method(self):
"""``has_index_method()`` shoul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHasIndexMethod:
def test_has_index_method_true_index_method(self):
"""``has_index_method()`` should return ``True`` if its argument has an ``index()`` bound method."""
class TestPage(object):
def index(self):
return ''
self.assertTrue(interfaces.has_ind... | the_stack_v2_python_sparse | confeitaria_tests/interfaces.py | confeitaria/confeitaria | train | 0 | |
0ae6229273ce5fbbde426a7c5fcdd788f95e287c | [
"self.factory = RequestFactory()\nself.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password=\"Abdullah's passwd\")\nself.trip = Trip.objects.create(title='Summer Break', passenger=self.user, arrive_at='BOS', terminal='G')",
"get_request = self.factory.get('trips/2/')\nresponse = TripDet... | <|body_start_0|>
self.factory = RequestFactory()
self.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password="Abdullah's passwd")
self.trip = Trip.objects.create(title='Summer Break', passenger=self.user, arrive_at='BOS', terminal='G')
<|end_body_0|>
<|body_start_1|>
... | Tests for the TripDetail view. | TripDetailTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripDetailTests:
"""Tests for the TripDetail view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns: None"""
<|body_0|>
def test_get_details_fo... | stack_v2_sparse_classes_75kplus_train_071347 | 10,206 | permissive | [
{
"docstring": "Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns: None",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "A user sees instructions for a Trip on its details ... | 2 | stack_v2_sparse_classes_30k_train_047483 | Implement the Python class `TripDetailTests` described below.
Class description:
Tests for the TripDetail view.
Method signatures and docstrings:
- def setUp(self): Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns... | Implement the Python class `TripDetailTests` described below.
Class description:
Tests for the TripDetail view.
Method signatures and docstrings:
- def setUp(self): Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns... | 65d933c64a3bf830f51ac237f5781ddfb69f342c | <|skeleton|>
class TripDetailTests:
"""Tests for the TripDetail view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns: None"""
<|body_0|>
def test_get_details_fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TripDetailTests:
"""Tests for the TripDetail view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripDetail view. Parameters: self(TripDetailTests): the calling object Returns: None"""
self.factory = RequestFactory()
self.user = ... | the_stack_v2_python_sparse | travelly/trips/tests.py | UPstartDeveloper/fiercely-souvenir | train | 0 |
1961a008c00fd86bdd7647e8601b00789cb0a6d4 | [
"if not customfield:\n return TicketSystem(self.env).get_custom_fields()\nelse:\n all = TicketSystem(self.env).get_custom_fields()\n for item in all:\n if item['name'] == customfield['name']:\n return item\n return None",
"if not (customfield.get('name') and customfield.get('type') a... | <|body_start_0|>
if not customfield:
return TicketSystem(self.env).get_custom_fields()
else:
all = TicketSystem(self.env).get_custom_fields()
for item in all:
if item['name'] == customfield['name']:
return item
return No... | These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) Input to methods is a 'customfield' dict supporting these keys: name = name of ... | CustomFields | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomFields:
"""These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) Input to methods is a 'customfield' dic... | stack_v2_sparse_classes_75kplus_train_071348 | 6,714 | permissive | [
{
"docstring": "Returns the custom fields from TicketSystem component. Use a cfdict with 'name' key set to find a specific custom field only.",
"name": "get_custom_fields",
"signature": "def get_custom_fields(self, customfield=None)"
},
{
"docstring": "Basic validation of the input for modifying... | 5 | stack_v2_sparse_classes_30k_train_053588 | Implement the Python class `CustomFields` described below.
Class description:
These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) ... | Implement the Python class `CustomFields` described below.
Class description:
These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) ... | e6335c264e7a9a2e961e9a72db3660c2da1c24e3 | <|skeleton|>
class CustomFields:
"""These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) Input to methods is a 'customfield' dic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomFields:
"""These methods should be part of TicketSystem API/Data Model. Adds update_custom_field and delete_custom_field methods. (The get_custom_fields is already part of the API - just redirect here, and add option to only get one named field back.) Input to methods is a 'customfield' dict supporting ... | the_stack_v2_python_sparse | resource/trac-plugins/customfieldadmin/customfieldadmin/api.py | okamototk/kanonconductor | train | 0 |
99471dc8d8095ae4c2b829f35bee4b4dd6dc7bf4 | [
"self._file_path = file_path\nself._nbd_path = '/dev/nbd' + str(LoadNbdImage.nbd_port % 16)\nLoadNbdImage.nbd_port = (LoadNbdImage.nbd_port + 1) % 16",
"mountpath = self._nbd_path\nlogging.debug('Starting qemu block device emulation ' + mountpath + ' from image ' + self._file_path)\nmodprobe_cmd = ['modprobe', 'n... | <|body_start_0|>
self._file_path = file_path
self._nbd_path = '/dev/nbd' + str(LoadNbdImage.nbd_port % 16)
LoadNbdImage.nbd_port = (LoadNbdImage.nbd_port + 1) % 16
<|end_body_0|>
<|body_start_1|>
mountpath = self._nbd_path
logging.debug('Starting qemu block device emulation ' + ... | Mounts virtual disk via qemu-nbd | LoadNbdImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
<|body_0|>
def __enter__(self):
"""Map disk image as a... | stack_v2_sparse_classes_75kplus_train_071349 | 8,532 | no_license | [
{
"docstring": "Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open",
"name": "__init__",
"signature": "def __init__(self, file_path)"
},
{
"docstring": "Map disk image as a device.",
"name": "__enter__",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_041405 | Implement the Python class `LoadNbdImage` described below.
Class description:
Mounts virtual disk via qemu-nbd
Method signatures and docstrings:
- def __init__(self, file_path): Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open
- def __enter__(self)... | Implement the Python class `LoadNbdImage` described below.
Class description:
Mounts virtual disk via qemu-nbd
Method signatures and docstrings:
- def __init__(self, file_path): Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open
- def __enter__(self)... | e01a7e11931a61ae91b9cadbc961d703f8c77925 | <|skeleton|>
class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
<|body_0|>
def __enter__(self):
"""Map disk image as a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadNbdImage:
"""Mounts virtual disk via qemu-nbd"""
def __init__(self, file_path):
"""Inits object Args: file_path: a path to a file containing virtual disk image. Returns: path to raw disk device to open"""
self._file_path = file_path
self._nbd_path = '/dev/nbd' + str(LoadNbdIma... | the_stack_v2_python_sparse | Migrate/Linux_GC/NbdBundle_utils.py | migrate2iaas/cloudscraper-engine | train | 1 |
dfc41e846b29df10336f25a683ef32085b1e83bf | [
"serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nSprinkleSchedule.objects.update_or_create(device=serializer.validated_data['device'], defaults=serializer.validated_data)\nreturn JsonResponse(serializer.data, status=status.HTTP_201_CREATED)",
"try:\n schedule = S... | <|body_start_0|>
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
SprinkleSchedule.objects.update_or_create(device=serializer.validated_data['device'], defaults=serializer.validated_data)
return JsonResponse(serializer.data, status=status.HTTP... | Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific. | ScheduleViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_071350 | 2,458 | no_license | [
{
"docstring": "Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation.",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Get the current scheduled sprinkle configuration. <br /> If the device does not have any configurat... | 3 | stack_v2_sparse_classes_30k_train_026924 | Implement the Python class `ScheduleViewSet` described below.
Class description:
Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Set the sprinkle schedule for one device <br /> This is an... | Implement the Python class `ScheduleViewSet` described below.
Class description:
Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Set the sprinkle schedule for one device <br /> This is an... | 58ac6554ee92f94130900d49b7d55dd30eabf9ab | <|skeleton|>
class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
serializer = self.get_serializer(... | the_stack_v2_python_sparse | aquas_web/devices/views/api/schedule.py | jaconsta/aquas_web | train | 0 |
13fc1f7a026ce95052f732439afba435ca9153b1 | [
"self.path = path\nself.out = out\nself.subsampleFactor = subsampleFactor\nif self.out != None:\n self.fileOut = self.out\n if os.path.splitext(self.fileOut)[-1] != '.mp4':\n self.fileOut = os.path.splitext(self.fileOut)[0] + '.mp4'\n if os.name == 'nt':\n self.out_video = imageio.get_writer(... | <|body_start_0|>
self.path = path
self.out = out
self.subsampleFactor = subsampleFactor
if self.out != None:
self.fileOut = self.out
if os.path.splitext(self.fileOut)[-1] != '.mp4':
self.fileOut = os.path.splitext(self.fileOut)[0] + '.mp4'
... | docstring for Visualizer. | Visualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Visualizer:
"""docstring for Visualizer."""
def __init__(self, path, subsampleFactor, out=None):
"""input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4"""
<|body_0|>
def getFilesNames(self):
"""Returns the .ply file names of ... | stack_v2_sparse_classes_75kplus_train_071351 | 3,315 | no_license | [
{
"docstring": "input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4",
"name": "__init__",
"signature": "def __init__(self, path, subsampleFactor, out=None)"
},
{
"docstring": "Returns the .ply file names of the point cloud sequence input: - subsampleFactor, ... | 3 | stack_v2_sparse_classes_30k_train_049155 | Implement the Python class `Visualizer` described below.
Class description:
docstring for Visualizer.
Method signatures and docstrings:
- def __init__(self, path, subsampleFactor, out=None): input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4
- def getFilesNames(self): Returns th... | Implement the Python class `Visualizer` described below.
Class description:
docstring for Visualizer.
Method signatures and docstrings:
- def __init__(self, path, subsampleFactor, out=None): input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4
- def getFilesNames(self): Returns th... | 5aa9891ea09e3e6a83c84ac89c75618ced377ba3 | <|skeleton|>
class Visualizer:
"""docstring for Visualizer."""
def __init__(self, path, subsampleFactor, out=None):
"""input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4"""
<|body_0|>
def getFilesNames(self):
"""Returns the .ply file names of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Visualizer:
"""docstring for Visualizer."""
def __init__(self, path, subsampleFactor, out=None):
"""input: - path, str: folder with decompressed .ply files - out, str: filePath to save .mp4"""
self.path = path
self.out = out
self.subsampleFactor = subsampleFactor
i... | the_stack_v2_python_sparse | visualizer.py | liaochen1/PCCCP | train | 0 |
36267fd9d4029e51e0abb639b8447bda224af1a8 | [
"try:\n data = {'filter': filter}\n response = self.service.get(self.request.uri, data)\n log.info('Widget GET request successfully. ')\n return self.success(response, 200)\nexcept Exception as e:\n log.error('Widget GET request Error.Exception: {0}. '.format(e))\n return self.error({'success': 0,... | <|body_start_0|>
try:
data = {'filter': filter}
response = self.service.get(self.request.uri, data)
log.info('Widget GET request successfully. ')
return self.success(response, 200)
except Exception as e:
log.error('Widget GET request Error.Exce... | WidgetHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WidgetHandler:
def get(self, filter=None):
"""Receives POST requests. :return:"""
<|body_0|>
def post(self):
"""Method POST to API restful widget :returns: json -- to sync requests (200) | empty string (""). :raises: Exception (500)"""
<|body_1|>
def put... | stack_v2_sparse_classes_75kplus_train_071352 | 4,852 | no_license | [
{
"docstring": "Receives POST requests. :return:",
"name": "get",
"signature": "def get(self, filter=None)"
},
{
"docstring": "Method POST to API restful widget :returns: json -- to sync requests (200) | empty string (\"\"). :raises: Exception (500)",
"name": "post",
"signature": "def po... | 4 | null | Implement the Python class `WidgetHandler` described below.
Class description:
Implement the WidgetHandler class.
Method signatures and docstrings:
- def get(self, filter=None): Receives POST requests. :return:
- def post(self): Method POST to API restful widget :returns: json -- to sync requests (200) | empty string... | Implement the Python class `WidgetHandler` described below.
Class description:
Implement the WidgetHandler class.
Method signatures and docstrings:
- def get(self, filter=None): Receives POST requests. :return:
- def post(self): Method POST to API restful widget :returns: json -- to sync requests (200) | empty string... | d062523116ff9af6e1731997213102deeb50ab3d | <|skeleton|>
class WidgetHandler:
def get(self, filter=None):
"""Receives POST requests. :return:"""
<|body_0|>
def post(self):
"""Method POST to API restful widget :returns: json -- to sync requests (200) | empty string (""). :raises: Exception (500)"""
<|body_1|>
def put... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WidgetHandler:
def get(self, filter=None):
"""Receives POST requests. :return:"""
try:
data = {'filter': filter}
response = self.service.get(self.request.uri, data)
log.info('Widget GET request successfully. ')
return self.success(response, 200)
... | the_stack_v2_python_sparse | modules/widgetsspa/v1/api/rest/widgets.py | gpsanches/redventures-backend | train | 0 | |
7f6727dc76877393ec43c03f00a97b4eeaf7c79e | [
"pressure = np.zeros(self.frequency.amount)\nfor subsystem in self.linked_subsystems:\n pressure = pressure + subsystem.pressure\nreturn pressure",
"try:\n return 20.0 * np.log10(self.pressure / (2.0 * 10 ** (-5.0)))\nexcept FloatingPointError:\n return np.zeros(self.frequency.amount)"
] | <|body_start_0|>
pressure = np.zeros(self.frequency.amount)
for subsystem in self.linked_subsystems:
pressure = pressure + subsystem.pressure
return pressure
<|end_body_0|>
<|body_start_1|>
try:
return 20.0 * np.log10(self.pressure / (2.0 * 10 ** (-5.0)))
... | Abstract base class for fluid components. | ComponentCavity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentCavity:
"""Abstract base class for fluid components."""
def pressure(self):
"""Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities."""
<|body_0|>
def pressure_level(self):
"""So... | stack_v2_sparse_classes_75kplus_train_071353 | 1,003 | no_license | [
{
"docstring": "Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities.",
"name": "pressure",
"signature": "def pressure(self)"
},
{
"docstring": "Sound pressure level :math:`L_p`. :rtype: :class:`numpy.ndarray` .. math:: ... | 2 | null | Implement the Python class `ComponentCavity` described below.
Class description:
Abstract base class for fluid components.
Method signatures and docstrings:
- def pressure(self): Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities.
- def pre... | Implement the Python class `ComponentCavity` described below.
Class description:
Abstract base class for fluid components.
Method signatures and docstrings:
- def pressure(self): Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities.
- def pre... | e30b6dc59d8ab02cd41924f7b6c14d0d1e77e19e | <|skeleton|>
class ComponentCavity:
"""Abstract base class for fluid components."""
def pressure(self):
"""Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities."""
<|body_0|>
def pressure_level(self):
"""So... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComponentCavity:
"""Abstract base class for fluid components."""
def pressure(self):
"""Pressure within the component :math:`p_{component}`. :rtype: :class:`numpy.ndarray` This is the sum of all subsystems velocities."""
pressure = np.zeros(self.frequency.amount)
for subsystem in ... | the_stack_v2_python_sparse | Sea/model/components/ComponentCavity.py | python-acoustics/Sea | train | 7 |
f1e090e8885f8292128621a3caf280f80891efae | [
"self.instance_generator = instance_generator\nself.labelset_ = {l: i for i, l in enumerate(labels, start=3)}\nself.labelset_[UNK] = 0\nself.labelset_[ROOT] = 1\nself.labelset_[UNRELATED] = 2\nself._zero = zero",
"zlabel = UNK if self._zero else UNRELATED\nfor doc in raw_documents:\n for pair in self.instance_... | <|body_start_0|>
self.instance_generator = instance_generator
self.labelset_ = {l: i for i, l in enumerate(labels, start=3)}
self.labelset_[UNK] = 0
self.labelset_[ROOT] = 1
self.labelset_[UNRELATED] = 2
self._zero = zero
<|end_body_0|>
<|body_start_1|>
zlabel = ... | Label extractor for the STAC corpus. | LabelVectorizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
<|body_0|>
def transform(self, raw_documents):
"""Lear... | stack_v2_sparse_classes_75kplus_train_071354 | 2,050 | no_license | [
{
"docstring": "instance_generator to enumerate the instances from a doc :type labels: set(string)",
"name": "__init__",
"signature": "def __init__(self, instance_generator, labels, zero=False)"
},
{
"docstring": "Learn the label encoder and return a vector of labels There is one label per insta... | 2 | stack_v2_sparse_classes_30k_train_015444 | Implement the Python class `LabelVectorizer` described below.
Class description:
Label extractor for the STAC corpus.
Method signatures and docstrings:
- def __init__(self, instance_generator, labels, zero=False): instance_generator to enumerate the instances from a doc :type labels: set(string)
- def transform(self,... | Implement the Python class `LabelVectorizer` described below.
Class description:
Label extractor for the STAC corpus.
Method signatures and docstrings:
- def __init__(self, instance_generator, labels, zero=False): instance_generator to enumerate the instances from a doc :type labels: set(string)
- def transform(self,... | c550f4383016e05fe20ad7180a027979e3540d1f | <|skeleton|>
class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
<|body_0|>
def transform(self, raw_documents):
"""Lear... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabelVectorizer:
"""Label extractor for the STAC corpus."""
def __init__(self, instance_generator, labels, zero=False):
"""instance_generator to enumerate the instances from a doc :type labels: set(string)"""
self.instance_generator = instance_generator
self.labelset_ = {l: i for ... | the_stack_v2_python_sparse | educe/stac/learning/doc_vectorizer.py | kowey/educe | train | 1 |
7b99b5cd20a0920839ff2417c9de55d45c41faa0 | [
"self.config = config\nself.skill_context = skill_context\nself.handlers = handlers if handlers is not None else {}\nself.behaviours = behaviours if behaviours is not None else {}\nself.models = models if models is not None else {}",
"skill_loader = ConfigLoader('skill-config_schema.json', SkillConfig)\nskill_con... | <|body_start_0|>
self.config = config
self.skill_context = skill_context
self.handlers = handlers if handlers is not None else {}
self.behaviours = behaviours if behaviours is not None else {}
self.models = models if models is not None else {}
<|end_body_0|>
<|body_start_1|>
... | This class implements a skill. | Skill | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Skill:
"""This class implements a skill."""
def __init__(self, config: SkillConfig, skill_context: SkillContext, handlers: Optional[Dict[str, Handler]], behaviours: Optional[Dict[str, Behaviour]], models: Optional[Dict[str, Model]]):
"""Initialize a skill. :param config: the skill co... | stack_v2_sparse_classes_75kplus_train_071355 | 20,903 | permissive | [
{
"docstring": "Initialize a skill. :param config: the skill configuration. :param handlers: the list of handlers to handle incoming envelopes. :param behaviours: the list of behaviours that defines the proactive component of the agent. :param models: the list of models shared across tasks, behaviours and",
... | 2 | null | Implement the Python class `Skill` described below.
Class description:
This class implements a skill.
Method signatures and docstrings:
- def __init__(self, config: SkillConfig, skill_context: SkillContext, handlers: Optional[Dict[str, Handler]], behaviours: Optional[Dict[str, Behaviour]], models: Optional[Dict[str, ... | Implement the Python class `Skill` described below.
Class description:
This class implements a skill.
Method signatures and docstrings:
- def __init__(self, config: SkillConfig, skill_context: SkillContext, handlers: Optional[Dict[str, Handler]], behaviours: Optional[Dict[str, Behaviour]], models: Optional[Dict[str, ... | bc4f65fc749e9cd628f3d0f91bba3d522bce82e4 | <|skeleton|>
class Skill:
"""This class implements a skill."""
def __init__(self, config: SkillConfig, skill_context: SkillContext, handlers: Optional[Dict[str, Handler]], behaviours: Optional[Dict[str, Behaviour]], models: Optional[Dict[str, Model]]):
"""Initialize a skill. :param config: the skill co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Skill:
"""This class implements a skill."""
def __init__(self, config: SkillConfig, skill_context: SkillContext, handlers: Optional[Dict[str, Handler]], behaviours: Optional[Dict[str, Behaviour]], models: Optional[Dict[str, Model]]):
"""Initialize a skill. :param config: the skill configuration. ... | the_stack_v2_python_sparse | aea/skills/base.py | greencultureai/agents-aea | train | 0 |
b5477b8ff69fc5094f669d728528991e390e9483 | [
"if nargs:\n raise ValueError('nargs not allowed')\ndefault = default or {}\nsuper(KeyValueAction, self).__init__(option_strings, dest, nargs, default=default, **kwargs)",
"if not isinstance(values, Mapping):\n raise ValueError('type must be \"key_value\"')\nif not getattr(namespace, self.dest):\n setatt... | <|body_start_0|>
if nargs:
raise ValueError('nargs not allowed')
default = default or {}
super(KeyValueAction, self).__init__(option_strings, dest, nargs, default=default, **kwargs)
<|end_body_0|>
<|body_start_1|>
if not isinstance(values, Mapping):
raise ValueEr... | Key=value argument class for an argparse option. | KeyValueAction | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyValueAction:
"""Key=value argument class for an argparse option."""
def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs):
"""Instantiate class."""
<|body_0|>
def __call__(self, parser, namespace, values, option_string=None):
"""Call cla... | stack_v2_sparse_classes_75kplus_train_071356 | 9,142 | permissive | [
{
"docstring": "Instantiate class.",
"name": "__init__",
"signature": "def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs)"
},
{
"docstring": "Call class directly.",
"name": "__call__",
"signature": "def __call__(self, parser, namespace, values, option_string=Non... | 2 | stack_v2_sparse_classes_30k_train_000932 | Implement the Python class `KeyValueAction` described below.
Class description:
Key=value argument class for an argparse option.
Method signatures and docstrings:
- def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs): Instantiate class.
- def __call__(self, parser, namespace, values, option_s... | Implement the Python class `KeyValueAction` described below.
Class description:
Key=value argument class for an argparse option.
Method signatures and docstrings:
- def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs): Instantiate class.
- def __call__(self, parser, namespace, values, option_s... | 94aebff4f83b294653192a1b74111f6a9f114de2 | <|skeleton|>
class KeyValueAction:
"""Key=value argument class for an argparse option."""
def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs):
"""Instantiate class."""
<|body_0|>
def __call__(self, parser, namespace, values, option_string=None):
"""Call cla... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyValueAction:
"""Key=value argument class for an argparse option."""
def __init__(self, option_strings, dest, default=None, nargs=None, **kwargs):
"""Instantiate class."""
if nargs:
raise ValueError('nargs not allowed')
default = default or {}
super(KeyValueA... | the_stack_v2_python_sparse | runway/cfngin/commands/stacker/base.py | edgarpoce/runway | train | 1 |
d6e89a5b0125c05fd721eb61667b842afc40fc97 | [
"while 1:\n try:\n self.find(By.ID, 'username').send_keys(username)\n break\n except:\n print('没有找到元素')\nself.find(By.ID, 'memberAdd_acctid').send_keys(account)\nself.find(By.ID, 'memberAdd_phone').send_keys(phone)\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()",
"pages: str = self... | <|body_start_0|>
while 1:
try:
self.find(By.ID, 'username').send_keys(username)
break
except:
print('没有找到元素')
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phone)
... | 添加成员类 | AddMemberPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while 1:
try:
self.find(By.ID, 'user... | stack_v2_sparse_classes_75kplus_train_071357 | 4,450 | no_license | [
{
"docstring": "添加成员",
"name": "add_member",
"signature": "def add_member(self, username, account, phone)"
},
{
"docstring": "获取所有的联系人姓名",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000716 | Implement the Python class `AddMemberPage` described below.
Class description:
添加成员类
Method signatures and docstrings:
- def add_member(self, username, account, phone): 添加成员
- def get_member(self): 获取所有的联系人姓名 | Implement the Python class `AddMemberPage` described below.
Class description:
添加成员类
Method signatures and docstrings:
- def add_member(self, username, account, phone): 添加成员
- def get_member(self): 获取所有的联系人姓名
<|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
... | 41651054386069fb3da5ec80d4acd922561f6de5 | <|skeleton|>
class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddMemberPage:
"""添加成员类"""
def add_member(self, username, account, phone):
"""添加成员"""
while 1:
try:
self.find(By.ID, 'username').send_keys(username)
break
except:
print('没有找到元素')
self.find(By.ID, 'memberAdd_ac... | the_stack_v2_python_sparse | com/python/pytest_test1/web/selenium_po/page/add_member_page.py | fengzige1993/PythonData | train | 0 |
1e65a44ea237bad99c048b00a22cb43eb8500818 | [
"try:\n project_id = self.kwargs.get('project_pk')\n Project.objects.get(id=project_id)\n issue_id = self.kwargs.get('issue_pk')\n issue = Issue.objects.get(id=issue_id, project=project_id)\n return self.queryset.filter(issue=issue)\nexcept Project.DoesNotExist:\n raise NotFound(f'Project (id:{pro... | <|body_start_0|>
try:
project_id = self.kwargs.get('project_pk')
Project.objects.get(id=project_id)
issue_id = self.kwargs.get('issue_pk')
issue = Issue.objects.get(id=issue_id, project=project_id)
return self.queryset.filter(issue=issue)
excep... | CommentViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentViewSet:
def get_queryset(self, *args, **kwargs):
"""Handle nested project's and issue's 'pk' in the URI"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Custom create method used to setup the comment's Foreign-keys (author_user & issue)"""
... | stack_v2_sparse_classes_75kplus_train_071358 | 6,335 | permissive | [
{
"docstring": "Handle nested project's and issue's 'pk' in the URI",
"name": "get_queryset",
"signature": "def get_queryset(self, *args, **kwargs)"
},
{
"docstring": "Custom create method used to setup the comment's Foreign-keys (author_user & issue)",
"name": "create",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_024775 | Implement the Python class `CommentViewSet` described below.
Class description:
Implement the CommentViewSet class.
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Handle nested project's and issue's 'pk' in the URI
- def create(self, request, *args, **kwargs): Custom create method used t... | Implement the Python class `CommentViewSet` described below.
Class description:
Implement the CommentViewSet class.
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Handle nested project's and issue's 'pk' in the URI
- def create(self, request, *args, **kwargs): Custom create method used t... | 21ce354ffae6d2fd4cd26d665eec06d022fb2ac7 | <|skeleton|>
class CommentViewSet:
def get_queryset(self, *args, **kwargs):
"""Handle nested project's and issue's 'pk' in the URI"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Custom create method used to setup the comment's Foreign-keys (author_user & issue)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentViewSet:
def get_queryset(self, *args, **kwargs):
"""Handle nested project's and issue's 'pk' in the URI"""
try:
project_id = self.kwargs.get('project_pk')
Project.objects.get(id=project_id)
issue_id = self.kwargs.get('issue_pk')
issue = I... | the_stack_v2_python_sparse | apps/api_issue_tracking/views.py | Valkea/OC_P10 | train | 0 | |
c585f74d225e48c19accf2cc063c4b247d19c92a | [
"extern_pars = np.copy(pars)\nextern_pars[6:8] = np.exp(extern_pars[6:8])\nreturn extern_pars",
"intern_pars = np.copy(pars)\nintern_pars[6:8] = np.log(intern_pars[6:8])\nreturn intern_pars",
"if covmatrix is None:\n dx = self._pars[6]\n dv = self._pars[7]\n self._covmatrix = np.identity(6)\n self._... | <|body_start_0|>
extern_pars = np.copy(pars)
extern_pars[6:8] = np.exp(extern_pars[6:8])
return extern_pars
<|end_body_0|>
<|body_start_1|>
intern_pars = np.copy(pars)
intern_pars[6:8] = np.log(intern_pars[6:8])
return intern_pars
<|end_body_1|>
<|body_start_2|>
... | SphereComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphereComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
<|body_0|>
def internalise(pars):
"""Take parameter set in external form (as used to build attributes) and... | stack_v2_sparse_classes_75kplus_train_071359 | 24,480 | permissive | [
{
"docstring": "Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).",
"name": "externalise",
"signature": "def externalise(pars)"
},
{
"docstring": "Take parameter set in external form (as used to build attributes) and convert to int... | 3 | stack_v2_sparse_classes_30k_train_033791 | Implement the Python class `SphereComponent` described below.
Class description:
Implement the SphereComponent class.
Method signatures and docstrings:
- def externalise(pars): Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).
- def internalise(pars): T... | Implement the Python class `SphereComponent` described below.
Class description:
Implement the SphereComponent class.
Method signatures and docstrings:
- def externalise(pars): Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes).
- def internalise(pars): T... | d38aa19edd0229bb0a8b7126f248e61b9a0a8ff3 | <|skeleton|>
class SphereComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
<|body_0|>
def internalise(pars):
"""Take parameter set in external form (as used to build attributes) and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SphereComponent:
def externalise(pars):
"""Take parameter set in internal form (as used by emcee) and convert to external form (as used to build attributes)."""
extern_pars = np.copy(pars)
extern_pars[6:8] = np.exp(extern_pars[6:8])
return extern_pars
def internalise(pars)... | the_stack_v2_python_sparse | chronostar/component.py | tcrundall/chronostar | train | 0 | |
569cb10b55aa217325624866446d9b4792d377bf | [
"rdelta, _ = self._getRdelta()\nfor s in rdelta[st]:\n l = []\n for k in self.delta[s]:\n if st in self.delta[s][k]:\n l.append(k)\n for k in l:\n self.addTransition(s, k, stf)\n self.delFinal(s)",
"_, rdelta = self._getRdelta()\nfor s in rdelta[s2]:\n l = []\n for k in ... | <|body_start_0|>
rdelta, _ = self._getRdelta()
for s in rdelta[st]:
l = []
for k in self.delta[s]:
if st in self.delta[s][k]:
l.append(k)
for k in l:
self.addTransition(s, k, stf)
self.delFinal(s)
<|end_b... | Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA | ANFA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ANFA:
"""Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA"""
def moveFinal(self, st, stf):
"""Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :param int stf: the destination final state .. note:: stf mus... | stack_v2_sparse_classes_75kplus_train_071360 | 35,135 | permissive | [
{
"docstring": "Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :param int stf: the destination final state .. note:: stf must be a 'last' final state, i.e., must have no out transitions to anywhere but to a possible dead state .. attention:: the object is mo... | 4 | stack_v2_sparse_classes_30k_train_053562 | Implement the Python class `ANFA` described below.
Class description:
Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA
Method signatures and docstrings:
- def moveFinal(self, st, stf): Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :par... | Implement the Python class `ANFA` described below.
Class description:
Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA
Method signatures and docstrings:
- def moveFinal(self, st, stf): Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :par... | 99086336b1c96d9ec0f547741bcff2c773129017 | <|skeleton|>
class ANFA:
"""Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA"""
def moveFinal(self, st, stf):
"""Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :param int stf: the destination final state .. note:: stf mus... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ANFA:
"""Acyclic Nondeterministic Finite Automata class .. inheritance-diagram:: ANFA"""
def moveFinal(self, st, stf):
"""Unsets a set as final transfering transition to another final :param int st: the state to be 'moved' :param int stf: the destination final state .. note:: stf must be a 'last'... | the_stack_v2_python_sparse | fado-python3/FAdo/fl.py | narame7/set2regex | train | 0 |
d1f797897cc64dec2c865a3be1444ef458c1c9aa | [
"self._component = self._component_type()\nself.real_input_shape = [self._hparams.batch_size] + self._dataset.shape[1:]\nself.gen_input_shape = [self._hparams.batch_size, 1, 1, 100]\nself.condition_shape = [self._hparams.batch_size, self._dataset.num_classes]\nself._component.build(self.gen_input_shape, self.real_i... | <|body_start_0|>
self._component = self._component_type()
self.real_input_shape = [self._hparams.batch_size] + self._dataset.shape[1:]
self.gen_input_shape = [self._hparams.batch_size, 1, 1, 100]
self.condition_shape = [self._hparams.batch_size, self._dataset.num_classes]
self._c... | A simple workflow for standalone GANs. Not used in composite architectures. | GANWorkflow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANWorkflow:
"""A simple workflow for standalone GANs. Not used in composite architectures."""
def _setup_component(self):
"""Setup the component"""
<|body_0|>
def training_step(self, dataset_handle, global_step, phase_change=False):
"""The training procedure wit... | stack_v2_sparse_classes_75kplus_train_071361 | 3,507 | permissive | [
{
"docstring": "Setup the component",
"name": "_setup_component",
"signature": "def _setup_component(self)"
},
{
"docstring": "The training procedure within the batch loop",
"name": "training_step",
"signature": "def training_step(self, dataset_handle, global_step, phase_change=False)"
... | 3 | null | Implement the Python class `GANWorkflow` described below.
Class description:
A simple workflow for standalone GANs. Not used in composite architectures.
Method signatures and docstrings:
- def _setup_component(self): Setup the component
- def training_step(self, dataset_handle, global_step, phase_change=False): The t... | Implement the Python class `GANWorkflow` described below.
Class description:
A simple workflow for standalone GANs. Not used in composite architectures.
Method signatures and docstrings:
- def _setup_component(self): Setup the component
- def training_step(self, dataset_handle, global_step, phase_change=False): The t... | 33bf8a3a620b46b5180280f2ca5f0b28c168b806 | <|skeleton|>
class GANWorkflow:
"""A simple workflow for standalone GANs. Not used in composite architectures."""
def _setup_component(self):
"""Setup the component"""
<|body_0|>
def training_step(self, dataset_handle, global_step, phase_change=False):
"""The training procedure wit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GANWorkflow:
"""A simple workflow for standalone GANs. Not used in composite architectures."""
def _setup_component(self):
"""Setup the component"""
self._component = self._component_type()
self.real_input_shape = [self._hparams.batch_size] + self._dataset.shape[1:]
self.g... | the_stack_v2_python_sparse | rsm/workflows/gan_workflow.py | Cerenaut/rsm | train | 1 |
fa6333a5d1fb6ab535a5a8ef8b57f143867567fc | [
"if self.embed_images:\n nb, resources = super(EmbedImagesPreprocessor, self).preprocess(nb, resources)\nreturn (nb, resources)",
"if imgformat in ['png', 'jpg']:\n from io import BytesIO\n try:\n from PIL import Image\n except ImportError:\n self.log.info('Pillow library not available t... | <|body_start_0|>
if self.embed_images:
nb, resources = super(EmbedImagesPreprocessor, self).preprocess(nb, resources)
return (nb, resources)
<|end_body_0|>
<|body_start_1|>
if imgformat in ['png', 'jpg']:
from io import BytesIO
try:
from PIL i... | :mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the cell metadata. The preprocessor is installed by default. To enable embedding images with Nb... | EmbedImagesPreprocessor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbedImagesPreprocessor:
""":mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the cell metadata. The preprocessor is insta... | stack_v2_sparse_classes_75kplus_train_071362 | 5,940 | permissive | [
{
"docstring": "Skip preprocessor if not enabled",
"name": "preprocess",
"signature": "def preprocess(self, nb, resources)"
},
{
"docstring": "Resize images if desired and PIL is installed Parameters ---------- imgname: str Name of image imgformat: str Format of image (JPG or PNG) imgdata: Binar... | 4 | stack_v2_sparse_classes_30k_train_037128 | Implement the Python class `EmbedImagesPreprocessor` described below.
Class description:
:mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the c... | Implement the Python class `EmbedImagesPreprocessor` described below.
Class description:
:mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the c... | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | <|skeleton|>
class EmbedImagesPreprocessor:
""":mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the cell metadata. The preprocessor is insta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmbedImagesPreprocessor:
""":mod:`nbconvert` Preprocessor to embed images in a markdown cell as attachment inside the notebook itself. This :class:`~nbconvert.preprocessors.Preprocessor` replaces kernel code in markdown cells with the results stored in the cell metadata. The preprocessor is installed by defau... | the_stack_v2_python_sparse | Library/lib/python3.7/site-packages/jupyter_contrib_nbextensions-0.5.1-py3.7.egg/jupyter_contrib_nbextensions/nbconvert_support/pre_embedimages.py | holzschu/Carnets | train | 541 |
e5b99a7696dbf3dd7e541aae721b61621570f650 | [
"self.logger = logger\nself.grab_period = grab_period\nself.grab_limit = grab_limit\nself.file_index = 1\nself.call_index = 0\nimage_dirs = sorted(glob.glob('Images[0-9][0-9][0-9][0-9]'))\nif len(image_dirs) != 0:\n last_dir = image_dirs[-1]\n dir_index = int(last_dir[-4:]) + 1\nelse:\n dir_index = 1\nself... | <|body_start_0|>
self.logger = logger
self.grab_period = grab_period
self.grab_limit = grab_limit
self.file_index = 1
self.call_index = 0
image_dirs = sorted(glob.glob('Images[0-9][0-9][0-9][0-9]'))
if len(image_dirs) != 0:
last_dir = image_dirs[-1]
... | ImageGrabber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageGrabber:
def __init__(self, logger, grab_period=5, grab_limit=100):
"""Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = ImageGrabber(logger, grab_period=5, grab_limit=50) while 1: ret, frame = cap.read() # get image, for exam... | stack_v2_sparse_classes_75kplus_train_071363 | 1,983 | no_license | [
{
"docstring": "Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = ImageGrabber(logger, grab_period=5, grab_limit=50) while 1: ret, frame = cap.read() # get image, for example process_image_to_extract_info(frame) if appropriate_to_grab: ig.grab(frame,log_m... | 2 | stack_v2_sparse_classes_30k_train_010986 | Implement the Python class `ImageGrabber` described below.
Class description:
Implement the ImageGrabber class.
Method signatures and docstrings:
- def __init__(self, logger, grab_period=5, grab_limit=100): Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = Imag... | Implement the Python class `ImageGrabber` described below.
Class description:
Implement the ImageGrabber class.
Method signatures and docstrings:
- def __init__(self, logger, grab_period=5, grab_limit=100): Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = Imag... | 6452a0b36b60ab79c2d113cbe9d68ea79e9e6ed2 | <|skeleton|>
class ImageGrabber:
def __init__(self, logger, grab_period=5, grab_limit=100):
"""Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = ImageGrabber(logger, grab_period=5, grab_limit=50) while 1: ret, frame = cap.read() # get image, for exam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageGrabber:
def __init__(self, logger, grab_period=5, grab_limit=100):
"""Create a image grabber that grabs an image every grab_period calls. Default is every 5th call. Usage: ig = ImageGrabber(logger, grab_period=5, grab_limit=50) while 1: ret, frame = cap.read() # get image, for example process_im... | the_stack_v2_python_sparse | image_grabber.py | FRC1076/Vision_2016 | train | 0 | |
eef9ca2fb1f6f654aecfcf021dc942bc08eb3b6c | [
"super(Sampler, self).__init__()\nself.mean = nn.Linear(input_dim, h_dim)\nself.logvar = nn.Linear(input_dim, h_dim)",
"input = torch.cat((input1, input2), dim=1)\nmean = self.mean(input)\nlogvar = self.logvar(input)\nstd = logvar.mul(0.5).exp_()\neps = Variable(std.data.new(std.size()).normal_())\nif use_mean:\n... | <|body_start_0|>
super(Sampler, self).__init__()
self.mean = nn.Linear(input_dim, h_dim)
self.logvar = nn.Linear(input_dim, h_dim)
<|end_body_0|>
<|body_start_1|>
input = torch.cat((input1, input2), dim=1)
mean = self.mean(input)
logvar = self.logvar(input)
std =... | Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution | Sampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sampler:
"""Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution"""
def __init__(self, input_dim, h_dim=512):
"""Two FC layers to compute the mean and variance... | stack_v2_sparse_classes_75kplus_train_071364 | 41,496 | no_license | [
{
"docstring": "Two FC layers to compute the mean and variance :param input_dim: int, the dimension of the embedding vector :param h_dim: int, the dimension of the latent variable",
"name": "__init__",
"signature": "def __init__(self, input_dim, h_dim=512)"
},
{
"docstring": "The forward method ... | 2 | stack_v2_sparse_classes_30k_train_030475 | Implement the Python class `Sampler` described below.
Class description:
Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution
Method signatures and docstrings:
- def __init__(self, input_dim, h... | Implement the Python class `Sampler` described below.
Class description:
Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution
Method signatures and docstrings:
- def __init__(self, input_dim, h... | 90d52bfc89cf429d2389e5e8bd4b85efdb05ac64 | <|skeleton|>
class Sampler:
"""Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution"""
def __init__(self, input_dim, h_dim=512):
"""Two FC layers to compute the mean and variance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sampler:
"""Calculate the mean and variance of the approximated latent distribution And output a vector from the distribution, which is either sampled from or using the mean of distribution"""
def __init__(self, input_dim, h_dim=512):
"""Two FC layers to compute the mean and variance :param input... | the_stack_v2_python_sparse | outer_prod_motion_mask/twostreamvan_generator.py | sunxm2357/TwoStreamVAN | train | 8 |
84bf46c1be37075ed872866536fcb4f25c9afa5f | [
"super(AMSoftmaxLoss, self).__init__()\nself.s = s\nself.m = m\nself.speaker_num = speaker_num\nself.W = torch.nn.Parameter(torch.randn(hidden_dim, speaker_num), requires_grad=True)\nnn.init.xavier_normal_(self.W, gain=1)",
"assert len(x_BxH) == len(labels_B)\nassert torch.min(labels_B) >= 0\nassert torch.max(lab... | <|body_start_0|>
super(AMSoftmaxLoss, self).__init__()
self.s = s
self.m = m
self.speaker_num = speaker_num
self.W = torch.nn.Parameter(torch.randn(hidden_dim, speaker_num), requires_grad=True)
nn.init.xavier_normal_(self.W, gain=1)
<|end_body_0|>
<|body_start_1|>
... | AMSoftmaxLoss | [
"Apache-2.0",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AMSoftmaxLoss:
def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs):
"""AM Softmax Loss"""
<|body_0|>
def forward(self, x_BxH, labels_B):
"""x shape: (B, H) labels shape: (B)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(AMSo... | stack_v2_sparse_classes_75kplus_train_071365 | 16,174 | permissive | [
{
"docstring": "AM Softmax Loss",
"name": "__init__",
"signature": "def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs)"
},
{
"docstring": "x shape: (B, H) labels shape: (B)",
"name": "forward",
"signature": "def forward(self, x_BxH, labels_B)"
}
] | 2 | null | Implement the Python class `AMSoftmaxLoss` described below.
Class description:
Implement the AMSoftmaxLoss class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs): AM Softmax Loss
- def forward(self, x_BxH, labels_B): x shape: (B, H) labels shape: (B) | Implement the Python class `AMSoftmaxLoss` described below.
Class description:
Implement the AMSoftmaxLoss class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs): AM Softmax Loss
- def forward(self, x_BxH, labels_B): x shape: (B, H) labels shape: (B)
<|skeleto... | 76a9432b824f6ae3eae09a35a67782c4ed582832 | <|skeleton|>
class AMSoftmaxLoss:
def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs):
"""AM Softmax Loss"""
<|body_0|>
def forward(self, x_BxH, labels_B):
"""x shape: (B, H) labels shape: (B)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AMSoftmaxLoss:
def __init__(self, hidden_dim, speaker_num, s=30.0, m=0.4, **kwargs):
"""AM Softmax Loss"""
super(AMSoftmaxLoss, self).__init__()
self.s = s
self.m = m
self.speaker_num = speaker_num
self.W = torch.nn.Parameter(torch.randn(hidden_dim, speaker_num)... | the_stack_v2_python_sparse | s3prl/downstream/sv_voxceleb1/model.py | s3prl/s3prl | train | 1,549 | |
8d45a3efa38afa94a7bc2263211536f069456f2a | [
"if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelif type(data) is not list:\n raise TypeError('data must be a list')\nelif len(data) < 2:\n raise ValueError('data must contain multiple values')\nelse:\n self.lambtha ... | <|body_start_0|>
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = float(lambtha)
elif type(data) is not list:
raise TypeError('data must be a list')
elif len(data) < 2:
raise Valu... | Tye class to call methods of Poisson distribution CDF and PDF | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Tye class to call methods of Poisson distribution CDF and PDF"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data"""
<|body_0|>
def pmf(self, k):
""... | stack_v2_sparse_classes_75kplus_train_071366 | 1,588 | no_license | [
{
"docstring": "Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Method Probability Mass Function for Poisson k: integer value of the data re... | 3 | stack_v2_sparse_classes_30k_train_033360 | Implement the Python class `Poisson` described below.
Class description:
Tye class to call methods of Poisson distribution CDF and PDF
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of dat... | Implement the Python class `Poisson` described below.
Class description:
Tye class to call methods of Poisson distribution CDF and PDF
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of dat... | 7f9a040f23eda32c5aa154c991c930a01b490f0f | <|skeleton|>
class Poisson:
"""Tye class to call methods of Poisson distribution CDF and PDF"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data"""
<|body_0|>
def pmf(self, k):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Poisson:
"""Tye class to call methods of Poisson distribution CDF and PDF"""
def __init__(self, data=None, lambtha=1.0):
"""Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data"""
if data is None:
if lambtha <= 0:
... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | dbaroli/holbertonschool-machine_learning | train | 0 |
88221cf89dafa1cdcc51572f0297c41cf24bb415 | [
"user = request.user\nif user.is_staff:\n return self.fast_response('chats', filtering='all', instance=user)\nelse:\n return self.fast_response('chat', many=False, instance=user)",
"serializer = self.serializer_class(data=request.data)\nserializer.is_valid(raise_exception=True)\nkey = serializer.data.get('t... | <|body_start_0|>
user = request.user
if user.is_staff:
return self.fast_response('chats', filtering='all', instance=user)
else:
return self.fast_response('chat', many=False, instance=user)
<|end_body_0|>
<|body_start_1|>
serializer = self.serializer_class(data=re... | Активация аккаунта Чаты пользователя/администратора | ClientViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientViewSet:
"""Активация аккаунта Чаты пользователя/администратора"""
def chat(self, request, *args, **kwargs):
"""Чаты пользователя"""
<|body_0|>
def activate(self, request, *args, **kwargs):
"""Активация аккаунта"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_071367 | 1,719 | no_license | [
{
"docstring": "Чаты пользователя",
"name": "chat",
"signature": "def chat(self, request, *args, **kwargs)"
},
{
"docstring": "Активация аккаунта",
"name": "activate",
"signature": "def activate(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `ClientViewSet` described below.
Class description:
Активация аккаунта Чаты пользователя/администратора
Method signatures and docstrings:
- def chat(self, request, *args, **kwargs): Чаты пользователя
- def activate(self, request, *args, **kwargs): Активация аккаунта | Implement the Python class `ClientViewSet` described below.
Class description:
Активация аккаунта Чаты пользователя/администратора
Method signatures and docstrings:
- def chat(self, request, *args, **kwargs): Чаты пользователя
- def activate(self, request, *args, **kwargs): Активация аккаунта
<|skeleton|>
class Clie... | 0aa7fbbea112341cac2e8f5ae613f77ec91978d3 | <|skeleton|>
class ClientViewSet:
"""Активация аккаунта Чаты пользователя/администратора"""
def chat(self, request, *args, **kwargs):
"""Чаты пользователя"""
<|body_0|>
def activate(self, request, *args, **kwargs):
"""Активация аккаунта"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientViewSet:
"""Активация аккаунта Чаты пользователя/администратора"""
def chat(self, request, *args, **kwargs):
"""Чаты пользователя"""
user = request.user
if user.is_staff:
return self.fast_response('chats', filtering='all', instance=user)
else:
... | the_stack_v2_python_sparse | backend/client/api/views.py | ScrollPage/Soil-State-Tracker-2 | train | 0 |
c886f53809179128f2c1587c8375019deaa81619 | [
"local_file = f'{local_path}system_logs.txt'\ncommand = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}'\nprint(f'fetch command = {command}')\nos.system(command)\nreturn local_file",
"local_file = f'{local_path}secondary_system_logs.txt'\ncommand = f'sshpass -p... | <|body_start_0|>
local_file = f'{local_path}system_logs.txt'
command = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}'
print(f'fetch command = {command}')
os.system(command)
return local_file
<|end_body_0|>
<|body_start_1|>
... | Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, password, remote_file, local_... | LogFetcher | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"WTFPL",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u... | stack_v2_sparse_classes_75kplus_train_071368 | 13,309 | permissive | [
{
"docstring": "Fetches system logs from server and copies to local machine :param host: str, ssh host :param username: str, ssh username :param password: str, ssh password :param remote_file: str, location of system logs on server :param local_path: str, local path to copy system logs to :return: local_file: s... | 3 | stack_v2_sparse_classes_30k_val_001005 | Implement the Python class `LogFetcher` described below.
Class description:
Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se... | Implement the Python class `LogFetcher` described below.
Class description:
Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, pass... | the_stack_v2_python_sparse | govern/data-security/ranger/ranger-tools/src/main/python/ranger_performance_tool/ranger_perf_utils/logging_utils.py | alldatacenter/alldata | train | 774 |
1adce00d706e9b8d1e6a24c0729552d1663214c6 | [
"self.key = key\nself.val = val\nself.left = left\nself.right = right\nself.N = N\nself.color = color",
"if self.left != None:\n self.left.color = 'Black'\nif self.right != None:\n self.right.color = 'Black'\nself.color = 'Red'"
] | <|body_start_0|>
self.key = key
self.val = val
self.left = left
self.right = right
self.N = N
self.color = color
<|end_body_0|>
<|body_start_1|>
if self.left != None:
self.left.color = 'Black'
if self.right != None:
self.right.colo... | Node | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black'):
"""初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :param N: 当前结点所在的子树的结点数量 :param color: 当前结点的颜色:红/黑"""
<|body_0|>
def flipColors(self)... | stack_v2_sparse_classes_75kplus_train_071369 | 21,313 | permissive | [
{
"docstring": "初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :param N: 当前结点所在的子树的结点数量 :param color: 当前结点的颜色:红/黑",
"name": "__init__",
"signature": "def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black')"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_012807 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black'): 初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :para... | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black'): 初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :para... | b769d46727279cf6d8532819076a3fef496d05c7 | <|skeleton|>
class Node:
def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black'):
"""初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :param N: 当前结点所在的子树的结点数量 :param color: 当前结点的颜色:红/黑"""
<|body_0|>
def flipColors(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def __init__(self, key=None, val=None, left=None, right=None, N=1, color='Black'):
"""初始化一个红黑树的结点 :param key: 结点的索引,用以比较结点 :param val: 结点中存储的值 :param left: 结点的左子树 :param right: 结点的右子树 :param N: 当前结点所在的子树的结点数量 :param color: 当前结点的颜色:红/黑"""
self.key = key
self.val = val
self... | the_stack_v2_python_sparse | DataStructure/Tree/RedBlackTree.py | z-waterking/ClassicAlgorighthms | train | 27 | |
7a908dbb6ede1d104a249485a63f73b3eed68c52 | [
"try:\n username = request.data.get('username', '')\n User.reset_password(username=username)\n return Response({}, status=status.HTTP_201_CREATED)\nexcept User.DoesNotExist:\n raise Http404",
"if not request.user.is_authenticated:\n raise PermissionDenied()\ndata = request.data\npassword, new_passw... | <|body_start_0|>
try:
username = request.data.get('username', '')
User.reset_password(username=username)
return Response({}, status=status.HTTP_201_CREATED)
except User.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if not request.use... | UserPassword | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPassword:
def post(self, request, *args, **kwargs):
"""Reset a user's password and email it to them."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Change the authenticated user's password."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071370 | 4,355 | permissive | [
{
"docstring": "Reset a user's password and email it to them.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Change the authenticated user's password.",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045943 | Implement the Python class `UserPassword` described below.
Class description:
Implement the UserPassword class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Reset a user's password and email it to them.
- def put(self, request, *args, **kwargs): Change the authenticated user's passwor... | Implement the Python class `UserPassword` described below.
Class description:
Implement the UserPassword class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Reset a user's password and email it to them.
- def put(self, request, *args, **kwargs): Change the authenticated user's passwor... | 0f737e92d7946a83150b402784d911ab7438547b | <|skeleton|>
class UserPassword:
def post(self, request, *args, **kwargs):
"""Reset a user's password and email it to them."""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Change the authenticated user's password."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserPassword:
def post(self, request, *args, **kwargs):
"""Reset a user's password and email it to them."""
try:
username = request.data.get('username', '')
User.reset_password(username=username)
return Response({}, status=status.HTTP_201_CREATED)
ex... | the_stack_v2_python_sparse | huxley/api/views/user.py | bmun/huxley | train | 23 | |
e24f77a7ec4c63a0c1ac7d553b9bc43a5beba174 | [
"b = x.max()\ny = np.exp(x - b)\nx = (y.T / y.sum(axis=1)).T\nself.x = x\nreturn x",
"dx = np.zeros(dout.shape, dtype=np.float64)\nfor i in range(0, dout.shape[0]):\n delta = self.x[i, :].reshape(-1, 1)\n delta = np.diagflat(delta) - np.dot(delta, delta.T)\n dx[i, :] = np.dot(delta, dout[i, :])\nreturn d... | <|body_start_0|>
b = x.max()
y = np.exp(x - b)
x = (y.T / y.sum(axis=1)).T
self.x = x
return x
<|end_body_0|>
<|body_start_1|>
dx = np.zeros(dout.shape, dtype=np.float64)
for i in range(0, dout.shape[0]):
delta = self.x[i, :].reshape(-1, 1)
... | Softmax activation module. | SoftMaxModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
<|body_0|>
def backward(self, dout):
"""Backward pass. Args: dout: gradients of the previous modul Returns: d... | stack_v2_sparse_classes_75kplus_train_071371 | 3,644 | no_license | [
{
"docstring": "Forward pass. Args: x: input to the module Returns: out: output of the module",
"name": "forward",
"signature": "def forward(self, x)"
},
{
"docstring": "Backward pass. Args: dout: gradients of the previous modul Returns: dx: gradients with respect to the input of the module",
... | 2 | stack_v2_sparse_classes_30k_train_049969 | Implement the Python class `SoftMaxModule` described below.
Class description:
Softmax activation module.
Method signatures and docstrings:
- def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module
- def backward(self, dout): Backward pass. Args: dout: gradients of the prev... | Implement the Python class `SoftMaxModule` described below.
Class description:
Softmax activation module.
Method signatures and docstrings:
- def forward(self, x): Forward pass. Args: x: input to the module Returns: out: output of the module
- def backward(self, dout): Backward pass. Args: dout: gradients of the prev... | 19e8ac762cedda82410a0dda676edaf659c55d6a | <|skeleton|>
class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
<|body_0|>
def backward(self, dout):
"""Backward pass. Args: dout: gradients of the previous modul Returns: d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoftMaxModule:
"""Softmax activation module."""
def forward(self, x):
"""Forward pass. Args: x: input to the module Returns: out: output of the module"""
b = x.max()
y = np.exp(x - b)
x = (y.T / y.sum(axis=1)).T
self.x = x
return x
def backward(self, d... | the_stack_v2_python_sparse | assignment_1/code/modules.py | RancyChepchirchir/dl-assignments | train | 0 |
46ef0ad07cd6aa58b2ef7a2096e6017c94bfd0c9 | [
"cr.execute('\\n SELECT MIN(ml.date_to - ai.date_invoice)\\n FROM membership_membership_line ml\\n JOIN account_invoice_line ail ON (\\n ml.account_invoice_line = ail.id\\n )\\n JOIN account_invoice ai ON (\\n ai.id = ail.invoice_id)\\n WHERE ml... | <|body_start_0|>
cr.execute('\n SELECT MIN(ml.date_to - ai.date_invoice)\n FROM membership_membership_line ml\n JOIN account_invoice_line ail ON (\n ml.account_invoice_line = ail.id\n )\n JOIN account_invoice ai ON (\n ai.id = ail.invoice_id)\n ... | Member line | membership_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class membership_line:
"""Member line"""
def _check_membership_date(self, cr, uid, ids, context=None):
"""Check if membership product is not in the past"""
<|body_0|>
def _state(self, cr, uid, ids, name, args, context=None):
"""Compute the state lines"""
<|body... | stack_v2_sparse_classes_75kplus_train_071372 | 29,113 | no_license | [
{
"docstring": "Check if membership product is not in the past",
"name": "_check_membership_date",
"signature": "def _check_membership_date(self, cr, uid, ids, context=None)"
},
{
"docstring": "Compute the state lines",
"name": "_state",
"signature": "def _state(self, cr, uid, ids, name,... | 2 | null | Implement the Python class `membership_line` described below.
Class description:
Member line
Method signatures and docstrings:
- def _check_membership_date(self, cr, uid, ids, context=None): Check if membership product is not in the past
- def _state(self, cr, uid, ids, name, args, context=None): Compute the state li... | Implement the Python class `membership_line` described below.
Class description:
Member line
Method signatures and docstrings:
- def _check_membership_date(self, cr, uid, ids, context=None): Check if membership product is not in the past
- def _state(self, cr, uid, ids, name, args, context=None): Compute the state li... | 840f28642b5d328e4b86839c413e5164622295a5 | <|skeleton|>
class membership_line:
"""Member line"""
def _check_membership_date(self, cr, uid, ids, context=None):
"""Check if membership product is not in the past"""
<|body_0|>
def _state(self, cr, uid, ids, name, args, context=None):
"""Compute the state lines"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class membership_line:
"""Member line"""
def _check_membership_date(self, cr, uid, ids, context=None):
"""Check if membership product is not in the past"""
cr.execute('\n SELECT MIN(ml.date_to - ai.date_invoice)\n FROM membership_membership_line ml\n JOIN account_invoice... | the_stack_v2_python_sparse | membership/membership.py | MarkNorgate/addons-EAD | train | 0 |
2e09a5feca96dd3cdb3dae4a0114d5163e9c7261 | [
"memclient = memcache.Client()\ntotal = memclient.get(str(instance))\nif total is None:\n total = 0\n counters = cls.all().filter('instance_key =', instance)\n for counter in counters:\n total += counter.count\n memclient.add(str(instance), str(total), 60)\nreturn int(total)",
"memclient = memc... | <|body_start_0|>
memclient = memcache.Client()
total = memclient.get(str(instance))
if total is None:
total = 0
counters = cls.all().filter('instance_key =', instance)
for counter in counters:
total += counter.count
memclient.add(st... | Contador sharded instance es el key del objeto al que apunta | ShardedCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
<|body_0|>
def increase_counter(cls, instance, count):... | stack_v2_sparse_classes_75kplus_train_071373 | 5,048 | no_license | [
{
"docstring": "Returns the value of the counter, is counters is not in memcache, counts all the sharded counters",
"name": "get_count",
"signature": "def get_count(cls, instance)"
},
{
"docstring": "Increment the counter of given key",
"name": "increase_counter",
"signature": "def incre... | 2 | stack_v2_sparse_classes_30k_train_030079 | Implement the Python class `ShardedCounter` described below.
Class description:
Contador sharded instance es el key del objeto al que apunta
Method signatures and docstrings:
- def get_count(cls, instance): Returns the value of the counter, is counters is not in memcache, counts all the sharded counters
- def increas... | Implement the Python class `ShardedCounter` described below.
Class description:
Contador sharded instance es el key del objeto al que apunta
Method signatures and docstrings:
- def get_count(cls, instance): Returns the value of the counter, is counters is not in memcache, counts all the sharded counters
- def increas... | d441693eedb32c36fe853895110df808a9959941 | <|skeleton|>
class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
<|body_0|>
def increase_counter(cls, instance, count):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShardedCounter:
"""Contador sharded instance es el key del objeto al que apunta"""
def get_count(cls, instance):
"""Returns the value of the counter, is counters is not in memcache, counts all the sharded counters"""
memclient = memcache.Client()
total = memclient.get(str(instance... | the_stack_v2_python_sparse | src/webapp/georemindme/models_utils.py | GeoRemindMe/GeoRemindMe_Web | train | 8 |
9084a2d3826675a055b2cc24306d5c2061e26cc3 | [
"super(Tar, self).__init__()\nself.dry_run = dry_run\nself.verbose = verbose",
"path = os.path.dirname(file_path)\nif path == '':\n path = '.'\nfolder_name = os.path.basename(file_path)\ntar_filename = '%s.tar.gz' % folder_name\ntar_filename = os.path.join(path, tar_filename)\nextra_tar_options = ''\nif self.v... | <|body_start_0|>
super(Tar, self).__init__()
self.dry_run = dry_run
self.verbose = verbose
<|end_body_0|>
<|body_start_1|>
path = os.path.dirname(file_path)
if path == '':
path = '.'
folder_name = os.path.basename(file_path)
tar_filename = '%s.tar.gz'... | Tar Class. | Tar | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
<|body_0|>
def create(self, file_path):
"""Create TAR file."""
<|body_1|>
def extract(self, file_path):
"""Extract TAR file."""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_071374 | 1,535 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, dry_run=False, verbose=False)"
},
{
"docstring": "Create TAR file.",
"name": "create",
"signature": "def create(self, file_path)"
},
{
"docstring": "Extract TAR file.",
"name": "extract",
"signat... | 3 | stack_v2_sparse_classes_30k_val_001460 | Implement the Python class `Tar` described below.
Class description:
Tar Class.
Method signatures and docstrings:
- def __init__(self, dry_run=False, verbose=False): Init.
- def create(self, file_path): Create TAR file.
- def extract(self, file_path): Extract TAR file. | Implement the Python class `Tar` described below.
Class description:
Tar Class.
Method signatures and docstrings:
- def __init__(self, dry_run=False, verbose=False): Init.
- def create(self, file_path): Create TAR file.
- def extract(self, file_path): Extract TAR file.
<|skeleton|>
class Tar:
"""Tar Class."""
... | 19ab8b09985d8c19f235feea348e3a2b0dae890a | <|skeleton|>
class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
<|body_0|>
def create(self, file_path):
"""Create TAR file."""
<|body_1|>
def extract(self, file_path):
"""Extract TAR file."""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tar:
"""Tar Class."""
def __init__(self, dry_run=False, verbose=False):
"""Init."""
super(Tar, self).__init__()
self.dry_run = dry_run
self.verbose = verbose
def create(self, file_path):
"""Create TAR file."""
path = os.path.dirname(file_path)
... | the_stack_v2_python_sparse | gerrit_backup_tool/tar/Tar.py | ZhangYaxu/gerrit_backup_tool | train | 0 |
322670cff6b2187362d9f73ea4e380f9402fd694 | [
"if '__init__' in clsdct:\n init_code = inspect.getsource(clsdct['__init__'])\n init_code = metacls.check_init_code(init_code)\nreturn super().__new__(metacls, clsname, bases, clsdct)",
"lines = init_source.strip().split('\\n')\nsearch_pat = 'self.'\nfor line in lines:\n if search_pat not in line:\n ... | <|body_start_0|>
if '__init__' in clsdct:
init_code = inspect.getsource(clsdct['__init__'])
init_code = metacls.check_init_code(init_code)
return super().__new__(metacls, clsname, bases, clsdct)
<|end_body_0|>
<|body_start_1|>
lines = init_source.strip().split('\n')
... | CheckInstanceArgs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckInstanceArgs:
def __new__(metacls, clsname, bases, clsdct, **kwargs):
"""New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente nach der Schreibweise. Wenn sie nicht klein geschrieben sind, dann wird en NameError erhoben."""
<|... | stack_v2_sparse_classes_75kplus_train_071375 | 2,079 | permissive | [
{
"docstring": "New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente nach der Schreibweise. Wenn sie nicht klein geschrieben sind, dann wird en NameError erhoben.",
"name": "__new__",
"signature": "def __new__(metacls, clsname, bases, clsdct, **kwargs)"
... | 2 | null | Implement the Python class `CheckInstanceArgs` described below.
Class description:
Implement the CheckInstanceArgs class.
Method signatures and docstrings:
- def __new__(metacls, clsname, bases, clsdct, **kwargs): New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente n... | Implement the Python class `CheckInstanceArgs` described below.
Class description:
Implement the CheckInstanceArgs class.
Method signatures and docstrings:
- def __new__(metacls, clsname, bases, clsdct, **kwargs): New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente n... | 9499db8159efce1e3c38975b66a9c649631c6727 | <|skeleton|>
class CheckInstanceArgs:
def __new__(metacls, clsname, bases, clsdct, **kwargs):
"""New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente nach der Schreibweise. Wenn sie nicht klein geschrieben sind, dann wird en NameError erhoben."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckInstanceArgs:
def __new__(metacls, clsname, bases, clsdct, **kwargs):
"""New Method durchsucht das Klassen-Dict nach der __init__ Methode und überprüft die gesetzten Argumente nach der Schreibweise. Wenn sie nicht klein geschrieben sind, dann wird en NameError erhoben."""
if '__init__' in... | the_stack_v2_python_sparse | Kapitel_6/_3_check_instance_args.py | Geralonx/Classes_Tutorial | train | 1 | |
5c60d785931e3ded631f928274b04f364c560cc2 | [
"super().__init__(dist_sync_on_step=dist_sync_on_step)\nself.threshold = threshold\nself.length = length\nself.reduce_dims = reduce_dims\nself.add_state('hits', default=torch.zeros(length), dist_reduce_fx='sum')\nself.add_state('false_alarms', default=torch.zeros(length), dist_reduce_fx='sum')\nself.add_state('miss... | <|body_start_0|>
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.threshold = threshold
self.length = length
self.reduce_dims = reduce_dims
self.add_state('hits', default=torch.zeros(length), dist_reduce_fx='sum')
self.add_state('false_alarms', default=torch.zer... | Critical Success Index metric. | CSI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
<|body_0|>
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""Update calculations."""
... | stack_v2_sparse_classes_75kplus_train_071376 | 4,694 | permissive | [
{
"docstring": "Initilize metric.",
"name": "__init__",
"signature": "def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False)"
},
{
"docstring": "Update calculations.",
"name": "update",
"signature": "def update(self, preds: torch.Tensor, target: torch.Te... | 3 | stack_v2_sparse_classes_30k_train_005693 | Implement the Python class `CSI` described below.
Class description:
Critical Success Index metric.
Method signatures and docstrings:
- def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False): Initilize metric.
- def update(self, preds: torch.Tensor, target: torch.Tensor): Update calc... | Implement the Python class `CSI` described below.
Class description:
Critical Success Index metric.
Method signatures and docstrings:
- def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False): Initilize metric.
- def update(self, preds: torch.Tensor, target: torch.Tensor): Update calc... | 655e7dc62f28f142521d3abb7221e4b6860452a4 | <|skeleton|>
class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
<|body_0|>
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""Update calculations."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSI:
"""Critical Success Index metric."""
def __init__(self, threshold, length, reduce_dims=(0, 2, 3, 4), dist_sync_on_step=False):
"""Initilize metric."""
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.threshold = threshold
self.length = length
self.re... | the_stack_v2_python_sparse | metrics/cat_scores.py | fmidev/lagrangian-convolutional-neural-network | train | 9 |
b0db2db35fed328278562d03ca063003c5146a3c | [
"super().__init__(**kwargs)\ntrain_factory, inference_factory, validation_factory, test_factory = (kwargs.get('triples_factory'), kwargs.get('inference_factory'), kwargs.get('validation_factory'), kwargs.get('test_factory'))\nif gnn_encoder is None:\n dim = self.entity_representations[0].shape[0]\n gnn_encode... | <|body_start_0|>
super().__init__(**kwargs)
train_factory, inference_factory, validation_factory, test_factory = (kwargs.get('triples_factory'), kwargs.get('inference_factory'), kwargs.get('validation_factory'), kwargs.get('test_factory'))
if gnn_encoder is None:
dim = self.entity_re... | Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected to be over the full graph | InductiveNodePieceGNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InductiveNodePieceGNN:
"""Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected t... | stack_v2_sparse_classes_75kplus_train_071377 | 5,554 | permissive | [
{
"docstring": "Initialize the model. :param gnn_encoder: an iterable of message passing layers. Defaults to 2-layer CompGCN with Hadamard composition. :param kwargs: additional keyword-based parameters passed to `InductiveNodePiece.__init__`.",
"name": "__init__",
"signature": "def __init__(self, *, gn... | 3 | stack_v2_sparse_classes_30k_train_048546 | Implement the Python class `InductiveNodePieceGNN` described below.
Class description:
Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples A... | Implement the Python class `InductiveNodePieceGNN` described below.
Class description:
Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples A... | 5ff3597b18ab9a220e34361d3c3f262060811df1 | <|skeleton|>
class InductiveNodePieceGNN:
"""Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InductiveNodePieceGNN:
"""Inductive NodePiece with a GNN encoder on top. Overall, it's a 3-step procedure: 1. Featurizing nodes via NodePiece 2. Message passing over the active graph using NodePiece features 3. Scoring function for a given batch of triples As of now, message passing is expected to be over the... | the_stack_v2_python_sparse | src/pykeen/models/inductive/inductive_nodepiece_gnn.py | pykeen/pykeen | train | 1,308 |
e8c704b87c9c494d65f8048b9a6c1e036f7adbee | [
"product_config = ProductConfig.objects.get(pk=pk)\nif product_config.product_stautus != new_status:\n detail_dict = {'word': 'product_stautus', 'name': '产品配置状态', 'new_value': dict(PRODUCT_STATUS)[new_status], 'old_value': dict(PRODUCT_STATUS)[product_config.product_stautus], 'log_id': log_id}\n DetailLog.obj... | <|body_start_0|>
product_config = ProductConfig.objects.get(pk=pk)
if product_config.product_stautus != new_status:
detail_dict = {'word': 'product_stautus', 'name': '产品配置状态', 'new_value': dict(PRODUCT_STATUS)[new_status], 'old_value': dict(PRODUCT_STATUS)[product_config.product_stautus], 'l... | ProConfigLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProConfigLog:
def status_change(self, pk, log_id, new_status):
"""产品配置状态记录 :param pk: :param log_id: :param new_status: :return:"""
<|body_0|>
def porconfig_apply(self, pk, data, log_id):
"""产品配置修改 :param pk: :param data: 修改后的数据 :param log_id: :return:"""
<|b... | stack_v2_sparse_classes_75kplus_train_071378 | 30,222 | no_license | [
{
"docstring": "产品配置状态记录 :param pk: :param log_id: :param new_status: :return:",
"name": "status_change",
"signature": "def status_change(self, pk, log_id, new_status)"
},
{
"docstring": "产品配置修改 :param pk: :param data: 修改后的数据 :param log_id: :return:",
"name": "porconfig_apply",
"signatur... | 2 | stack_v2_sparse_classes_30k_val_000375 | Implement the Python class `ProConfigLog` described below.
Class description:
Implement the ProConfigLog class.
Method signatures and docstrings:
- def status_change(self, pk, log_id, new_status): 产品配置状态记录 :param pk: :param log_id: :param new_status: :return:
- def porconfig_apply(self, pk, data, log_id): 产品配置修改 :par... | Implement the Python class `ProConfigLog` described below.
Class description:
Implement the ProConfigLog class.
Method signatures and docstrings:
- def status_change(self, pk, log_id, new_status): 产品配置状态记录 :param pk: :param log_id: :param new_status: :return:
- def porconfig_apply(self, pk, data, log_id): 产品配置修改 :par... | ff4f09a00a0efb4571fa90c6b32f8b55ce2aa6c4 | <|skeleton|>
class ProConfigLog:
def status_change(self, pk, log_id, new_status):
"""产品配置状态记录 :param pk: :param log_id: :param new_status: :return:"""
<|body_0|>
def porconfig_apply(self, pk, data, log_id):
"""产品配置修改 :param pk: :param data: 修改后的数据 :param log_id: :return:"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProConfigLog:
def status_change(self, pk, log_id, new_status):
"""产品配置状态记录 :param pk: :param log_id: :param new_status: :return:"""
product_config = ProductConfig.objects.get(pk=pk)
if product_config.product_stautus != new_status:
detail_dict = {'word': 'product_stautus', '... | the_stack_v2_python_sparse | applications/log_manage/views.py | z991/neng_backend | train | 1 | |
9e398f3f07fff8a207c57595bd1c708a9f49a06e | [
"try:\n if not isinstance(data['ids'], list):\n return JsonResponse(code='999996', msg='参数有误!')\n for i in data['ids']:\n if not isinstance(i, int):\n return JsonResponse(code='999996', msg='参数有误!')\nexcept KeyError:\n return JsonResponse(code='999996', msg='参数有误!')",
"data = JSO... | <|body_start_0|>
try:
if not isinstance(data['ids'], list):
return JsonResponse(code='999996', msg='参数有误!')
for i in data['ids']:
if not isinstance(i, int):
return JsonResponse(code='999996', msg='参数有误!')
except KeyError:
... | DelCaseProject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelCaseProject:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""删除项目 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if not isinstance(data['ids'], li... | stack_v2_sparse_classes_75kplus_train_071379 | 11,764 | no_license | [
{
"docstring": "校验参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "删除项目 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `DelCaseProject` described below.
Class description:
Implement the DelCaseProject class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 删除项目 :param request: :return: | Implement the Python class `DelCaseProject` described below.
Class description:
Implement the DelCaseProject class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 删除项目 :param request: :return:
<|skeleton|>
class DelCaseProject:
def para... | d65297b71ac9f759d508985ee15564162c285e11 | <|skeleton|>
class DelCaseProject:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""删除项目 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelCaseProject:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
try:
if not isinstance(data['ids'], list):
return JsonResponse(code='999996', msg='参数有误!')
for i in data['ids']:
if not isinstance(i, int):
... | the_stack_v2_python_sparse | automation-test_new/api_test/case/caseProjectList.py | beitou/django_api_test | train | 0 | |
5247ef9797fcb8bd76e899ceb630d13308773ca1 | [
"if self.user:\n return 'Plan:{0}, Taken by: {1}'.format(self.plan.title, self.user.email)\nelse:\n return self.plan",
"subject = 'Your Cheers World Subscription has been Activated'\ncontext_data = {'user': self.user, 'plan': self.plan, 'language': language}\nhtml_template_path = 'emails/subscription-email.... | <|body_start_0|>
if self.user:
return 'Plan:{0}, Taken by: {1}'.format(self.plan.title, self.user.email)
else:
return self.plan
<|end_body_0|>
<|body_start_1|>
subject = 'Your Cheers World Subscription has been Activated'
context_data = {'user': self.user, 'plan'... | This model store the data of bar subscription. | ModelBarSubscription | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelBarSubscription:
"""This model store the data of bar subscription."""
def __str__(self):
"""Returns the string representation of the bar subscription object."""
<|body_0|>
def send_activation_subscription_email(self, language=None):
"""Sends the activation s... | stack_v2_sparse_classes_75kplus_train_071380 | 3,210 | no_license | [
{
"docstring": "Returns the string representation of the bar subscription object.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Sends the activation subscription mail to the user.",
"name": "send_activation_subscription_email",
"signature": "def send_activation... | 2 | stack_v2_sparse_classes_30k_val_001793 | Implement the Python class `ModelBarSubscription` described below.
Class description:
This model store the data of bar subscription.
Method signatures and docstrings:
- def __str__(self): Returns the string representation of the bar subscription object.
- def send_activation_subscription_email(self, language=None): S... | Implement the Python class `ModelBarSubscription` described below.
Class description:
This model store the data of bar subscription.
Method signatures and docstrings:
- def __str__(self): Returns the string representation of the bar subscription object.
- def send_activation_subscription_email(self, language=None): S... | a8389cfa268c74e956358dac3ee925d54948a15c | <|skeleton|>
class ModelBarSubscription:
"""This model store the data of bar subscription."""
def __str__(self):
"""Returns the string representation of the bar subscription object."""
<|body_0|>
def send_activation_subscription_email(self, language=None):
"""Sends the activation s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelBarSubscription:
"""This model store the data of bar subscription."""
def __str__(self):
"""Returns the string representation of the bar subscription object."""
if self.user:
return 'Plan:{0}, Taken by: {1}'.format(self.plan.title, self.user.email)
else:
... | the_stack_v2_python_sparse | cheers/apps/bar/models/subscription.py | prabhjot-s-kbihm-com/python3-cheers | train | 0 |
3d9f1145d9eaeac478fd041b5dfbf668b3a79eff | [
"assert len(master_key) in AES.rounds_by_key_size\nself.n_rounds = AES.rounds_by_key_size[len(master_key)]\nself._key_matrices = self._expand_key(master_key)",
"key_columns = bytes2matrix(master_key)\niteration_size = len(master_key) // _sage_const_4\ni = _sage_const_1\nwhile len(key_columns) < (self.n_rounds + _... | <|body_start_0|>
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
<|end_body_0|>
<|body_start_1|>
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // ... | AES | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_75kplus_train_071381 | 8,781 | permissive | [
{
"docstring": "Initializes the object with a given key.",
"name": "__init__",
"signature": "def __init__(self, master_key)"
},
{
"docstring": "Expands and returns a list of key matrices for the given master_key.",
"name": "_expand_key",
"signature": "def _expand_key(self, master_key)"
... | 3 | stack_v2_sparse_classes_30k_train_000157 | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | cda0db4888322cce759a7362de88fff5cc79f599 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
def _expand_key(self, master_key):... | the_stack_v2_python_sparse | Codegate/2022 Finals/aesmaster/solve.sage.py | Qwaz/solved-hacking-problem | train | 100 | |
b9783d1552ad40417addf9098d64e0de61492871 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % nh == 0\nself.d_k = d_model // nh\nself.nh = nh\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.dropout = nn.Dropout(p=dropout)",
"bsz = x.size(0)\nif mask is not None:\n mask = mask.view(bsz, 1, -1, 1)\nquery, key, value = [l(x).view... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % nh == 0
self.d_k = d_model // nh
self.nh = nh
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
bsz = x.size(0)... | MultiHeadedAttention | [
"GPL-3.0-only",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, nh, d_model, dropout=0.1):
"""Args: nh (int): number of heads d_model (int): input hidden size dropout:"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: x: (N, L, D) mask: (N, L)"""
<|body_1|>
def attention... | stack_v2_sparse_classes_75kplus_train_071382 | 2,423 | permissive | [
{
"docstring": "Args: nh (int): number of heads d_model (int): input hidden size dropout:",
"name": "__init__",
"signature": "def __init__(self, nh, d_model, dropout=0.1)"
},
{
"docstring": "Args: x: (N, L, D) mask: (N, L)",
"name": "forward",
"signature": "def forward(self, x, mask=None... | 3 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, nh, d_model, dropout=0.1): Args: nh (int): number of heads d_model (int): input hidden size dropout:
- def forward(self, x, mask=None):... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, nh, d_model, dropout=0.1): Args: nh (int): number of heads d_model (int): input hidden size dropout:
- def forward(self, x, mask=None):... | 85c50b26eb8941781dc4bb93bce61201aff4643d | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, nh, d_model, dropout=0.1):
"""Args: nh (int): number of heads d_model (int): input hidden size dropout:"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: x: (N, L, D) mask: (N, L)"""
<|body_1|>
def attention... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadedAttention:
def __init__(self, nh, d_model, dropout=0.1):
"""Args: nh (int): number of heads d_model (int): input hidden size dropout:"""
super(MultiHeadedAttention, self).__init__()
assert d_model % nh == 0
self.d_k = d_model // nh
self.nh = nh
self.l... | the_stack_v2_python_sparse | models/intphys/extra/tvqa_plus/self_attention.py | hucvl/craft | train | 12 | |
2e220c2cdda1cb1dff44f5e1369069bd1bb803c3 | [
"if not value:\n value = u''\nelif isinstance(value, (tuple, list)):\n value = u'\\n'.join(value)\nreturn value",
"values = super(StringListField, self).clean(value)\nval = [val.strip() for val in values.splitlines() if val]\nreturn val"
] | <|body_start_0|>
if not value:
value = u''
elif isinstance(value, (tuple, list)):
value = u'\n'.join(value)
return value
<|end_body_0|>
<|body_start_1|>
values = super(StringListField, self).clean(value)
val = [val.strip() for val in values.splitlines() i... | StringListField | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
<|body_0|>
def clean(self, value):
"""Converts a value from the HTML form to ... | stack_v2_sparse_classes_75kplus_train_071383 | 1,735 | permissive | [
{
"docstring": "Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string",
"name": "prepare_value",
"signature": "def prepare_value(self, value)"
},
{
"docstring": "Converts a value from the HTML form to a ListField va... | 2 | stack_v2_sparse_classes_30k_train_017082 | Implement the Python class `StringListField` described below.
Class description:
Implement the StringListField class.
Method signatures and docstrings:
- def prepare_value(self, value): Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode stri... | Implement the Python class `StringListField` described below.
Class description:
Implement the StringListField class.
Method signatures and docstrings:
- def prepare_value(self, value): Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode stri... | 0fcb81e6a5edaf42c00c64faf001fc43b24e11c0 | <|skeleton|>
class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
<|body_0|>
def clean(self, value):
"""Converts a value from the HTML form to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
if not value:
value = u''
elif isinstance(value, (tuple, list)):
value =... | the_stack_v2_python_sparse | fjord/base/forms.py | mozilla/fjord | train | 18 | |
1764e9d847188449878478106bc96aadc087713c | [
"if not nums:\n return 0\npos = 0\nwhile True:\n if len(nums) == 1:\n return 1\n if pos == len(nums) - 1:\n break\n if nums[pos] == nums[pos + 1]:\n del nums[pos + 1]\n continue\n pos += 1\nreturn len(nums)",
"if not nums:\n return 0\ni = 1\nwhile i < len(nums):\n ... | <|body_start_0|>
if not nums:
return 0
pos = 0
while True:
if len(nums) == 1:
return 1
if pos == len(nums) - 1:
break
if nums[pos] == nums[pos + 1]:
del nums[pos + 1]
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates_old(self, nums: List[int]) -> int:
"""老代码 132 ms 15.2 MB Python3"""
<|body_0|>
def removeDuplicates(self, nums: List[int]) -> int:
"""20191021 124 ms 15.3 MB Python3"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_75kplus_train_071384 | 1,174 | no_license | [
{
"docstring": "老代码 132 ms 15.2 MB Python3",
"name": "removeDuplicates_old",
"signature": "def removeDuplicates_old(self, nums: List[int]) -> int"
},
{
"docstring": "20191021 124 ms 15.3 MB Python3",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums: List[int]) ->... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates_old(self, nums: List[int]) -> int: 老代码 132 ms 15.2 MB Python3
- def removeDuplicates(self, nums: List[int]) -> int: 20191021 124 ms 15.3 MB Python3 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates_old(self, nums: List[int]) -> int: 老代码 132 ms 15.2 MB Python3
- def removeDuplicates(self, nums: List[int]) -> int: 20191021 124 ms 15.3 MB Python3
<|skelet... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def removeDuplicates_old(self, nums: List[int]) -> int:
"""老代码 132 ms 15.2 MB Python3"""
<|body_0|>
def removeDuplicates(self, nums: List[int]) -> int:
"""20191021 124 ms 15.3 MB Python3"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicates_old(self, nums: List[int]) -> int:
"""老代码 132 ms 15.2 MB Python3"""
if not nums:
return 0
pos = 0
while True:
if len(nums) == 1:
return 1
if pos == len(nums) - 1:
break
... | the_stack_v2_python_sparse | leetcode/26.remove_duplicates_from_sorted_array.py | iamkissg/leetcode | train | 0 | |
3d74d886c6068490f5546e225ae337483874ee6f | [
"super(ParallelCoattention, self).__init__()\nn_entities = 1 if weight_tying else 2\nwith self.init_scope():\n self.energy_layers = chainer.ChainList(*[links.Bilinear(hidden_dim, out_dim, head) for _ in range(n_entities)])\n self.j_layer = GraphLinear(hidden_dim, out_dim)\nself.hidden_dim = hidden_dim\nself.o... | <|body_start_0|>
super(ParallelCoattention, self).__init__()
n_entities = 1 if weight_tying else 2
with self.init_scope():
self.energy_layers = chainer.ChainList(*[links.Bilinear(hidden_dim, out_dim, head) for _ in range(n_entities)])
self.j_layer = GraphLinear(hidden_dim... | ParallelCoattention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelCoattention:
def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
<|... | stack_v2_sparse_classes_75kplus_train_071385 | 7,885 | permissive | [
{
"docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism",
"name": "__init__",
"signature": "def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True)"
... | 3 | stack_v2_sparse_classes_30k_train_012214 | Implement the Python class `ParallelCoattention` described below.
Class description:
Implement the ParallelCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True): :param hidden_dim: dimension of atom representation :param out_... | Implement the Python class `ParallelCoattention` described below.
Class description:
Implement the ParallelCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True): :param hidden_dim: dimension of atom representation :param out_... | 21b64a3c8cc9bc33718ae09c65aa917e575132eb | <|skeleton|>
class ParallelCoattention:
def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParallelCoattention:
def __init__(self, hidden_dim, out_dim, head, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
super(ParallelCo... | the_stack_v2_python_sparse | models/coattention/parallel_coattention.py | Minys233/GCN-BMP | train | 1 | |
d656aecc6f9511e2114ae366a0a3fcc8175a20d5 | [
"self._email = email\nself._password = password\nself._tracker_source = tracker_source\nself._tracker_client = None",
"if self._tracker_client is not None:\n return\nself._tracker_client = gdata.projecthosting.client.ProjectHostingClient()\nif self._email and self._password:\n self._tracker_client.client_lo... | <|body_start_0|>
self._email = email
self._password = password
self._tracker_source = tracker_source
self._tracker_client = None
<|end_body_0|>
<|body_start_1|>
if self._tracker_client is not None:
return
self._tracker_client = gdata.projecthosting.client.Pro... | Class for accessing the tracker on code.google.com. | TrackerAccess | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackerAccess:
"""Class for accessing the tracker on code.google.com."""
def __init__(self, email='', password='', tracker_source=DEFAULT_TRACKER_SOURCE):
"""TrackerAccess constructor. Args: email: The email address to Login with; may be "" for anonymous access. password: The passwor... | stack_v2_sparse_classes_75kplus_train_071386 | 5,221 | permissive | [
{
"docstring": "TrackerAccess constructor. Args: email: The email address to Login with; may be \"\" for anonymous access. password: The password that goes with the email address; may be \"\" if the email is \"\". tracker_source: A string describing this program. This can be anything you like but should should ... | 3 | stack_v2_sparse_classes_30k_train_015403 | Implement the Python class `TrackerAccess` described below.
Class description:
Class for accessing the tracker on code.google.com.
Method signatures and docstrings:
- def __init__(self, email='', password='', tracker_source=DEFAULT_TRACKER_SOURCE): TrackerAccess constructor. Args: email: The email address to Login wi... | Implement the Python class `TrackerAccess` described below.
Class description:
Class for accessing the tracker on code.google.com.
Method signatures and docstrings:
- def __init__(self, email='', password='', tracker_source=DEFAULT_TRACKER_SOURCE): TrackerAccess constructor. Args: email: The email address to Login wi... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TrackerAccess:
"""Class for accessing the tracker on code.google.com."""
def __init__(self, email='', password='', tracker_source=DEFAULT_TRACKER_SOURCE):
"""TrackerAccess constructor. Args: email: The email address to Login with; may be "" for anonymous access. password: The passwor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrackerAccess:
"""Class for accessing the tracker on code.google.com."""
def __init__(self, email='', password='', tracker_source=DEFAULT_TRACKER_SOURCE):
"""TrackerAccess constructor. Args: email: The email address to Login with; may be "" for anonymous access. password: The password that goes w... | the_stack_v2_python_sparse | third_party/chromite/lib/tracker_access.py | metux/chromium-suckless | train | 5 |
7d9b90ad5ec11e4df24aad2af6cb823e4cfc1142 | [
"stacktrace = Stacktrace()\ncallstack = CallStack(_INFINITY_PRIORITY)\nfor line in stacktrace_string.splitlines():\n is_new_callstack, stack_priority, format_type = self._IsStartOfNewCallStack(line)\n if is_new_callstack:\n if callstack.priority != _INFINITY_PRIORITY and callstack:\n stacktr... | <|body_start_0|>
stacktrace = Stacktrace()
callstack = CallStack(_INFINITY_PRIORITY)
for line in stacktrace_string.splitlines():
is_new_callstack, stack_priority, format_type = self._IsStartOfNewCallStack(line)
if is_new_callstack:
if callstack.priority !=... | FracasParser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FracasParser:
def Parse(self, stacktrace_string, deps):
"""Parse fracas stacktrace string into Stacktrace instance."""
<|body_0|>
def _IsStartOfNewCallStack(self, line):
"""Determine whether a line is a start of a callstack or not. Returns a tuple - (is_new_callstack... | stack_v2_sparse_classes_75kplus_train_071387 | 1,679 | permissive | [
{
"docstring": "Parse fracas stacktrace string into Stacktrace instance.",
"name": "Parse",
"signature": "def Parse(self, stacktrace_string, deps)"
},
{
"docstring": "Determine whether a line is a start of a callstack or not. Returns a tuple - (is_new_callstack, stack_priority, format_type).",
... | 2 | null | Implement the Python class `FracasParser` described below.
Class description:
Implement the FracasParser class.
Method signatures and docstrings:
- def Parse(self, stacktrace_string, deps): Parse fracas stacktrace string into Stacktrace instance.
- def _IsStartOfNewCallStack(self, line): Determine whether a line is a... | Implement the Python class `FracasParser` described below.
Class description:
Implement the FracasParser class.
Method signatures and docstrings:
- def Parse(self, stacktrace_string, deps): Parse fracas stacktrace string into Stacktrace instance.
- def _IsStartOfNewCallStack(self, line): Determine whether a line is a... | ce3728559112bfb3e8b32137eada517aec6d22f9 | <|skeleton|>
class FracasParser:
def Parse(self, stacktrace_string, deps):
"""Parse fracas stacktrace string into Stacktrace instance."""
<|body_0|>
def _IsStartOfNewCallStack(self, line):
"""Determine whether a line is a start of a callstack or not. Returns a tuple - (is_new_callstack... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FracasParser:
def Parse(self, stacktrace_string, deps):
"""Parse fracas stacktrace string into Stacktrace instance."""
stacktrace = Stacktrace()
callstack = CallStack(_INFINITY_PRIORITY)
for line in stacktrace_string.splitlines():
is_new_callstack, stack_priority, f... | the_stack_v2_python_sparse | appengine/findit/crash/fracas_parser.py | eunchong/infra | train | 0 | |
e08f4f06e3825ef67cc1a1d3dc8266917f12d8a6 | [
"self.config = config\nself.logger = logger\nself._runner = None",
"if not self._runner:\n self._runner = Runner(self)\nreturn self._runner"
] | <|body_start_0|>
self.config = config
self.logger = logger
self._runner = None
<|end_body_0|>
<|body_start_1|>
if not self._runner:
self._runner = Runner(self)
return self._runner
<|end_body_1|>
| The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata. | Container | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
"""The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata."""
def __init__(self, config, logger):
"""Args: config(dict): The configuration file decoded logger(logging.Logger)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_071388 | 740 | permissive | [
{
"docstring": "Args: config(dict): The configuration file decoded logger(logging.Logger)",
"name": "__init__",
"signature": "def __init__(self, config, logger)"
},
{
"docstring": "Returns: shelf.bulk_update.runner.Runner",
"name": "runner",
"signature": "def runner(self)"
}
] | 2 | null | Implement the Python class `Container` described below.
Class description:
The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata.
Method signatures and docstrings:
- def __init__(self, config, logger): Args: config(dict): The configuration f... | Implement the Python class `Container` described below.
Class description:
The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata.
Method signatures and docstrings:
- def __init__(self, config, logger): Args: config(dict): The configuration f... | ea59703082402ad3b6454482f0487418295fbd19 | <|skeleton|>
class Container:
"""The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata."""
def __init__(self, config, logger):
"""Args: config(dict): The configuration file decoded logger(logging.Logger)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Container:
"""The goal of this object is to create as little objects as possible in order to provide functionality for a bulk update of metadata."""
def __init__(self, config, logger):
"""Args: config(dict): The configuration file decoded logger(logging.Logger)"""
self.config = config
... | the_stack_v2_python_sparse | shelf/bulk_update/container.py | bfilipov/shelf | train | 0 |
a6b763663dbf5485c2608f660137f035080d391b | [
"for par in oldRule.from_symbols:\n par._set_to_rule(newRule)\n newRule._from_symbols.append(par)\nfor ch in oldRule.to_symbols:\n ch._set_from_rule(newRule)\n newRule._to_symbols.append(ch)\nreturn newRule",
"if oldNode.from_rule is not None and len(oldNode.from_rule.to_symbols) > 0:\n indexParent... | <|body_start_0|>
for par in oldRule.from_symbols:
par._set_to_rule(newRule)
newRule._from_symbols.append(par)
for ch in oldRule.to_symbols:
ch._set_from_rule(newRule)
newRule._to_symbols.append(ch)
return newRule
<|end_body_0|>
<|body_start_1|>
... | Class that aggregate functions modifying the parsed tree. | Manipulations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manipulations:
"""Class that aggregate functions modifying the parsed tree."""
def replaceRule(oldRule, newRule):
"""Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to replace with. :return: New instance attached to the tree."... | stack_v2_sparse_classes_75kplus_train_071389 | 2,616 | permissive | [
{
"docstring": "Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to replace with. :return: New instance attached to the tree.",
"name": "replaceRule",
"signature": "def replaceRule(oldRule, newRule)"
},
{
"docstring": "Replace instance of ... | 3 | stack_v2_sparse_classes_30k_train_005116 | Implement the Python class `Manipulations` described below.
Class description:
Class that aggregate functions modifying the parsed tree.
Method signatures and docstrings:
- def replaceRule(oldRule, newRule): Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to r... | Implement the Python class `Manipulations` described below.
Class description:
Class that aggregate functions modifying the parsed tree.
Method signatures and docstrings:
- def replaceRule(oldRule, newRule): Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to r... | 8308a1fd349bf9ea0d267360cc9a4ab20d1629e8 | <|skeleton|>
class Manipulations:
"""Class that aggregate functions modifying the parsed tree."""
def replaceRule(oldRule, newRule):
"""Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to replace with. :return: New instance attached to the tree."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Manipulations:
"""Class that aggregate functions modifying the parsed tree."""
def replaceRule(oldRule, newRule):
"""Replace instance of Rule with another one. :param oldRule: Instance in the tree. :param newRule: Instance to replace with. :return: New instance attached to the tree."""
fo... | the_stack_v2_python_sparse | grammpy/transforms/Manipulations.py | PatrikValkovic/grammpy | train | 2 |
5b5596b43921f15acc0cc2b0960f5969d439e2a8 | [
"super(AvatarServicesTestMixin, cls).setUpClass()\nsiteconfig = SiteConfiguration.objects.get_current()\ncls._original_settings = siteconfig.settings.copy()",
"super(AvatarServicesTestMixin, self).tearDown()\navatar_services.reset()\nsiteconfig = SiteConfiguration.objects.get_current()\nsiteconfig.settings = self... | <|body_start_0|>
super(AvatarServicesTestMixin, cls).setUpClass()
siteconfig = SiteConfiguration.objects.get_current()
cls._original_settings = siteconfig.settings.copy()
<|end_body_0|>
<|body_start_1|>
super(AvatarServicesTestMixin, self).tearDown()
avatar_services.reset()
... | A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not be automatically undone when the test-case finishes. Instead, we cache the site configura... | AvatarServicesTestMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvatarServicesTestMixin:
"""A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not be automatically undone when the test-... | stack_v2_sparse_classes_75kplus_train_071390 | 1,358 | permissive | [
{
"docstring": "Cache the SiteConfiguration settings object.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Restore the SiteConfiguration settings object.",
"name": "tearDown",
"signature": "def tearDown(self)"
}
] | 2 | null | Implement the Python class `AvatarServicesTestMixin` described below.
Class description:
A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not... | Implement the Python class `AvatarServicesTestMixin` described below.
Class description:
A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class AvatarServicesTestMixin:
"""A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not be automatically undone when the test-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AvatarServicesTestMixin:
"""A testcase mixin for resetting the state of avatar services. The avatar service registry class will change the state of the :py:attr:`SiteConfiguration.settings <djblets.siteconfig.models.SiteConfiguration>` object, which will not be automatically undone when the test-case finishes... | the_stack_v2_python_sparse | reviewboard/avatars/testcase.py | reviewboard/reviewboard | train | 1,141 |
4b691812e776858353dd1e1dc819b625a2281f00 | [
"with self.namespaces('p(x|z,alpha)'):\n with self.namespaces('h(z)'):\n Z = self.build_hidden_layers(Z, diminput=self.params['dim_stochastic'], dimoutput=self.params['p_dim_hidden'], nlayers=self.params['z_generative_layers'], normalization=self.params['p_normlayers'])\n h = T.concatenate([alpha, Z], ... | <|body_start_0|>
with self.namespaces('p(x|z,alpha)'):
with self.namespaces('h(z)'):
Z = self.build_hidden_layers(Z, diminput=self.params['dim_stochastic'], dimoutput=self.params['p_dim_hidden'], nlayers=self.params['z_generative_layers'], normalization=self.params['p_normlayers'])
... | AbstractSingleStochasticLayerSemiVAE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractSingleStochasticLayerSemiVAE:
def build_generative(self, alpha, Z):
"""Build subgraph to estimate conditional params"""
<|body_0|>
def build_inference_Z(self, alpha, hx):
"""return q(z|alpha,h(x))"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071391 | 4,016 | permissive | [
{
"docstring": "Build subgraph to estimate conditional params",
"name": "build_generative",
"signature": "def build_generative(self, alpha, Z)"
},
{
"docstring": "return q(z|alpha,h(x))",
"name": "build_inference_Z",
"signature": "def build_inference_Z(self, alpha, hx)"
}
] | 2 | null | Implement the Python class `AbstractSingleStochasticLayerSemiVAE` described below.
Class description:
Implement the AbstractSingleStochasticLayerSemiVAE class.
Method signatures and docstrings:
- def build_generative(self, alpha, Z): Build subgraph to estimate conditional params
- def build_inference_Z(self, alpha, h... | Implement the Python class `AbstractSingleStochasticLayerSemiVAE` described below.
Class description:
Implement the AbstractSingleStochasticLayerSemiVAE class.
Method signatures and docstrings:
- def build_generative(self, alpha, Z): Build subgraph to estimate conditional params
- def build_inference_Z(self, alpha, h... | 821a1f21b5399d6b50c68cd15869c419933d8ed7 | <|skeleton|>
class AbstractSingleStochasticLayerSemiVAE:
def build_generative(self, alpha, Z):
"""Build subgraph to estimate conditional params"""
<|body_0|>
def build_inference_Z(self, alpha, hx):
"""return q(z|alpha,h(x))"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractSingleStochasticLayerSemiVAE:
def build_generative(self, alpha, Z):
"""Build subgraph to estimate conditional params"""
with self.namespaces('p(x|z,alpha)'):
with self.namespaces('h(z)'):
Z = self.build_hidden_layers(Z, diminput=self.params['dim_stochastic']... | the_stack_v2_python_sparse | models/AbstractSingleStochasticLayerSemiVAE.py | clinicalml/vae_ssl | train | 9 | |
796e49ae886e9e5d8b2c5c29da56dded995563c3 | [
"defValues = {}\ndefValues['opti.initial.model.training.size'] = (1000, None)\ndefValues['opti.acquisition.samp.size'] = (100, None)\ndefValues['opti.prob.acquisition.strategy'] = ('pi', None)\ndefValues['opti.acquisition.ucb.mult'] = (2.0, None)\nself.sample = None\nsuper(BayesianOptimizer, self).__init__(configFi... | <|body_start_0|>
defValues = {}
defValues['opti.initial.model.training.size'] = (1000, None)
defValues['opti.acquisition.samp.size'] = (100, None)
defValues['opti.prob.acquisition.strategy'] = ('pi', None)
defValues['opti.acquisition.ucb.mult'] = (2.0, None)
self.sample =... | optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted | BayesianOptimizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimizer:
"""optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted"""
def __init__(self, configFile, domain):
"""intialize Parameters configFile : configuration file domain : application domain object"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_071392 | 6,378 | permissive | [
{
"docstring": "intialize Parameters configFile : configuration file domain : application domain object",
"name": "__init__",
"signature": "def __init__(self, configFile, domain)"
},
{
"docstring": "run optimizer",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "ru... | 4 | stack_v2_sparse_classes_30k_train_012622 | Implement the Python class `BayesianOptimizer` described below.
Class description:
optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted
Method signatures and docstrings:
- def __init__(self, configFile, domain): intialize Parameters configFile : configuration file d... | Implement the Python class `BayesianOptimizer` described below.
Class description:
optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted
Method signatures and docstrings:
- def __init__(self, configFile, domain): intialize Parameters configFile : configuration file d... | 861fd06b6b7abaffe5e8ca795136ab0fbb2234b5 | <|skeleton|>
class BayesianOptimizer:
"""optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted"""
def __init__(self, configFile, domain):
"""intialize Parameters configFile : configuration file domain : application domain object"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimizer:
"""optimize with bayesian optimizer. Finds max, For min cost function should return cost witj sigh inverted"""
def __init__(self, configFile, domain):
"""intialize Parameters configFile : configuration file domain : application domain object"""
defValues = {}
de... | the_stack_v2_python_sparse | arotau/arotau/optsolo.py | pranab/whakapai | train | 18 |
003fb03da0e935df8c908132c28051ecd760753b | [
"course_id = request.data['course']\ncheck = self._is_instructor_or_ta(course_id, request.user)\nif check is not True:\n return check\nserializer = self.get_serializer(data=request.data)\nif serializer.is_valid():\n serializer.save()\n send_mail(serializer.data['subject'], serializer.data['body'], serializ... | <|body_start_0|>
course_id = request.data['course']
check = self._is_instructor_or_ta(course_id, request.user)
if check is not True:
return check
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
se... | Viewset for `Email`. | EmailViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailViewSet:
"""Viewset for `Email`."""
def create_email(self, request):
"""Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATED` Raises: `HTTP_400_BAD_REQUEST`: Raised due to `create(... | stack_v2_sparse_classes_75kplus_train_071393 | 4,219 | no_license | [
{
"docstring": "Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATED` Raises: `HTTP_400_BAD_REQUEST`: Raised due to `create()` method `HTTP_401_UNAUTHORIZED`: Raised by `IsInstructorOrTA` permission class `HTTP_40... | 3 | stack_v2_sparse_classes_30k_train_019603 | Implement the Python class `EmailViewSet` described below.
Class description:
Viewset for `Email`.
Method signatures and docstrings:
- def create_email(self, request): Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATE... | Implement the Python class `EmailViewSet` described below.
Class description:
Viewset for `Email`.
Method signatures and docstrings:
- def create_email(self, request): Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATE... | ab04535bc307167b2d79fa7e2b37e74e16f63963 | <|skeleton|>
class EmailViewSet:
"""Viewset for `Email`."""
def create_email(self, request):
"""Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATED` Raises: `HTTP_400_BAD_REQUEST`: Raised due to `create(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailViewSet:
"""Viewset for `Email`."""
def create_email(self, request):
"""Adds an email to the course. Args: request (Request): DRF `Request` object Returns: `Response` with the created email data and status `HTTP_201_CREATED` Raises: `HTTP_400_BAD_REQUEST`: Raised due to `create()` method `HT... | the_stack_v2_python_sparse | email_notices/api.py | suraj-iitb/bodhitree | train | 1 |
8386cc3e6407247fb98fe8bd5e810d6c31436eb9 | [
"self.name = name\nself.age = age\nPerson.Count += 1",
"print('name is ', self.name)\nprint('age is ', self.age)\nprint('there are ' + str(Person.Count) + ' person in the class')"
] | <|body_start_0|>
self.name = name
self.age = age
Person.Count += 1
<|end_body_0|>
<|body_start_1|>
print('name is ', self.name)
print('age is ', self.age)
print('there are ' + str(Person.Count) + ' person in the class')
<|end_body_1|>
| classdocs | Person | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
"""classdocs"""
def __init__(self, name, age):
"""Constructor @param: name the name of this person @param: age the age of this person"""
<|body_0|>
def detail(self):
"""the detail infomation of this person"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_071394 | 889 | no_license | [
{
"docstring": "Constructor @param: name the name of this person @param: age the age of this person",
"name": "__init__",
"signature": "def __init__(self, name, age)"
},
{
"docstring": "the detail infomation of this person",
"name": "detail",
"signature": "def detail(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000259 | Implement the Python class `Person` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person
- def detail(self): the detail infomation of this person | Implement the Python class `Person` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person
- def detail(self): the detail infomation of this person
<|skeleton|>
class Person:
... | c7dd6def7ec081b483c3a4cfe334d17c049224c2 | <|skeleton|>
class Person:
"""classdocs"""
def __init__(self, name, age):
"""Constructor @param: name the name of this person @param: age the age of this person"""
<|body_0|>
def detail(self):
"""the detail infomation of this person"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Person:
"""classdocs"""
def __init__(self, name, age):
"""Constructor @param: name the name of this person @param: age the age of this person"""
self.name = name
self.age = age
Person.Count += 1
def detail(self):
"""the detail infomation of this person"""
... | the_stack_v2_python_sparse | offline-only/tkinter/jicheng.py | liucz25/FSGL | train | 1 |
2967dc32092a1a501b1586b65249ae28820f91c7 | [
"self.auth_user = auth_user\nself.permissions = permissions\nself.nested = nested",
"self.no_permission = None\nfmspw = Fmspw.objects.filter(user=self.auth_user, pw_isactive=True).first()\nif not fmspw:\n self.error = \"fmspw object doesn't exists\"\n return False\nuser_level = fmspw.LEVEL_ItmIDid\nself.sec... | <|body_start_0|>
self.auth_user = auth_user
self.permissions = permissions
self.nested = nested
<|end_body_0|>
<|body_start_1|>
self.no_permission = None
fmspw = Fmspw.objects.filter(user=self.auth_user, pw_isactive=True).first()
if not fmspw:
self.error = "f... | PermissionValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionValidator:
def __init__(self, auth_user, permissions: list, nested=False):
""":param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCustomer','mnuDiagnosis'] (from Securitycontrollist.controlname) :param nested: TODO if nested is true control pa... | stack_v2_sparse_classes_75kplus_train_071395 | 2,442 | no_license | [
{
"docstring": ":param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCustomer','mnuDiagnosis'] (from Securitycontrollist.controlname) :param nested: TODO if nested is true control parent permissions considered.",
"name": "__init__",
"signature": "def __init__(self, auth... | 2 | null | Implement the Python class `PermissionValidator` described below.
Class description:
Implement the PermissionValidator class.
Method signatures and docstrings:
- def __init__(self, auth_user, permissions: list, nested=False): :param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCusto... | Implement the Python class `PermissionValidator` described below.
Class description:
Implement the PermissionValidator class.
Method signatures and docstrings:
- def __init__(self, auth_user, permissions: list, nested=False): :param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCusto... | 4c69fc216ec66ed6aa150845a165eb89554d3952 | <|skeleton|>
class PermissionValidator:
def __init__(self, auth_user, permissions: list, nested=False):
""":param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCustomer','mnuDiagnosis'] (from Securitycontrollist.controlname) :param nested: TODO if nested is true control pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PermissionValidator:
def __init__(self, auth_user, permissions: list, nested=False):
""":param auth_user: request.user :param permission: permission list Eg. ['mnuEmpDtl','mnuCustomer','mnuDiagnosis'] (from Securitycontrollist.controlname) :param nested: TODO if nested is true control parent permissio... | the_stack_v2_python_sparse | cl_table/utils.py | Beautesoft/webfebackend | train | 0 | |
6c97b29550da26246311b058d52a3500cbc0ddb0 | [
"super(POSCorpus, self).__init__(*args, **kwargs)\nself.corpus_name = 'pos_' + self.corpus_name\ntrain_sents = open(self.paths['train']).readlines()\nself.train_sents = [s.rstrip().split() for s in train_sents]\ndev_sents = open(self.paths['dev']).readlines()\nself.dev_sents = [s.rstrip().split() for s in dev_sents... | <|body_start_0|>
super(POSCorpus, self).__init__(*args, **kwargs)
self.corpus_name = 'pos_' + self.corpus_name
train_sents = open(self.paths['train']).readlines()
self.train_sents = [s.rstrip().split() for s in train_sents]
dev_sents = open(self.paths['dev']).readlines()
... | A Corpus of POS tag features | POSCorpus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class POSCorpus:
"""A Corpus of POS tag features"""
def __init__(self, *args, **kwargs):
"""We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters ---------- paths_dict : dict a dict with two levels: <corp... | stack_v2_sparse_classes_75kplus_train_071396 | 10,058 | permissive | [
{
"docstring": "We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters ---------- paths_dict : dict a dict with two levels: <corpus_name>: <train/dev/rest> corpus_name : str the <corpus_name> you want to use.",
"name": "__i... | 2 | null | Implement the Python class `POSCorpus` described below.
Class description:
A Corpus of POS tag features
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters -... | Implement the Python class `POSCorpus` described below.
Class description:
A Corpus of POS tag features
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters -... | c45336ce4e9fbb3ce45ce2edc9f7acbb11288623 | <|skeleton|>
class POSCorpus:
"""A Corpus of POS tag features"""
def __init__(self, *args, **kwargs):
"""We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters ---------- paths_dict : dict a dict with two levels: <corp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class POSCorpus:
"""A Corpus of POS tag features"""
def __init__(self, *args, **kwargs):
"""We pass the whole dict containing all the paths for every corpus because it makes it easier to save and manage the cache pickles Parameters ---------- paths_dict : dict a dict with two levels: <corpus_name>: <tr... | the_stack_v2_python_sparse | src/corpus/iest_corpus.py | jabalazs/implicit_emotion | train | 6 |
883249bc722c818afa6852428188d5bd6414be2a | [
"layers_ = list()\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nmodes = ['concat', 'sum', 'mean', 'prod', 'max', 'min', 'logsumexp', 'el... | <|body_start_0|>
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
modes = ['concat', 'sum'... | Tests MergeLayer. | MergeLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071397 | 6,335 | permissive | [
{
"docstring": "Test the logic of MergeLayer.",
"name": "test_layer_logic",
"signature": "def test_layer_logic(self)"
},
{
"docstring": "Test the output of MergeLayer with empty layers.",
"name": "test_empty_merge_layer",
"signature": "def test_empty_merge_layer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026522 | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers. | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers.
<|skeleton|>
class MergeLayerTest:
"... | 931ead9222ca90bfc75c3045dc79fb118de340c9 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
... | the_stack_v2_python_sparse | texar/torch/core/layers_test.py | panaali/texar-pytorch | train | 1 |
bea0d5a6205c1636270eccea38224e80648d6941 | [
"super(LayerNorm, self).__init__()\nself.a2 = nn.Parameter(torch.ones(features))\nself.b2 = nn.Parameter(torch.zeros(features))\nself.eps = eps",
"mean = x.mean(-1, keepdim=True)\nstd = x.std(-1, keepdim=True)\nreturn self.a2 * (x - mean) / (std + self.eps) + self.b2"
] | <|body_start_0|>
super(LayerNorm, self).__init__()
self.a2 = nn.Parameter(torch.ones(features))
self.b2 = nn.Parameter(torch.zeros(features))
self.eps = eps
<|end_body_0|>
<|body_start_1|>
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.... | LayerNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerNorm:
def __init__(self, features, eps=1e-06):
""":param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0"""
<|body_0|>
def forward(self, x):
"""首先对输入变量x求其最后一个维度的均值,并保持输出维度与输入维度一致 接着再求最后一个维度的标准差,然后就是根据规范化公式,用x减去均值除以标准差获得规范化的结果 最后对结果乘以缩放参数,即a2,加上位移参数b2"""... | stack_v2_sparse_classes_75kplus_train_071398 | 15,718 | no_license | [
{
"docstring": ":param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0",
"name": "__init__",
"signature": "def __init__(self, features, eps=1e-06)"
},
{
"docstring": "首先对输入变量x求其最后一个维度的均值,并保持输出维度与输入维度一致 接着再求最后一个维度的标准差,然后就是根据规范化公式,用x减去均值除以标准差获得规范化的结果 最后对结果乘以缩放参数,即a2,加上位移参数b2",
"name":... | 2 | stack_v2_sparse_classes_30k_train_002170 | Implement the Python class `LayerNorm` described below.
Class description:
Implement the LayerNorm class.
Method signatures and docstrings:
- def __init__(self, features, eps=1e-06): :param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0
- def forward(self, x): 首先对输入变量x求其最后一个维度的均值,并保持输出维度与输入维度一致 接着再求最后一个维度的标... | Implement the Python class `LayerNorm` described below.
Class description:
Implement the LayerNorm class.
Method signatures and docstrings:
- def __init__(self, features, eps=1e-06): :param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0
- def forward(self, x): 首先对输入变量x求其最后一个维度的均值,并保持输出维度与输入维度一致 接着再求最后一个维度的标... | 9d1f87a51eea48314d454f84c486d29352eb5b13 | <|skeleton|>
class LayerNorm:
def __init__(self, features, eps=1e-06):
""":param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0"""
<|body_0|>
def forward(self, x):
"""首先对输入变量x求其最后一个维度的均值,并保持输出维度与输入维度一致 接着再求最后一个维度的标准差,然后就是根据规范化公式,用x减去均值除以标准差获得规范化的结果 最后对结果乘以缩放参数,即a2,加上位移参数b2"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayerNorm:
def __init__(self, features, eps=1e-06):
""":param features: 词嵌入的维度 :param eps: 一个足够小的数,在规范化公式的分母中出现,防止分母为0"""
super(LayerNorm, self).__init__()
self.a2 = nn.Parameter(torch.ones(features))
self.b2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def... | the_stack_v2_python_sparse | DeepLearning/Transformer/transformer.py | pxz97/AlgorithmsByPython | train | 1 | |
37de2b04c700a5ef18f66dbe19afdb74f2ea403d | [
"super(Channel_DHT22_Data_File, self).__init__(verbose=verbose)\nself.fname = fname_data\nself.time_wait = time_wait\nself.realtime = realtime\nself.data = None\nself.load_data()",
"if fname:\n self.fname = fname\ndata = []\nwith open(self.fname, 'r') as fi:\n for line in fi.readlines():\n d = np.asa... | <|body_start_0|>
super(Channel_DHT22_Data_File, self).__init__(verbose=verbose)
self.fname = fname_data
self.time_wait = time_wait
self.realtime = realtime
self.data = None
self.load_data()
<|end_body_0|>
<|body_start_1|>
if fname:
self.fname = fname
... | Channel_DHT22_Data_File | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Channel_DHT22_Data_File:
def __init__(self, fname_data, time_wait=5.0, realtime=False, verbose=False):
"""Read raw DHT22 data from specified text file. Parameters ---------- fname_data : File containing data samples. time_wait : number of seconds between polling sensor for new data. real... | stack_v2_sparse_classes_75kplus_train_071399 | 17,936 | no_license | [
{
"docstring": "Read raw DHT22 data from specified text file. Parameters ---------- fname_data : File containing data samples. time_wait : number of seconds between polling sensor for new data. realtime : boolean, if True, then simulate reading data in realtime. If False, then yield data as fast as possible.",
... | 3 | stack_v2_sparse_classes_30k_train_014230 | Implement the Python class `Channel_DHT22_Data_File` described below.
Class description:
Implement the Channel_DHT22_Data_File class.
Method signatures and docstrings:
- def __init__(self, fname_data, time_wait=5.0, realtime=False, verbose=False): Read raw DHT22 data from specified text file. Parameters ---------- fn... | Implement the Python class `Channel_DHT22_Data_File` described below.
Class description:
Implement the Channel_DHT22_Data_File class.
Method signatures and docstrings:
- def __init__(self, fname_data, time_wait=5.0, realtime=False, verbose=False): Read raw DHT22 data from specified text file. Parameters ---------- fn... | 707a72a0cde5f4d622b4029b2e67a7bff21e3ae8 | <|skeleton|>
class Channel_DHT22_Data_File:
def __init__(self, fname_data, time_wait=5.0, realtime=False, verbose=False):
"""Read raw DHT22 data from specified text file. Parameters ---------- fname_data : File containing data samples. time_wait : number of seconds between polling sensor for new data. real... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Channel_DHT22_Data_File:
def __init__(self, fname_data, time_wait=5.0, realtime=False, verbose=False):
"""Read raw DHT22 data from specified text file. Parameters ---------- fname_data : File containing data samples. time_wait : number of seconds between polling sensor for new data. realtime : boolean... | the_stack_v2_python_sparse | sensor_monitor/sensors.py | Who8MyLunch/Sensor-Monitor | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.