blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
709b7a281bac1f3d1f7541e5bddaa9a7e7cf4786 | [
"super(ExtremeDeepNieFineCoattention, self).__init__()\nself.n_lt_layers = 3\nwith self.init_scope():\n self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)\n self.attention_layer_1 = GraphLinear(head, 1, nobias=True)\n self.attention_layer_2 = GraphLinear(head, 1, nobias=True)\n self.prev_lt_l... | <|body_start_0|>
super(ExtremeDeepNieFineCoattention, self).__init__()
self.n_lt_layers = 3
with self.init_scope():
self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)
self.attention_layer_1 = GraphLinear(head, 1, nobias=True)
self.attention_layer_2 ... | TODO | ExtremeDeepNieFineCoattention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtremeDeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":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_36k_train_025700 | 25,561 | 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.identity)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_000174 | Implement the Python class `ExtremeDeepNieFineCoattention` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representatio... | Implement the Python class `ExtremeDeepNieFineCoattention` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representatio... | 21b64a3c8cc9bc33718ae09c65aa917e575132eb | <|skeleton|>
class ExtremeDeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":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_36k | data/stack_v2_sparse_classes_30k | class ExtremeDeepNieFineCoattention:
"""TODO"""
def __init__(self, hidden_dim, out_dim, head, activation=functions.identity):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism"""
super... | the_stack_v2_python_sparse | models/coattention/nie_coattention.py | Minys233/GCN-BMP | train | 1 |
864411f7126302a18ead4a60175233b64d4215fe | [
"q = Queue()\nq.enqueue(1)\nself.assertEqual(q.queue[-1], 1)",
"q = Queue()\nq.enqueue(1)\nq.enqueue(2)\nself.assertEqual(q.queue[-1], 2)",
"q = Queue()\nq.enqueue(None)\nself.assertEqual(q.queue, [])"
] | <|body_start_0|>
q = Queue()
q.enqueue(1)
self.assertEqual(q.queue[-1], 1)
<|end_body_0|>
<|body_start_1|>
q = Queue()
q.enqueue(1)
q.enqueue(2)
self.assertEqual(q.queue[-1], 2)
<|end_body_1|>
<|body_start_2|>
q = Queue()
q.enqueue(None)
... | TestMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMethods:
def test1(self):
"""Test on empty queue."""
<|body_0|>
def test2(self):
"""Test on non-empty queue."""
<|body_1|>
def test3(self):
"""Test with a None object."""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
q = Queu... | stack_v2_sparse_classes_36k_train_025701 | 636 | no_license | [
{
"docstring": "Test on empty queue.",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "Test on non-empty queue.",
"name": "test2",
"signature": "def test2(self)"
},
{
"docstring": "Test with a None object.",
"name": "test3",
"signature": "def test3(self... | 3 | stack_v2_sparse_classes_30k_train_005896 | Implement the Python class `TestMethods` described below.
Class description:
Implement the TestMethods class.
Method signatures and docstrings:
- def test1(self): Test on empty queue.
- def test2(self): Test on non-empty queue.
- def test3(self): Test with a None object. | Implement the Python class `TestMethods` described below.
Class description:
Implement the TestMethods class.
Method signatures and docstrings:
- def test1(self): Test on empty queue.
- def test2(self): Test on non-empty queue.
- def test3(self): Test with a None object.
<|skeleton|>
class TestMethods:
def test... | 794803c69f745c97450091e51ad5fdfc102732eb | <|skeleton|>
class TestMethods:
def test1(self):
"""Test on empty queue."""
<|body_0|>
def test2(self):
"""Test on non-empty queue."""
<|body_1|>
def test3(self):
"""Test with a None object."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMethods:
def test1(self):
"""Test on empty queue."""
q = Queue()
q.enqueue(1)
self.assertEqual(q.queue[-1], 1)
def test2(self):
"""Test on non-empty queue."""
q = Queue()
q.enqueue(1)
q.enqueue(2)
self.assertEqual(q.queue[-1], 2)... | the_stack_v2_python_sparse | hw1/queue/test_enqueue.py | jack-diamond/devops | train | 0 | |
982bec4c20ff24e41acfa99c580b3b2ea6c8620a | [
"n = len(s)\nif n <= 1:\n return s\nmax_res = ''\nfor i in range(n):\n for j in range(i, n):\n sp = s[i:j + 1]\n if sp == sp[::-1]:\n if len(sp) > len(max_res):\n max_res = sp\nreturn max_res",
"n = len(s)\nif n <= 1:\n return s\nmax_res = ''\nfor i in range(n):\n ... | <|body_start_0|>
n = len(s)
if n <= 1:
return s
max_res = ''
for i in range(n):
for j in range(i, n):
sp = s[i:j + 1]
if sp == sp[::-1]:
if len(sp) > len(max_res):
max_res = sp
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""暴力 超时 :type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
"""优化 :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(s)
if n <= 1:
retur... | stack_v2_sparse_classes_36k_train_025702 | 1,660 | no_license | [
{
"docstring": "暴力 超时 :type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": "优化 :type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 暴力 超时 :type s: str :rtype: str
- def longestPalindrome2(self, s): 优化 :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 暴力 超时 :type s: str :rtype: str
- def longestPalindrome2(self, s): 优化 :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalind... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""暴力 超时 :type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
"""优化 :type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
"""暴力 超时 :type s: str :rtype: str"""
n = len(s)
if n <= 1:
return s
max_res = ''
for i in range(n):
for j in range(i, n):
sp = s[i:j + 1]
if sp == sp[::-1]:
... | the_stack_v2_python_sparse | leetcode/5_timeout.py | yanggelinux/algorithm-data-structure | train | 0 | |
4be13360876c4b2e3305ed572bab98f5b638995c | [
"url = self.client.get_url('markets')\nparams = {'exchange': exchange, 'base': base, 'quote': quote}\nresp = requests.get(url, params=params)\nif resp.status_code == 200:\n return resp.json()\nelse:\n return resp.text",
"url = self.client.get_url('market-cap/history')\nparams = {'start': start, 'end': end}\... | <|body_start_0|>
url = self.client.get_url('markets')
params = {'exchange': exchange, 'base': base, 'quote': quote}
resp = requests.get(url, params=params)
if resp.status_code == 200:
return resp.json()
else:
return resp.text
<|end_body_0|>
<|body_start_1... | Markets | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Markets:
def get_markets(self, exchange=None, base=None, quote=None):
"""Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter by Optional :param [str] base: Comma separated list of base currencies to filter by Optional :p... | stack_v2_sparse_classes_36k_train_025703 | 3,056 | permissive | [
{
"docstring": "Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter by Optional :param [str] base: Comma separated list of base currencies to filter by Optional :param [str] quote: Comma separated list of quote currencies to filter by Optional"... | 3 | stack_v2_sparse_classes_30k_train_019631 | Implement the Python class `Markets` described below.
Class description:
Implement the Markets class.
Method signatures and docstrings:
- def get_markets(self, exchange=None, base=None, quote=None): Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter... | Implement the Python class `Markets` described below.
Class description:
Implement the Markets class.
Method signatures and docstrings:
- def get_markets(self, exchange=None, base=None, quote=None): Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter... | 70d864b83a0384be2120cbfddc26d55cc1e22065 | <|skeleton|>
class Markets:
def get_markets(self, exchange=None, base=None, quote=None):
"""Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter by Optional :param [str] base: Comma separated list of base currencies to filter by Optional :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Markets:
def get_markets(self, exchange=None, base=None, quote=None):
"""Returns information on the exchanges and markets that Nomics supports :param str exchange: Nomics Exchange ID to filter by Optional :param [str] base: Comma separated list of base currencies to filter by Optional :param [str] quo... | the_stack_v2_python_sparse | nomics/api/markets.py | luisriverag/nomics-python | train | 0 | |
90f2ae134d6af0ec71b0def9c901600c34b92e5c | [
"dg = Diagnosis.query.get(kf_id)\nif dg is None:\n abort(404, 'could not find {} `{}`'.format('diagnosis', kf_id))\nreturn DiagnosisSchema().jsonify(dg)",
"dg = Diagnosis.query.get(kf_id)\nif dg is None:\n abort(404, 'could not find {} `{}`'.format('diagnosis', kf_id))\nbody = request.get_json(force=True) o... | <|body_start_0|>
dg = Diagnosis.query.get(kf_id)
if dg is None:
abort(404, 'could not find {} `{}`'.format('diagnosis', kf_id))
return DiagnosisSchema().jsonify(dg)
<|end_body_0|>
<|body_start_1|>
dg = Diagnosis.query.get(kf_id)
if dg is None:
abort(404, ... | Diagnosis REST API | DiagnosisAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiagnosisAPI:
"""Diagnosis REST API"""
def get(self, kf_id):
"""Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing diagnosis. Allows partial update of resource --- te... | stack_v2_sparse_classes_36k_train_025704 | 5,021 | permissive | [
{
"docstring": "Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing diagnosis. Allows partial update of resource --- template: path: update_by_id.yml properties: resourc... | 3 | stack_v2_sparse_classes_30k_train_005920 | Implement the Python class `DiagnosisAPI` described below.
Class description:
Diagnosis REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis
- def patch(self, kf_id): Update an existing diagnosis. Allows partial upda... | Implement the Python class `DiagnosisAPI` described below.
Class description:
Diagnosis REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis
- def patch(self, kf_id): Update an existing diagnosis. Allows partial upda... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class DiagnosisAPI:
"""Diagnosis REST API"""
def get(self, kf_id):
"""Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing diagnosis. Allows partial update of resource --- te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiagnosisAPI:
"""Diagnosis REST API"""
def get(self, kf_id):
"""Get a diagnosis by id --- template: path: get_by_id.yml properties: resource: Diagnosis"""
dg = Diagnosis.query.get(kf_id)
if dg is None:
abort(404, 'could not find {} `{}`'.format('diagnosis', kf_id))
... | the_stack_v2_python_sparse | dataservice/api/diagnosis/resources.py | kids-first/kf-api-dataservice | train | 9 |
b18c34502918b94175ea56a6a68f003f5132f416 | [
"node_attributes = {}\nnode_plugin_attributes_query = db().query(cls.model.id, cls.model.attributes).join(models.ClusterPlugin, models.Plugin).filter(cls.model.node_id == node.id, models.ClusterPlugin.enabled.is_(True))\nfor node_plugin_id, attributes in node_plugin_attributes_query:\n for section_name, section_... | <|body_start_0|>
node_attributes = {}
node_plugin_attributes_query = db().query(cls.model.id, cls.model.attributes).join(models.ClusterPlugin, models.Plugin).filter(cls.model.node_id == node.id, models.ClusterPlugin.enabled.is_(True))
for node_plugin_id, attributes in node_plugin_attributes_quer... | NodeClusterPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeClusterPlugin:
def get_all_enabled_attributes_by_node(cls, node):
"""Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :returns: object with plugin Node attributes :rtype: dict"""
<|body_0|>
def add_nodes_for_cluster_p... | stack_v2_sparse_classes_36k_train_025705 | 24,356 | permissive | [
{
"docstring": "Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :returns: object with plugin Node attributes :rtype: dict",
"name": "get_all_enabled_attributes_by_node",
"signature": "def get_all_enabled_attributes_by_node(cls, node)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_003844 | Implement the Python class `NodeClusterPlugin` described below.
Class description:
Implement the NodeClusterPlugin class.
Method signatures and docstrings:
- def get_all_enabled_attributes_by_node(cls, node): Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :retur... | Implement the Python class `NodeClusterPlugin` described below.
Class description:
Implement the NodeClusterPlugin class.
Method signatures and docstrings:
- def get_all_enabled_attributes_by_node(cls, node): Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :retur... | 768ac74a420f822261c4eb8da72f1d8af3c6bbff | <|skeleton|>
class NodeClusterPlugin:
def get_all_enabled_attributes_by_node(cls, node):
"""Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :returns: object with plugin Node attributes :rtype: dict"""
<|body_0|>
def add_nodes_for_cluster_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeClusterPlugin:
def get_all_enabled_attributes_by_node(cls, node):
"""Returns node attributes from enabled plugins :param node: target node instance :type node: models.Node :returns: object with plugin Node attributes :rtype: dict"""
node_attributes = {}
node_plugin_attributes_query... | the_stack_v2_python_sparse | nailgun/nailgun/objects/plugin.py | dis-xcom/fuel-web | train | 0 | |
f42095188b8c408aa3beec93cfd79424ecd5298e | [
"plugin_path = os.path.dirname(WaveGen.__file__) + '/plugins'\nplugin_name = 'Seq'\navailable_plugins = importPluginModulesIn(plugin_path)\nplugin_creator = findPluginCreator(plugin_name, available_plugins)\nparam = {'SAMPLING_RATE': 1024, 'TIME': [0.0, 0.06, 0.07, 0.24, 0.26, 0.43, 0.44, 0.5, 0.5, 0.56, 0.57, 0.74... | <|body_start_0|>
plugin_path = os.path.dirname(WaveGen.__file__) + '/plugins'
plugin_name = 'Seq'
available_plugins = importPluginModulesIn(plugin_path)
plugin_creator = findPluginCreator(plugin_name, available_plugins)
param = {'SAMPLING_RATE': 1024, 'TIME': [0.0, 0.06, 0.07, 0.... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def testSeq(self):
"""TEST length"""
<|body_0|>
def testSine(self):
"""TEST length, discontinuity, period etc."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
plugin_path = os.path.dirname(WaveGen.__file__) + '/plugins'
plugin_name = '... | stack_v2_sparse_classes_36k_train_025706 | 2,155 | no_license | [
{
"docstring": "TEST length",
"name": "testSeq",
"signature": "def testSeq(self)"
},
{
"docstring": "TEST length, discontinuity, period etc.",
"name": "testSine",
"signature": "def testSine(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021580 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testSeq(self): TEST length
- def testSine(self): TEST length, discontinuity, period etc. | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testSeq(self): TEST length
- def testSine(self): TEST length, discontinuity, period etc.
<|skeleton|>
class Test:
def testSeq(self):
"""TEST length"""
<|body_0|... | 979c5fb164fb08856eb78b490d29481c0e4a3f43 | <|skeleton|>
class Test:
def testSeq(self):
"""TEST length"""
<|body_0|>
def testSine(self):
"""TEST length, discontinuity, period etc."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def testSeq(self):
"""TEST length"""
plugin_path = os.path.dirname(WaveGen.__file__) + '/plugins'
plugin_name = 'Seq'
available_plugins = importPluginModulesIn(plugin_path)
plugin_creator = findPluginCreator(plugin_name, available_plugins)
param = {'SAMPLI... | the_stack_v2_python_sparse | masterUser/src_backup/py/WaveGen/ifpass/test_waveform.py | wonjsohn/sarcos | train | 0 | |
27e2db0f96453751978fe2b1455273cfe2e8b1f6 | [
"add_input_output_information(self, input_names, output_name, output_shape)\nself.image_size = np.ascontiguousarray(image_shape, dtype=np.uintp)\nself.filters = np.ascontiguousarray(filters, dtype=np.double)\nself.strides = np.ascontiguousarray(strides, dtype=np.uintp)\nself.output_shape = (c_size_t * 3)(output_sha... | <|body_start_0|>
add_input_output_information(self, input_names, output_name, output_shape)
self.image_size = np.ascontiguousarray(image_shape, dtype=np.uintp)
self.filters = np.ascontiguousarray(filters, dtype=np.double)
self.strides = np.ascontiguousarray(strides, dtype=np.uintp)
... | DeepzonoConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepzonoConv:
def __init__(self, image_shape, filters, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape):
"""Arguments --------- image_shape : numpy.ndarray of shape [height, width, channels] filters : numpy.ndarray the 4D array with the filter we... | stack_v2_sparse_classes_36k_train_025707 | 34,420 | permissive | [
{
"docstring": "Arguments --------- image_shape : numpy.ndarray of shape [height, width, channels] filters : numpy.ndarray the 4D array with the filter weights strides : numpy.ndarray of shape [height, width] padding : str type of padding, either 'VALID' or 'SAME' input_names : iterable iterable with the name o... | 3 | stack_v2_sparse_classes_30k_train_006798 | Implement the Python class `DeepzonoConv` described below.
Class description:
Implement the DeepzonoConv class.
Method signatures and docstrings:
- def __init__(self, image_shape, filters, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape): Arguments --------- image_shape : num... | Implement the Python class `DeepzonoConv` described below.
Class description:
Implement the DeepzonoConv class.
Method signatures and docstrings:
- def __init__(self, image_shape, filters, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape): Arguments --------- image_shape : num... | 8771d3158b2c64a360d5bdfd4433490863257dd6 | <|skeleton|>
class DeepzonoConv:
def __init__(self, image_shape, filters, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape):
"""Arguments --------- image_shape : numpy.ndarray of shape [height, width, channels] filters : numpy.ndarray the 4D array with the filter we... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepzonoConv:
def __init__(self, image_shape, filters, strides, pad_top, pad_left, pad_bottom, pad_right, input_names, output_name, output_shape):
"""Arguments --------- image_shape : numpy.ndarray of shape [height, width, channels] filters : numpy.ndarray the 4D array with the filter weights strides ... | the_stack_v2_python_sparse | tf_verify/deepzono_nodes.py | eth-sri/eran | train | 306 | |
c601381d1f62c28706da15c33f20ee01c1da4966 | [
"msgs = self.get_messages(min_priority)\nmsgs = filter(lambda x: not x._read, msgs)\nreturn msgs",
"msgs = sorted(self.messagebox, key=lambda x: x.timestamp)\nmsgs = filter(lambda x: x.priority >= min_priority, msgs)\nreturn msgs"
] | <|body_start_0|>
msgs = self.get_messages(min_priority)
msgs = filter(lambda x: not x._read, msgs)
return msgs
<|end_body_0|>
<|body_start_1|>
msgs = sorted(self.messagebox, key=lambda x: x.timestamp)
msgs = filter(lambda x: x.priority >= min_priority, msgs)
return msgs
... | Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects. | MessageBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, W... | stack_v2_sparse_classes_36k_train_025708 | 8,668 | no_license | [
{
"docstring": "Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, WARNING, CRITICAL @type min_priority: int @return: A list of objects implementing L{IMessage}. @rtype: list",
"name": "get_unread",
"signature": "def get_unread(self, min_pri... | 2 | null | Implement the Python class `MessageBox` described below.
Class description:
Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects.
Method signatures and docstrings:
- def get_unread(self, min_priority=INFO): Retrieve unread messages. @param min_priority: Optional mi... | Implement the Python class `MessageBox` described below.
Class description:
Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects.
Method signatures and docstrings:
- def get_unread(self, min_priority=INFO): Retrieve unread messages. @param min_priority: Optional mi... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, WARNING, CRITI... | the_stack_v2_python_sparse | Products/ZenWidgets/messaging.py | zenoss/zenoss-prodbin | train | 27 |
95d01c7d2a128691f342859c4b1a4a6c51f3f647 | [
"logic = ArrangementLogic(self.auth, sid, cid)\nparams = ParamsParser(request.JSON)\nids = params.list('ids', desc='排课id列表')\ndata = []\narrangements = PracticeArrangement.objects.get_many(ids)\nfor arrangement in arrangements:\n try:\n logic.arrangement = arrangement\n data.append(logic.get_arrang... | <|body_start_0|>
logic = ArrangementLogic(self.auth, sid, cid)
params = ParamsParser(request.JSON)
ids = params.list('ids', desc='排课id列表')
data = []
arrangements = PracticeArrangement.objects.get_many(ids)
for arrangement in arrangements:
try:
... | PracticeArrangementListMgetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PracticeArrangementListMgetView:
def post(self, request, sid, cid):
"""批量获取排课信息 :param request: :param sid: :param cid: :return:"""
<|body_0|>
def get(self, request, sid, cid):
"""获取排课列表 :param request: :param sid: :param cid: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_025709 | 2,409 | no_license | [
{
"docstring": "批量获取排课信息 :param request: :param sid: :param cid: :return:",
"name": "post",
"signature": "def post(self, request, sid, cid)"
},
{
"docstring": "获取排课列表 :param request: :param sid: :param cid: :return:",
"name": "get",
"signature": "def get(self, request, sid, cid)"
}
] | 2 | null | Implement the Python class `PracticeArrangementListMgetView` described below.
Class description:
Implement the PracticeArrangementListMgetView class.
Method signatures and docstrings:
- def post(self, request, sid, cid): 批量获取排课信息 :param request: :param sid: :param cid: :return:
- def get(self, request, sid, cid): 获取排... | Implement the Python class `PracticeArrangementListMgetView` described below.
Class description:
Implement the PracticeArrangementListMgetView class.
Method signatures and docstrings:
- def post(self, request, sid, cid): 批量获取排课信息 :param request: :param sid: :param cid: :return:
- def get(self, request, sid, cid): 获取排... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class PracticeArrangementListMgetView:
def post(self, request, sid, cid):
"""批量获取排课信息 :param request: :param sid: :param cid: :return:"""
<|body_0|>
def get(self, request, sid, cid):
"""获取排课列表 :param request: :param sid: :param cid: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PracticeArrangementListMgetView:
def post(self, request, sid, cid):
"""批量获取排课信息 :param request: :param sid: :param cid: :return:"""
logic = ArrangementLogic(self.auth, sid, cid)
params = ParamsParser(request.JSON)
ids = params.list('ids', desc='排课id列表')
data = []
... | the_stack_v2_python_sparse | FireHydrant/server/practice/views/course/arrangement/list_mget.py | shoogoome/FireHydrant | train | 4 | |
76abed78295e1ce2c6cf892eb68aa3cb7b649ba0 | [
"extension_hooks = list()\neggs = find_eggs(self.rootDir)\nfactory = EggPMExtensionFactory()\nfor egg in eggs:\n eggfile = egg.location\n sys.path.append(eggfile)\n for filePointer, path in self._generateExtensionConfigFilePointers(eggfile):\n inifile = pylabs.inifile.IniFile(filePointer)\n h... | <|body_start_0|>
extension_hooks = list()
eggs = find_eggs(self.rootDir)
factory = EggPMExtensionFactory()
for egg in eggs:
eggfile = egg.location
sys.path.append(eggfile)
for filePointer, path in self._generateExtensionConfigFilePointers(eggfile):
... | Extension info finder class for egg extensions | EggExtensionInfoFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EggExtensionInfoFinder:
"""Extension info finder class for egg extensions"""
def find(self):
"""Find the extensions info for extensions in egg format"""
<|body_0|>
def _generateExtensionConfigFilePointers(self, eggFileName):
"""Generate file pointers and paths fo... | stack_v2_sparse_classes_36k_train_025710 | 16,327 | no_license | [
{
"docstring": "Find the extensions info for extensions in egg format",
"name": "find",
"signature": "def find(self)"
},
{
"docstring": "Generate file pointers and paths for each extension config file in a egg file. The generated paths are the internal paths of the extensions in the egg file. No... | 2 | stack_v2_sparse_classes_30k_train_004066 | Implement the Python class `EggExtensionInfoFinder` described below.
Class description:
Extension info finder class for egg extensions
Method signatures and docstrings:
- def find(self): Find the extensions info for extensions in egg format
- def _generateExtensionConfigFilePointers(self, eggFileName): Generate file ... | Implement the Python class `EggExtensionInfoFinder` described below.
Class description:
Extension info finder class for egg extensions
Method signatures and docstrings:
- def find(self): Find the extensions info for extensions in egg format
- def _generateExtensionConfigFilePointers(self, eggFileName): Generate file ... | 53d349fa6bee0ccead29afd6676979b44c109a61 | <|skeleton|>
class EggExtensionInfoFinder:
"""Extension info finder class for egg extensions"""
def find(self):
"""Find the extensions info for extensions in egg format"""
<|body_0|>
def _generateExtensionConfigFilePointers(self, eggFileName):
"""Generate file pointers and paths fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EggExtensionInfoFinder:
"""Extension info finder class for egg extensions"""
def find(self):
"""Find the extensions info for extensions in egg format"""
extension_hooks = list()
eggs = find_eggs(self.rootDir)
factory = EggPMExtensionFactory()
for egg in eggs:
... | the_stack_v2_python_sparse | core/extensions/PMExtensions.py | racktivity/ext-pylabs-core | train | 0 |
e911e0a791e9cbc588819f488678cec3f0581a50 | [
"import django.template.loaders.app_directories as app_directories\nfrom mezzanine.conf import settings\ncontext_name = 'OVEREXTENDS_DIRS'\nif context_name not in context:\n context[context_name] = {}\nif name not in context[context_name]:\n all_dirs = list(chain.from_iterable([template_engine.get('DIRS', [])... | <|body_start_0|>
import django.template.loaders.app_directories as app_directories
from mezzanine.conf import settings
context_name = 'OVEREXTENDS_DIRS'
if context_name not in context:
context[context_name] = {}
if name not in context[context_name]:
all_di... | Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templates that extend other app templates with the same relative name/path. We use our ... | OverExtendsNode | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OverExtendsNode:
"""Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templates that extend other app templates wi... | stack_v2_sparse_classes_36k_train_025711 | 6,331 | permissive | [
{
"docstring": "Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name/path to be discovered, so that circular template inheritance can occur.",
... | 2 | stack_v2_sparse_classes_30k_train_021354 | Implement the Python class `OverExtendsNode` described below.
Class description:
Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templ... | Implement the Python class `OverExtendsNode` described below.
Class description:
Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templ... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class OverExtendsNode:
"""Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templates that extend other app templates wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OverExtendsNode:
"""Allows the template ``foo/bar.html`` to extend ``foo/bar.html``, given that there is another version of it that can be loaded. This allows templates to be created in a project that extend their app template counterparts, or even app templates that extend other app templates with the same r... | the_stack_v2_python_sparse | mezzanine/template/loader_tags.py | fermorltd/mezzanine | train | 6 |
5d38f5c163c0867c095f5cdfa16848a3ed3b84e8 | [
"if root == None:\n return 0\n\ndef numberOfBinaryTree(root):\n if root.right == None and root.left == None:\n count_right = 0\n count_left = 0\n maxsum = 0\n return (count_right, count_left, maxsum)\n if root.right != None:\n count_right_r, count_left_r, maxsum_right = n... | <|body_start_0|>
if root == None:
return 0
def numberOfBinaryTree(root):
if root.right == None and root.left == None:
count_right = 0
count_left = 0
maxsum = 0
return (count_right, count_left, maxsum)
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
<|body_0|>
def diameterOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 72ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root == None:
... | stack_v2_sparse_classes_36k_train_025712 | 2,564 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int 79ms",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int 72ms",
"name": "diameterOfBinaryTree_1",
"signature": "def diameterOfBinaryTree_1(self, root)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 79ms
- def diameterOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 72ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 79ms
- def diameterOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 72ms
<|skeleton|>
class So... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
<|body_0|>
def diameterOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 72ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 79ms"""
if root == None:
return 0
def numberOfBinaryTree(root):
if root.right == None and root.left == None:
count_right = 0
count_left = 0
... | the_stack_v2_python_sparse | DiameterOfBinaryTree_543.py | 953250587/leetcode-python | train | 2 | |
76b96fdb7be3fdaa7f2210d3e995cc250bb0a96d | [
"from ec4vis.datasource import Datasource\nfrom ec4vis.plugins.filesystem_datasource_page import FilesystemDatasourcePage\nframe = wx.Frame(None, -1, u'DatasourcePanel Demo')\ndatasource = Datasource()\ndatasource_panel = DatasourcePanel(frame, -1, datasource=datasource)\nfs1_id, fs1_page = datasource_panel.noteboo... | <|body_start_0|>
from ec4vis.datasource import Datasource
from ec4vis.plugins.filesystem_datasource_page import FilesystemDatasourcePage
frame = wx.Frame(None, -1, u'DatasourcePanel Demo')
datasource = Datasource()
datasource_panel = DatasourcePanel(frame, -1, datasource=datasour... | Demonstrative application. | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Demonstrative application."""
def OnInit(self):
"""Initializer."""
<|body_0|>
def OnDatasourceChanged(self, event):
"""Demo handler for DatasourceChagedEvent."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from ec4vis.datasource import ... | stack_v2_sparse_classes_36k_train_025713 | 4,220 | no_license | [
{
"docstring": "Initializer.",
"name": "OnInit",
"signature": "def OnInit(self)"
},
{
"docstring": "Demo handler for DatasourceChagedEvent.",
"name": "OnDatasourceChanged",
"signature": "def OnDatasourceChanged(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017661 | Implement the Python class `App` described below.
Class description:
Demonstrative application.
Method signatures and docstrings:
- def OnInit(self): Initializer.
- def OnDatasourceChanged(self, event): Demo handler for DatasourceChagedEvent. | Implement the Python class `App` described below.
Class description:
Demonstrative application.
Method signatures and docstrings:
- def OnInit(self): Initializer.
- def OnDatasourceChanged(self, event): Demo handler for DatasourceChagedEvent.
<|skeleton|>
class App:
"""Demonstrative application."""
def OnIn... | 016515772e3ca4d9e59319450fc7a13668f00d11 | <|skeleton|>
class App:
"""Demonstrative application."""
def OnInit(self):
"""Initializer."""
<|body_0|>
def OnDatasourceChanged(self, event):
"""Demo handler for DatasourceChagedEvent."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class App:
"""Demonstrative application."""
def OnInit(self):
"""Initializer."""
from ec4vis.datasource import Datasource
from ec4vis.plugins.filesystem_datasource_page import FilesystemDatasourcePage
frame = wx.Frame(None, -1, u'DatasourcePanel Demo')
datasource = Datas... | the_stack_v2_python_sparse | ec4vis/datasource/panel.py | ecell/ecell4-vis | train | 0 |
3f2182fed3b446fed3e3b342c1f22ddb93e5d681 | [
"self._dbName = os.environ['MOPS_DBINSTANCE']\nself._instance = mopsInstance = Instance(self._dbName)\nself._conn = self._instance.get_dbh()\nself._cursor = self._conn.cursor()\nsql = 'select d.derivedobject_id, d.object_name ' + 'from derivedobjects d'\nn = self._cursor.execute(sql)\nif not n:\n raise Exception... | <|body_start_0|>
self._dbName = os.environ['MOPS_DBINSTANCE']
self._instance = mopsInstance = Instance(self._dbName)
self._conn = self._instance.get_dbh()
self._cursor = self._conn.cursor()
sql = 'select d.derivedobject_id, d.object_name ' + 'from derivedobjects d'
n = se... | DerivedObjectTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DerivedObjectTest:
def setUp(self):
"""Just create a DerivedObject instance from data in the DB. We will use that instance in our tests."""
<|body_0|>
def testFetchTracklets(self):
"""Look at the number of tracklets that make up this object. Then invoke its fetchTrac... | stack_v2_sparse_classes_36k_train_025714 | 17,613 | no_license | [
{
"docstring": "Just create a DerivedObject instance from data in the DB. We will use that instance in our tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Look at the number of tracklets that make up this object. Then invoke its fetchTracklets() method and compare res... | 4 | stack_v2_sparse_classes_30k_train_019160 | Implement the Python class `DerivedObjectTest` described below.
Class description:
Implement the DerivedObjectTest class.
Method signatures and docstrings:
- def setUp(self): Just create a DerivedObject instance from data in the DB. We will use that instance in our tests.
- def testFetchTracklets(self): Look at the n... | Implement the Python class `DerivedObjectTest` described below.
Class description:
Implement the DerivedObjectTest class.
Method signatures and docstrings:
- def setUp(self): Just create a DerivedObject instance from data in the DB. We will use that instance in our tests.
- def testFetchTracklets(self): Look at the n... | 06858b7e935243da7a3f55b3e5097d6440e0c1c2 | <|skeleton|>
class DerivedObjectTest:
def setUp(self):
"""Just create a DerivedObject instance from data in the DB. We will use that instance in our tests."""
<|body_0|>
def testFetchTracklets(self):
"""Look at the number of tracklets that make up this object. Then invoke its fetchTrac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DerivedObjectTest:
def setUp(self):
"""Just create a DerivedObject instance from data in the DB. We will use that instance in our tests."""
self._dbName = os.environ['MOPS_DBINSTANCE']
self._instance = mopsInstance = Instance(self._dbName)
self._conn = self._instance.get_dbh()
... | the_stack_v2_python_sparse | python/MOPS/test.py | ldenneau/mopsng | train | 0 | |
3b190e7412dc2e4ac29d30904af216a2f6bde551 | [
"task_counts = collections.Counter(tasks).values()\nM = max(task_counts)\nMct = task_counts.count(M)\nreturn max(len(tasks), (M - 1) * (N + 1) + Mct)",
"n += 1\nans = 0\nd = collections.Counter(tasks)\nheap = [-c for c in d.values()]\nheapq.heapify(heap)\nwhile heap:\n stack = []\n cnt = 0\n for _ in ran... | <|body_start_0|>
task_counts = collections.Counter(tasks).values()
M = max(task_counts)
Mct = task_counts.count(M)
return max(len(tasks), (M - 1) * (N + 1) + Mct)
<|end_body_0|>
<|body_start_1|>
n += 1
ans = 0
d = collections.Counter(tasks)
heap = [-c for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def _leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
task... | stack_v2_sparse_classes_36k_train_025715 | 1,366 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "_leastInterval",
"signature": "def _leastInterval(self, tasks, n)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def _leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def _leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
<|skelet... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def _leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
task_counts = collections.Counter(tasks).values()
M = max(task_counts)
Mct = task_counts.count(M)
return max(len(tasks), (M - 1) * (N + 1) + Mct)
def _leastInterval(s... | the_stack_v2_python_sparse | leetcode7/leastInterval.py | lizyang95/leetcode | train | 0 | |
658f89a78052844d178937b959d34a0b1e1849e2 | [
"output_mediator = self._CreateOutputMediator()\nself._output_writer = cli_test_lib.TestOutputWriter()\nself._output_module = json_out.JsonOutputModule(output_mediator, output_writer=self._output_writer)\nself._event_object = JsonTestEvent()",
"expected_header = b'{'\nself._output_module.WriteHeader()\nheader = s... | <|body_start_0|>
output_mediator = self._CreateOutputMediator()
self._output_writer = cli_test_lib.TestOutputWriter()
self._output_module = json_out.JsonOutputModule(output_mediator, output_writer=self._output_writer)
self._event_object = JsonTestEvent()
<|end_body_0|>
<|body_start_1|>
... | Tests for the JSON outputter. | JsonOutputTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonOutputTest:
"""Tests for the JSON outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
<|body_0|>
def testWriteHeader(self):
"""Tests the WriteHeader functions."""
<|body_1|>
def testWriteFooter(self):
"""Tests t... | stack_v2_sparse_classes_36k_train_025716 | 3,943 | permissive | [
{
"docstring": "Sets up the objects needed for this test.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the WriteHeader functions.",
"name": "testWriteHeader",
"signature": "def testWriteHeader(self)"
},
{
"docstring": "Tests the WriteFooter functions... | 4 | stack_v2_sparse_classes_30k_train_002094 | Implement the Python class `JsonOutputTest` described below.
Class description:
Tests for the JSON outputter.
Method signatures and docstrings:
- def setUp(self): Sets up the objects needed for this test.
- def testWriteHeader(self): Tests the WriteHeader functions.
- def testWriteFooter(self): Tests the WriteFooter ... | Implement the Python class `JsonOutputTest` described below.
Class description:
Tests for the JSON outputter.
Method signatures and docstrings:
- def setUp(self): Sets up the objects needed for this test.
- def testWriteHeader(self): Tests the WriteHeader functions.
- def testWriteFooter(self): Tests the WriteFooter ... | f525298bb1dd8f0fecd16d28acc443785ffe88c3 | <|skeleton|>
class JsonOutputTest:
"""Tests for the JSON outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
<|body_0|>
def testWriteHeader(self):
"""Tests the WriteHeader functions."""
<|body_1|>
def testWriteFooter(self):
"""Tests t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonOutputTest:
"""Tests for the JSON outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
output_mediator = self._CreateOutputMediator()
self._output_writer = cli_test_lib.TestOutputWriter()
self._output_module = json_out.JsonOutputModule(output_... | the_stack_v2_python_sparse | plaso/output/json_out_test.py | cnbird1999/plaso | train | 0 |
b4ab4001676cbef4a5771716361a61e96235bd64 | [
"from .models import CandleEurUsdM1Rate, CandleEurUsdDRate, CandleEurUsdH1Rate, CandleEurUsdM5Rate\nfrom .models import CandleUsdJpyM1Rate, CandleUsdJpyDRate, CandleUsdJpyH1Rate, CandleUsdJpyM5Rate\nfrom .models import CandleAudUsdDRate, CandleAudUsdH1Rate, CandleAudUsdM1Rate, CandleAudUsdM5Rate\nfrom .models impor... | <|body_start_0|>
from .models import CandleEurUsdM1Rate, CandleEurUsdDRate, CandleEurUsdH1Rate, CandleEurUsdM5Rate
from .models import CandleUsdJpyM1Rate, CandleUsdJpyDRate, CandleUsdJpyH1Rate, CandleUsdJpyM5Rate
from .models import CandleAudUsdDRate, CandleAudUsdH1Rate, CandleAudUsdM1Rate, Cand... | CurrencyPairToTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrencyPairToTable:
def get_table(cls, currency_pair, granularity):
""":param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase"""
<|body_0|>
def get_ma_table(cls, currency_pair):
""":param currency_pair: CurrencyPair :rtype : M... | stack_v2_sparse_classes_36k_train_025717 | 4,696 | no_license | [
{
"docstring": ":param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase",
"name": "get_table",
"signature": "def get_table(cls, currency_pair, granularity)"
},
{
"docstring": ":param currency_pair: CurrencyPair :rtype : MovingAverageBase",
"name": "get_... | 2 | null | Implement the Python class `CurrencyPairToTable` described below.
Class description:
Implement the CurrencyPairToTable class.
Method signatures and docstrings:
- def get_table(cls, currency_pair, granularity): :param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase
- def get_ma_... | Implement the Python class `CurrencyPairToTable` described below.
Class description:
Implement the CurrencyPairToTable class.
Method signatures and docstrings:
- def get_table(cls, currency_pair, granularity): :param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase
- def get_ma_... | 40e4d4a54865563d53b539a47fc5ce940c3cc9e1 | <|skeleton|>
class CurrencyPairToTable:
def get_table(cls, currency_pair, granularity):
""":param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase"""
<|body_0|>
def get_ma_table(cls, currency_pair):
""":param currency_pair: CurrencyPair :rtype : M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrencyPairToTable:
def get_table(cls, currency_pair, granularity):
""":param currency_pair: CurrencyPair :param granularity: Granularity :rtype : CurrencyCandleBase"""
from .models import CandleEurUsdM1Rate, CandleEurUsdDRate, CandleEurUsdH1Rate, CandleEurUsdM5Rate
from .models impor... | the_stack_v2_python_sparse | niku/module/rate/consts.py | webclinic017/histdata | train | 0 | |
e9e9697a55a6d343bbc1c5c3f0bff4894b3b5a60 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = True\nuser.is_staff = True... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_025718 | 7,049 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_017369 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 0f507783503de5cd9202e7d6bf63fc5ae3c26272 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | AutoOps/web/models.py | dba-base/python-homework | train | 3 | |
dc24b79c0332d962d9da76f770a613b2143f523d | [
"view = super().as_view(*args, **initkwargs)\n\nasync def async_view(*args, **kwargs):\n return await view(*args, **kwargs)\nasync_view.csrf_exempt = True\nreturn async_view",
"self.args = args\nself.kwargs = kwargs\nrequest = self.initialize_request(request, *args, **kwargs)\nself.request = request\nself.head... | <|body_start_0|>
view = super().as_view(*args, **initkwargs)
async def async_view(*args, **kwargs):
return await view(*args, **kwargs)
async_view.csrf_exempt = True
return async_view
<|end_body_0|>
<|body_start_1|>
self.args = args
self.kwargs = kwargs
... | Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass | AsyncMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async view."""
<|body_0|... | stack_v2_sparse_classes_36k_train_025719 | 4,309 | permissive | [
{
"docstring": "Make Django process the view as an async view.",
"name": "as_view",
"signature": "def as_view(cls, *args, **initkwargs)"
},
{
"docstring": "Add async support.",
"name": "dispatch",
"signature": "async def dispatch(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `AsyncMixin` described below.
Class description:
Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass
Method signatures and docstrings:
- def as_view(cls, *args, **initkwargs): Make Djang... | Implement the Python class `AsyncMixin` described below.
Class description:
Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass
Method signatures and docstrings:
- def as_view(cls, *args, **initkwargs): Make Djang... | 8c633e0a3821beb839ed120c4514c5733e675862 | <|skeleton|>
class AsyncMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async view."""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. class MyViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async view."""
view = super().as_view... | the_stack_v2_python_sparse | src/api/bkuser_core/common/async_utils.py | robert871126/bk-user | train | 0 |
f14b844b5bcf5cd333c3325c16c84b5fca2a9b41 | [
"if start_date and end_date:\n tweets, retweets = tweepy_getter.get_tweets_by_user(id, num_tweets, start_date, end_date)\nelif start_date or end_date:\n raise Exception('Please provide valid start and end dates')\nelse:\n tweets, retweets = tweepy_getter.get_tweets_by_user(id, num_tweets)\ntweet_setter.sto... | <|body_start_0|>
if start_date and end_date:
tweets, retweets = tweepy_getter.get_tweets_by_user(id, num_tweets, start_date, end_date)
elif start_date or end_date:
raise Exception('Please provide valid start and end dates')
else:
tweets, retweets = tweepy_gett... | Download Tweets for use in future algorithms. | TwitterTweetDownloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterTweetDownloader:
"""Download Tweets for use in future algorithms."""
def gen_user_tweets(self, id: Union[str, int], tweepy_getter, tweet_setter, num_tweets=None, start_date=None, end_date=None) -> List[Tweet]:
"""Retrieves tweets from twitter from a given user, and stores them... | stack_v2_sparse_classes_36k_train_025720 | 7,540 | no_license | [
{
"docstring": "Retrieves tweets from twitter from a given user, and stores them @param id the id or username of the user @param tweepy_getter the dao to retrieve tweets from tweepy @param tweept_setter the dao to store tweets with @param num_tweets the number of tweets to retrieve @param start_date - Optional,... | 2 | stack_v2_sparse_classes_30k_train_017577 | Implement the Python class `TwitterTweetDownloader` described below.
Class description:
Download Tweets for use in future algorithms.
Method signatures and docstrings:
- def gen_user_tweets(self, id: Union[str, int], tweepy_getter, tweet_setter, num_tweets=None, start_date=None, end_date=None) -> List[Tweet]: Retriev... | Implement the Python class `TwitterTweetDownloader` described below.
Class description:
Download Tweets for use in future algorithms.
Method signatures and docstrings:
- def gen_user_tweets(self, id: Union[str, int], tweepy_getter, tweet_setter, num_tweets=None, start_date=None, end_date=None) -> List[Tweet]: Retriev... | 33a3fa38ad4dcdd54ff583da15dcd67c99ad9701 | <|skeleton|>
class TwitterTweetDownloader:
"""Download Tweets for use in future algorithms."""
def gen_user_tweets(self, id: Union[str, int], tweepy_getter, tweet_setter, num_tweets=None, start_date=None, end_date=None) -> List[Tweet]:
"""Retrieves tweets from twitter from a given user, and stores them... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwitterTweetDownloader:
"""Download Tweets for use in future algorithms."""
def gen_user_tweets(self, id: Union[str, int], tweepy_getter, tweet_setter, num_tweets=None, start_date=None, end_date=None) -> List[Tweet]:
"""Retrieves tweets from twitter from a given user, and stores them @param id th... | the_stack_v2_python_sparse | src/process/download/twitter_downloader.py | ReinaKousaka/core | train | 0 |
be924fc8b8b542ea191cc049ab0c733c260a0012 | [
"order_id = request.GET.get('order_id')\nuser = request.user\ntry:\n OrderInfo.objects.get(order_id=order_id, user=request.user)\nexcept OrderInfo.DoesNotExist:\n return http.HttpResponseNotFound('订单不存在')\ntry:\n uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False)\nexcept Exc... | <|body_start_0|>
order_id = request.GET.get('order_id')
user = request.user
try:
OrderInfo.objects.get(order_id=order_id, user=request.user)
except OrderInfo.DoesNotExist:
return http.HttpResponseNotFound('订单不存在')
try:
uncomment_goods = OrderGo... | 订单商品评价 | OrderCommentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderCommentView:
"""订单商品评价"""
def get(self, request):
"""展示商品评价页面"""
<|body_0|>
def post(self, request):
"""保存评价订单商品"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
order_id = request.GET.get('order_id')
user = request.user
try:... | stack_v2_sparse_classes_36k_train_025721 | 16,199 | no_license | [
{
"docstring": "展示商品评价页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "保存评价订单商品",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018220 | Implement the Python class `OrderCommentView` described below.
Class description:
订单商品评价
Method signatures and docstrings:
- def get(self, request): 展示商品评价页面
- def post(self, request): 保存评价订单商品 | Implement the Python class `OrderCommentView` described below.
Class description:
订单商品评价
Method signatures and docstrings:
- def get(self, request): 展示商品评价页面
- def post(self, request): 保存评价订单商品
<|skeleton|>
class OrderCommentView:
"""订单商品评价"""
def get(self, request):
"""展示商品评价页面"""
<|body_0|... | 9081dc0d16090f23c006727934880f0e79d1a7f7 | <|skeleton|>
class OrderCommentView:
"""订单商品评价"""
def get(self, request):
"""展示商品评价页面"""
<|body_0|>
def post(self, request):
"""保存评价订单商品"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderCommentView:
"""订单商品评价"""
def get(self, request):
"""展示商品评价页面"""
order_id = request.GET.get('order_id')
user = request.user
try:
OrderInfo.objects.get(order_id=order_id, user=request.user)
except OrderInfo.DoesNotExist:
return http.Http... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/orders/views.py | lisa530/meiduo | train | 0 |
e84b887399f052197ac82623ac2a10aaedea910c | [
"cur = head\nwhile cur != None and cur.next != None:\n if cur.val == cur.next.val:\n tmp = cur.next\n cur.next = cur.next.next\n del tmp\n else:\n cur = cur.next",
"dummy = ListNode(-1)\ndummy.next = head\ncur = dummy\nwhile cur != None and cur.next != None and (cur.next.next != ... | <|body_start_0|>
cur = head
while cur != None and cur.next != None:
if cur.val == cur.next.val:
tmp = cur.next
cur.next = cur.next.next
del tmp
else:
cur = cur.next
<|end_body_0|>
<|body_start_1|>
dummy = Li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates_ii(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
while... | stack_v2_sparse_classes_36k_train_025722 | 1,479 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates_ii",
"signature": "def deleteDuplicates_ii(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates_ii(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates_ii(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates_ii(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
cur = head
while cur != None and cur.next != None:
if cur.val == cur.next.val:
tmp = cur.next
cur.next = cur.next.next
del tmp
... | the_stack_v2_python_sparse | 2019/list/remove_duplicates_from_sorted_list_83.py | yehongyu/acode | train | 0 | |
70b8a85b381963b4a90c4dff268b40a6ccba2ced | [
"super(DeepNAGNet, self).__init__()\nself.latent_dim = latent_dim\nself.output_dim = output_dim\nself.num_classes = num_classes\nself.gru1 = nn.GRU(latent_dim + num_classes, 128, 1, batch_first=True)\nself.gru2 = nn.GRU(128, 256, 1, batch_first=True)\nself.gru3 = nn.GRU(256, 512, 1, batch_first=True)\nself.fc = nn.... | <|body_start_0|>
super(DeepNAGNet, self).__init__()
self.latent_dim = latent_dim
self.output_dim = output_dim
self.num_classes = num_classes
self.gru1 = nn.GRU(latent_dim + num_classes, 128, 1, batch_first=True)
self.gru2 = nn.GRU(128, 256, 1, batch_first=True)
se... | DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN. | DeepNAGNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepNAGNet:
"""DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN."""
def __init__(self, latent_dim, output_dim, num_classes):
"""Initializes a new DeepNAG model. :param latent_dim: the latent ... | stack_v2_sparse_classes_36k_train_025723 | 10,275 | permissive | [
{
"docstring": "Initializes a new DeepNAG model. :param latent_dim: the latent space dimension :param output_dim: the dimension of the output tensors :param num_classes: the total number of sample classes",
"name": "__init__",
"signature": "def __init__(self, latent_dim, output_dim, num_classes)"
},
... | 2 | stack_v2_sparse_classes_30k_train_000647 | Implement the Python class `DeepNAGNet` described below.
Class description:
DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN.
Method signatures and docstrings:
- def __init__(self, latent_dim, output_dim, num_classes): Initia... | Implement the Python class `DeepNAGNet` described below.
Class description:
DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN.
Method signatures and docstrings:
- def __init__(self, latent_dim, output_dim, num_classes): Initia... | 1f6a16aa2ba029ee4e8dfa2536d2b1c2ea3eeda0 | <|skeleton|>
class DeepNAGNet:
"""DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN."""
def __init__(self, latent_dim, output_dim, num_classes):
"""Initializes a new DeepNAG model. :param latent_dim: the latent ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepNAGNet:
"""DeepNAG's network model. This model is a recurrent sequence generator. This same generator model is used as the generator network for DeepGAN."""
def __init__(self, latent_dim, output_dim, num_classes):
"""Initializes a new DeepNAG model. :param latent_dim: the latent space dimensi... | the_stack_v2_python_sparse | models/DeepNAG.py | mishav78/DeepNAG | train | 0 |
685f08f09ed26799f048614ecdbb26060178504a | [
"logger.debug('Start clean data in ResetPasswordForm.')\nemail = self.cleaned_data.get('email')\nself.validator_all(email)\nlogger.debug('Exit clean data in ResetPasswordForm.')\nreturn super(AddPatientForm, self).clean(*args, **kwargs)",
"logger.debug('Start validations in AddPatientForm.')\nvalidator = PatientV... | <|body_start_0|>
logger.debug('Start clean data in ResetPasswordForm.')
email = self.cleaned_data.get('email')
self.validator_all(email)
logger.debug('Exit clean data in ResetPasswordForm.')
return super(AddPatientForm, self).clean(*args, **kwargs)
<|end_body_0|>
<|body_start_1|... | Form to reset password User | AddPatientForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddPatientForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
<|body_0|>
def validator_all(self, email):
"""Checks validator in all fields."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.de... | stack_v2_sparse_classes_36k_train_025724 | 1,268 | permissive | [
{
"docstring": "Get patient fields.",
"name": "clean",
"signature": "def clean(self, *args, **kwargs)"
},
{
"docstring": "Checks validator in all fields.",
"name": "validator_all",
"signature": "def validator_all(self, email)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000067 | Implement the Python class `AddPatientForm` described below.
Class description:
Form to reset password User
Method signatures and docstrings:
- def clean(self, *args, **kwargs): Get patient fields.
- def validator_all(self, email): Checks validator in all fields. | Implement the Python class `AddPatientForm` described below.
Class description:
Form to reset password User
Method signatures and docstrings:
- def clean(self, *args, **kwargs): Get patient fields.
- def validator_all(self, email): Checks validator in all fields.
<|skeleton|>
class AddPatientForm:
"""Form to res... | 5387eb80dfb354e948abe64f7d8bbe087fc4f136 | <|skeleton|>
class AddPatientForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
<|body_0|>
def validator_all(self, email):
"""Checks validator in all fields."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddPatientForm:
"""Form to reset password User"""
def clean(self, *args, **kwargs):
"""Get patient fields."""
logger.debug('Start clean data in ResetPasswordForm.')
email = self.cleaned_data.get('email')
self.validator_all(email)
logger.debug('Exit clean data in Re... | the_stack_v2_python_sparse | medical_prescription/user/forms/addpatientform.py | ristovao/2017.2-Receituario-Medico | train | 0 |
e1a9cd3619175459f1dd276761102c7a36f98bcd | [
"params = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\ncourses = PracticeCourse.objects.filter(school_id=sid).values('id', 'update_time')\nif params.has('name'):\n courses = courses.filter(name... | <|body_start_0|>
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
courses = PracticeCourse.objects.filter(school_id=sid).values('id', 'update_time')
if params... | PracticeCourseListMgetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PracticeCourseListMgetView:
def get(self, request, sid):
"""获取课程列表 :param request: :param sid: :return:"""
<|body_0|>
def post(self, request, sid):
"""批量获取课程信息 :param request: :param sid: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
para... | stack_v2_sparse_classes_36k_train_025725 | 2,167 | no_license | [
{
"docstring": "获取课程列表 :param request: :param sid: :return:",
"name": "get",
"signature": "def get(self, request, sid)"
},
{
"docstring": "批量获取课程信息 :param request: :param sid: :return:",
"name": "post",
"signature": "def post(self, request, sid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013281 | Implement the Python class `PracticeCourseListMgetView` described below.
Class description:
Implement the PracticeCourseListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid): 获取课程列表 :param request: :param sid: :return:
- def post(self, request, sid): 批量获取课程信息 :param request: :param sid: ... | Implement the Python class `PracticeCourseListMgetView` described below.
Class description:
Implement the PracticeCourseListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid): 获取课程列表 :param request: :param sid: :return:
- def post(self, request, sid): 批量获取课程信息 :param request: :param sid: ... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class PracticeCourseListMgetView:
def get(self, request, sid):
"""获取课程列表 :param request: :param sid: :return:"""
<|body_0|>
def post(self, request, sid):
"""批量获取课程信息 :param request: :param sid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PracticeCourseListMgetView:
def get(self, request, sid):
"""获取课程列表 :param request: :param sid: :return:"""
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
... | the_stack_v2_python_sparse | FireHydrant/server/practice/views/course/info/list_mget.py | shoogoome/FireHydrant | train | 4 | |
026bf82afaf87aa0b32e280305200f28f39306cb | [
"if isinstance(key, int):\n return Operation(key)\nif key not in Operation._member_map_:\n return extend_enum(Operation, key, default)\nreturn Operation[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 26 <= value <= 6... | <|body_start_0|>
if isinstance(key, int):
return Operation(key)
if key not in Operation._member_map_:
return extend_enum(Operation, key, default)
return Operation[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
... | [Operation] Operation Codes [:rfc:`826`][:rfc:`5494`] | Operation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Operation:
"""[Operation] Operation Codes [:rfc:`826`][:rfc:`5494`]"""
def get(key: 'int | str', default: 'int'=-1) -> 'Operation':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_025726 | 3,124 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'Operation'"
},
{
"docstring": "Lookup function used when value is not found. A... | 2 | stack_v2_sparse_classes_30k_train_006058 | Implement the Python class `Operation` described below.
Class description:
[Operation] Operation Codes [:rfc:`826`][:rfc:`5494`]
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Operation': Backport support for original codes. Args: key: Key to get enum item. default: Default value... | Implement the Python class `Operation` described below.
Class description:
[Operation] Operation Codes [:rfc:`826`][:rfc:`5494`]
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Operation': Backport support for original codes. Args: key: Key to get enum item. default: Default value... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Operation:
"""[Operation] Operation Codes [:rfc:`826`][:rfc:`5494`]"""
def get(key: 'int | str', default: 'int'=-1) -> 'Operation':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Operation:
"""[Operation] Operation Codes [:rfc:`826`][:rfc:`5494`]"""
def get(key: 'int | str', default: 'int'=-1) -> 'Operation':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
... | the_stack_v2_python_sparse | pcapkit/const/arp/operation.py | JarryShaw/PyPCAPKit | train | 204 |
73e6e285a9d892ca64835c486cb9efb8657e5a1a | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('nhuang54_wud', 'nhuang54_wud')\nhubwayData = repo.nhuang54_wud.hubwayStation.find()\ncrashData = repo.nhuang54_wud.crashRecord.find()\nhubwayLocations = []\nfor row in hubwayData:\n hubwayLocations +=... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('nhuang54_wud', 'nhuang54_wud')
hubwayData = repo.nhuang54_wud.hubwayStation.find()
crashData = repo.nhuang54_wud.crashRecord.find()
hubway... | transformHubwayCrash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformHubwayCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing eve... | stack_v2_sparse_classes_36k_train_025727 | 6,105 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `transformHubwayCrash` described below.
Class description:
Implement the transformHubwayCrash class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), sta... | Implement the Python class `transformHubwayCrash` described below.
Class description:
Implement the transformHubwayCrash class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), sta... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformHubwayCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transformHubwayCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('nhuang54_wud', 'nhuang54_wud')... | the_stack_v2_python_sparse | nhuang54_wud/transformHubwayCrash.py | maximega/course-2019-spr-proj | train | 2 | |
0e368c591a4545d6ad7bdb866a4c2a400add0576 | [
"req_data = json.loads(request.body)\nsku_id = req_data.get('sku_id')\ncount = req_data.get('count')\nselected = req_data.get('selected', True)\nif not all([sku_id, count]):\n return JsonResponse({'code': 400, 'message': '缺少必传参数'})\ntry:\n count = int(count)\nexcept Exception as e:\n return JsonResponse({'... | <|body_start_0|>
req_data = json.loads(request.body)
sku_id = req_data.get('sku_id')
count = req_data.get('count')
selected = req_data.get('selected', True)
if not all([sku_id, count]):
return JsonResponse({'code': 400, 'message': '缺少必传参数'})
try:
c... | CartView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartView:
def post(self, request):
"""购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功"""
<|body_0|>
def get(self, request):
"""购物车记录获取: ① 根据用户是否登录,分别进行购物车数据的获取 ② 组织数据并返回响应"""
<|body_1|>
def put(self, request):
"""购物车记录修改: ① 获取参数并进行校... | stack_v2_sparse_classes_36k_train_025728 | 7,053 | no_license | [
{
"docstring": "购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "购物车记录获取: ① 根据用户是否登录,分别进行购物车数据的获取 ② 组织数据并返回响应",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "购物车记录修改... | 4 | stack_v2_sparse_classes_30k_test_000494 | Implement the Python class `CartView` described below.
Class description:
Implement the CartView class.
Method signatures and docstrings:
- def post(self, request): 购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功
- def get(self, request): 购物车记录获取: ① 根据用户是否登录,分别进行购物车数据的获取 ② 组织数据并返回响应
- def put(self, requ... | Implement the Python class `CartView` described below.
Class description:
Implement the CartView class.
Method signatures and docstrings:
- def post(self, request): 购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功
- def get(self, request): 购物车记录获取: ① 根据用户是否登录,分别进行购物车数据的获取 ② 组织数据并返回响应
- def put(self, requ... | dee2a25786a6b9d446886232cb96a7341b26c396 | <|skeleton|>
class CartView:
def post(self, request):
"""购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功"""
<|body_0|>
def get(self, request):
"""购物车记录获取: ① 根据用户是否登录,分别进行购物车数据的获取 ② 组织数据并返回响应"""
<|body_1|>
def put(self, request):
"""购物车记录修改: ① 获取参数并进行校... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartView:
def post(self, request):
"""购物车数据新增: ① 获取参数并进行校验 ② 根据用户是否登录,分别进行购物车数据的保存 ③ 返回响应,购物车记录添加成功"""
req_data = json.loads(request.body)
sku_id = req_data.get('sku_id')
count = req_data.get('count')
selected = req_data.get('selected', True)
if not all([sku_id,... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/carts/views.py | Jioani/meiduo | train | 0 | |
49e5220274d75bbb125b4b58d8416ae13a137503 | [
"self.num_size = len(nums)\nself.sum_num = {0: 0}\nsum_num = 0\nfor i in range(self.num_size):\n sum_num += nums[i]\n self.sum_num[i + 1] = sum_num\nprint(self.sum_num)",
"i = i if i > 0 else 0\nj = j if j < self.num_size else self.num_size\nreturn self.sum_num[j + 1] - self.sum_num[i]"
] | <|body_start_0|>
self.num_size = len(nums)
self.sum_num = {0: 0}
sum_num = 0
for i in range(self.num_size):
sum_num += nums[i]
self.sum_num[i + 1] = sum_num
print(self.sum_num)
<|end_body_0|>
<|body_start_1|>
i = i if i > 0 else 0
j = j if... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_size = len(nums)
self.sum_num = {0: 0}
... | stack_v2_sparse_classes_36k_train_025729 | 1,047 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002080 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 157cbaeeff74130e5105e58a6b4cdf66403a8a6f | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.num_size = len(nums)
self.sum_num = {0: 0}
sum_num = 0
for i in range(self.num_size):
sum_num += nums[i]
self.sum_num[i + 1] = sum_num
print(self.sum_num)
def sumRa... | the_stack_v2_python_sparse | Leetcode/303. Range Sum Query - Immutable.py | xiaohuanlin/Algorithms | train | 1 | |
26785751065b87146ccd135f98b0c68a1ef80a91 | [
"url = '/api/v1.2/graph-connections/%d/schema/propertykeys/reuse' % graph_id\ncode, res = Request().request(method='post', path=url, json=body, types='hubble')\nreturn (code, res)",
"url = '/api/v1.2/graph-connections/%d/schema/vertexlabels/reuse' % graph_id\ncode, res = Request().request(method='post', path=url,... | <|body_start_0|>
url = '/api/v1.2/graph-connections/%d/schema/propertykeys/reuse' % graph_id
code, res = Request().request(method='post', path=url, json=body, types='hubble')
return (code, res)
<|end_body_0|>
<|body_start_1|>
url = '/api/v1.2/graph-connections/%d/schema/vertexlabels/reu... | schema 复用接口 | ReuseSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReuseSchema:
"""schema 复用接口"""
def reuse_property(body, graph_id, auth=None):
""":param body: :param auth: :param graph_id: :return:"""
<|body_0|>
def reuse_vertexLabel(body, graph_id, auth=None):
""":param body: :param auth: :param graph_id: :return:"""
... | stack_v2_sparse_classes_36k_train_025730 | 26,078 | no_license | [
{
"docstring": ":param body: :param auth: :param graph_id: :return:",
"name": "reuse_property",
"signature": "def reuse_property(body, graph_id, auth=None)"
},
{
"docstring": ":param body: :param auth: :param graph_id: :return:",
"name": "reuse_vertexLabel",
"signature": "def reuse_verte... | 3 | stack_v2_sparse_classes_30k_train_010657 | Implement the Python class `ReuseSchema` described below.
Class description:
schema 复用接口
Method signatures and docstrings:
- def reuse_property(body, graph_id, auth=None): :param body: :param auth: :param graph_id: :return:
- def reuse_vertexLabel(body, graph_id, auth=None): :param body: :param auth: :param graph_id:... | Implement the Python class `ReuseSchema` described below.
Class description:
schema 复用接口
Method signatures and docstrings:
- def reuse_property(body, graph_id, auth=None): :param body: :param auth: :param graph_id: :return:
- def reuse_vertexLabel(body, graph_id, auth=None): :param body: :param auth: :param graph_id:... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class ReuseSchema:
"""schema 复用接口"""
def reuse_property(body, graph_id, auth=None):
""":param body: :param auth: :param graph_id: :return:"""
<|body_0|>
def reuse_vertexLabel(body, graph_id, auth=None):
""":param body: :param auth: :param graph_id: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReuseSchema:
"""schema 复用接口"""
def reuse_property(body, graph_id, auth=None):
""":param body: :param auth: :param graph_id: :return:"""
url = '/api/v1.2/graph-connections/%d/schema/propertykeys/reuse' % graph_id
code, res = Request().request(method='post', path=url, json=body, typ... | the_stack_v2_python_sparse | src/common/hubble_api.py | hugegraph/hugegraph-test | train | 1 |
d01c6fd0e611e04dddb7a1d4cbf6f0270f5f27c4 | [
"if self.id.text:\n match = self.__class__.atom_id_pattern.search(self.id.text)\n if match:\n return match.group('user_id')\nreturn None",
"if self.id.text:\n match = self.__class__.atom_id_pattern.search(self.id.text)\n if match:\n return match.group('map_id')\nreturn None"
] | <|body_start_0|>
if self.id.text:
match = self.__class__.atom_id_pattern.search(self.id.text)
if match:
return match.group('user_id')
return None
<|end_body_0|>
<|body_start_1|>
if self.id.text:
match = self.__class__.atom_id_pattern.search(se... | Adds convenience methods inherited by all Maps Data entries. | MapsDataEntry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapsDataEntry:
"""Adds convenience methods inherited by all Maps Data entries."""
def get_user_id(self):
"""Extracts the user ID of this entry."""
<|body_0|>
def get_map_id(self):
"""Extracts the map ID of this entry."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_025731 | 3,339 | permissive | [
{
"docstring": "Extracts the user ID of this entry.",
"name": "get_user_id",
"signature": "def get_user_id(self)"
},
{
"docstring": "Extracts the map ID of this entry.",
"name": "get_map_id",
"signature": "def get_map_id(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003258 | Implement the Python class `MapsDataEntry` described below.
Class description:
Adds convenience methods inherited by all Maps Data entries.
Method signatures and docstrings:
- def get_user_id(self): Extracts the user ID of this entry.
- def get_map_id(self): Extracts the map ID of this entry. | Implement the Python class `MapsDataEntry` described below.
Class description:
Adds convenience methods inherited by all Maps Data entries.
Method signatures and docstrings:
- def get_user_id(self): Extracts the user ID of this entry.
- def get_map_id(self): Extracts the map ID of this entry.
<|skeleton|>
class Maps... | 1c2e02c49716b9390b41e8783beeb70a11035851 | <|skeleton|>
class MapsDataEntry:
"""Adds convenience methods inherited by all Maps Data entries."""
def get_user_id(self):
"""Extracts the user ID of this entry."""
<|body_0|>
def get_map_id(self):
"""Extracts the map ID of this entry."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MapsDataEntry:
"""Adds convenience methods inherited by all Maps Data entries."""
def get_user_id(self):
"""Extracts the user ID of this entry."""
if self.id.text:
match = self.__class__.atom_id_pattern.search(self.id.text)
if match:
return match.gr... | the_stack_v2_python_sparse | vendor/gdata/maps/data.py | CollabQ/CollabQ | train | 4 |
a400a771e9b3dbe12e955e2578d8fe5b7e0628da | [
"super().__init__()\nself.wide = WideLayer(inputs_size=num_fields, output_size=1, dropout_p=wide_dropout_p)\nself.deep = MultilayerPerceptionLayer(inputs_size=embed_size, output_size=1, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation)\nself.output = WideLayer(inputs_size=num_field... | <|body_start_0|>
super().__init__()
self.wide = WideLayer(inputs_size=num_fields, output_size=1, dropout_p=wide_dropout_p)
self.deep = MultilayerPerceptionLayer(inputs_size=embed_size, output_size=1, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activation)
self... | Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems <https://arxiv.org/pdf/1606.07792.pdf>`_. | WideAndDeepModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WideAndDeepModel:
"""Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems <https://arxiv.org/pdf/1606.07792.pdf>`... | stack_v2_sparse_classes_36k_train_025732 | 3,948 | permissive | [
{
"docstring": "Initialize WideAndDeepModel Args: embed_size (int): size of embedding tensor num_fields (int): number of inputs' fields deep_layer_sizes (List[int]): layer sizes of dense network out_dropout_p (float, optional): probability of Dropout in output layer. Defaults to None wide_dropout_p (float, opti... | 2 | stack_v2_sparse_classes_30k_train_004103 | Implement the Python class `WideAndDeepModel` described below.
Class description:
Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems ... | Implement the Python class `WideAndDeepModel` described below.
Class description:
Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems ... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class WideAndDeepModel:
"""Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems <https://arxiv.org/pdf/1606.07792.pdf>`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WideAndDeepModel:
"""Model class of Wide and Deep Model Wide and Deep Model is one of the most famous click-through-rate prediction model which is designed by Google in 2016. :Reference: #. `Heng-Tze Cheng, 2016. Wide & Deep Learning for Recommender Systems <https://arxiv.org/pdf/1606.07792.pdf>`_."""
de... | the_stack_v2_python_sparse | torecsys/models/ctr/wide_and_deep.py | p768lwy3/torecsys | train | 98 |
d2b868878249b5f4de46196f1da9e0784bc612d8 | [
"self.beslutning_field = beslutning_field\nself.arsaks_data_field = arsaks_data_field\nself.score_field = score_field\nself.grense_avslag_field = grense_avslag_field\nself.grense_godkjent_field = grense_godkjent_field\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\n... | <|body_start_0|>
self.beslutning_field = beslutning_field
self.arsaks_data_field = arsaks_data_field
self.score_field = score_field
self.grense_avslag_field = grense_avslag_field
self.grense_godkjent_field = grense_godkjent_field
self.additional_properties = additional_pr... | Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int): TODO: type description here. grense_avslag_field (int): TODO: type descriptio... | PersonScoring | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonScoring:
"""Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int): TODO: type description here. grense_... | stack_v2_sparse_classes_36k_train_025733 | 3,457 | permissive | [
{
"docstring": "Constructor for the PersonScoring class",
"name": "__init__",
"signature": "def __init__(self, beslutning_field=None, arsaks_data_field=None, score_field=None, grense_avslag_field=None, grense_godkjent_field=None, additional_properties={})"
},
{
"docstring": "Creates an instance ... | 2 | null | Implement the Python class `PersonScoring` described below.
Class description:
Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int... | Implement the Python class `PersonScoring` described below.
Class description:
Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class PersonScoring:
"""Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int): TODO: type description here. grense_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonScoring:
"""Implementation of the 'Person.Scoring' model. TODO: type model description here. Attributes: beslutning_field (string): TODO: type description here. arsaks_data_field (list of PersonArsaksData): TODO: type description here. score_field (int): TODO: type description here. grense_avslag_field ... | the_stack_v2_python_sparse | idfy_rest_client/models/person_scoring.py | dealflowteam/Idfy | train | 0 |
bdd16bb6870ea5a9ded39bef95448c15cdc1223b | [
"super(GraphVisualizerPointDraw, self).__init__()\nself.setMinimumSize(QSize(13, 13))\nself.setMaximumSize(QSize(13, 13))",
"painter = QPainter(self)\npainter.drawEllipse(self.rect().center(), 6, 6)\npainter.setBrush(Qt.black)\npainter.drawEllipse(self.rect().center(), 2, 2)"
] | <|body_start_0|>
super(GraphVisualizerPointDraw, self).__init__()
self.setMinimumSize(QSize(13, 13))
self.setMaximumSize(QSize(13, 13))
<|end_body_0|>
<|body_start_1|>
painter = QPainter(self)
painter.drawEllipse(self.rect().center(), 6, 6)
painter.setBrush(Qt.black)
... | Define an empty widget with a point drew. | GraphVisualizerPointDraw | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphVisualizerPointDraw:
"""Define an empty widget with a point drew."""
def __init__(self):
"""Initialize a GraphVisualizerPointDraw instance."""
<|body_0|>
def paintEvent(self, event):
"""Paint an event."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_025734 | 24,840 | permissive | [
{
"docstring": "Initialize a GraphVisualizerPointDraw instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Paint an event.",
"name": "paintEvent",
"signature": "def paintEvent(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009776 | Implement the Python class `GraphVisualizerPointDraw` described below.
Class description:
Define an empty widget with a point drew.
Method signatures and docstrings:
- def __init__(self): Initialize a GraphVisualizerPointDraw instance.
- def paintEvent(self, event): Paint an event. | Implement the Python class `GraphVisualizerPointDraw` described below.
Class description:
Define an empty widget with a point drew.
Method signatures and docstrings:
- def __init__(self): Initialize a GraphVisualizerPointDraw instance.
- def paintEvent(self, event): Paint an event.
<|skeleton|>
class GraphVisualizer... | bbcf475a4b4e85836123452053bbbf34cc44063a | <|skeleton|>
class GraphVisualizerPointDraw:
"""Define an empty widget with a point drew."""
def __init__(self):
"""Initialize a GraphVisualizerPointDraw instance."""
<|body_0|>
def paintEvent(self, event):
"""Paint an event."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphVisualizerPointDraw:
"""Define an empty widget with a point drew."""
def __init__(self):
"""Initialize a GraphVisualizerPointDraw instance."""
super(GraphVisualizerPointDraw, self).__init__()
self.setMinimumSize(QSize(13, 13))
self.setMaximumSize(QSize(13, 13))
d... | the_stack_v2_python_sparse | posydon/visualization/VH_diagram/GraphVisualizer.py | POSYDON-code/POSYDON | train | 11 |
0ed6540b136f86359d3aad25766656a3a2ce017b | [
"self.driver.get(home_url)\nself.driver.find_element(Search.Search_Box).click()\nsearch_expected = '奥迪'\nself.driver.find_element(Search.Search_Box).send_keys('奥迪')\nprint('输入的搜索条件为:', search_expected)\ntime.sleep(2)\nself.driver.find_element(Search.Search_Button).click()\nself.driver.switch_to_window()\nresult_act... | <|body_start_0|>
self.driver.get(home_url)
self.driver.find_element(Search.Search_Box).click()
search_expected = '奥迪'
self.driver.find_element(Search.Search_Box).send_keys('奥迪')
print('输入的搜索条件为:', search_expected)
time.sleep(2)
self.driver.find_element(Search.Sear... | CarSearchResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CarSearchResult:
def test_searchResult(self):
"""首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong"""
<|body_0|>
def test_dropDown_Box(self):
"""点击输入框后,检查下拉框的热卖车型是够正确@author:dingdongdong"""
<|body_1|>
def test_home_search(self):
"""点击首页搜索框检查输入搜索条件... | stack_v2_sparse_classes_36k_train_025735 | 3,082 | no_license | [
{
"docstring": "首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong",
"name": "test_searchResult",
"signature": "def test_searchResult(self)"
},
{
"docstring": "点击输入框后,检查下拉框的热卖车型是够正确@author:dingdongdong",
"name": "test_dropDown_Box",
"signature": "def test_dropDown_Box(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_014210 | Implement the Python class `CarSearchResult` described below.
Class description:
Implement the CarSearchResult class.
Method signatures and docstrings:
- def test_searchResult(self): 首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong
- def test_dropDown_Box(self): 点击输入框后,检查下拉框的热卖车型是够正确@author:dingdongdong
- def test_ho... | Implement the Python class `CarSearchResult` described below.
Class description:
Implement the CarSearchResult class.
Method signatures and docstrings:
- def test_searchResult(self): 首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong
- def test_dropDown_Box(self): 点击输入框后,检查下拉框的热卖车型是够正确@author:dingdongdong
- def test_ho... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class CarSearchResult:
def test_searchResult(self):
"""首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong"""
<|body_0|>
def test_dropDown_Box(self):
"""点击输入框后,检查下拉框的热卖车型是够正确@author:dingdongdong"""
<|body_1|>
def test_home_search(self):
"""点击首页搜索框检查输入搜索条件... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CarSearchResult:
def test_searchResult(self):
"""首页搜索框输入“奥迪”后,点击搜索查看结果是否是“奥迪”@author:dingdongdong"""
self.driver.get(home_url)
self.driver.find_element(Search.Search_Box).click()
search_expected = '奥迪'
self.driver.find_element(Search.Search_Box).send_keys('奥迪')
... | the_stack_v2_python_sparse | mc/taochePC/test_homepage/test_carSearchBox.py | boeai/mc | train | 0 | |
8a9d8c0c54737c212f044049372d30160d48e093 | [
"response_object = {'status': 'fail'}\nuser = UserModel.find_by_id(_id=user_id)\nif not user:\n return (response_object, 404)\nelse:\n response_object['status'] = 'success'\n response_object['current_time'] = int(time())\n response_object['confirmation'] = [each.json() for each in user.confirmation.orde... | <|body_start_0|>
response_object = {'status': 'fail'}
user = UserModel.find_by_id(_id=user_id)
if not user:
return (response_object, 404)
else:
response_object['status'] = 'success'
response_object['current_time'] = int(time())
response_obj... | ConfirmationByUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
<|body_0|>
def post(cls, user_id: int):
"""Resend confirmation email"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response_object = {'status': 'fail'}
... | stack_v2_sparse_classes_36k_train_025736 | 4,034 | no_license | [
{
"docstring": "Returns confirmation for specific user",
"name": "get",
"signature": "def get(cls, user_id: int)"
},
{
"docstring": "Resend confirmation email",
"name": "post",
"signature": "def post(cls, user_id: int)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000133 | Implement the Python class `ConfirmationByUser` described below.
Class description:
Implement the ConfirmationByUser class.
Method signatures and docstrings:
- def get(cls, user_id: int): Returns confirmation for specific user
- def post(cls, user_id: int): Resend confirmation email | Implement the Python class `ConfirmationByUser` described below.
Class description:
Implement the ConfirmationByUser class.
Method signatures and docstrings:
- def get(cls, user_id: int): Returns confirmation for specific user
- def post(cls, user_id: int): Resend confirmation email
<|skeleton|>
class ConfirmationBy... | 92bc183b6423ba41aa7d073ec83af2b585c54a40 | <|skeleton|>
class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
<|body_0|>
def post(cls, user_id: int):
"""Resend confirmation email"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfirmationByUser:
def get(cls, user_id: int):
"""Returns confirmation for specific user"""
response_object = {'status': 'fail'}
user = UserModel.find_by_id(_id=user_id)
if not user:
return (response_object, 404)
else:
response_object['status'] ... | the_stack_v2_python_sparse | services/users/project/api/views/confirmations.py | jjason0/SupplyItCodeBase-1 | train | 0 | |
b70bf32f0bd39773c1acafbd78de998ece30f31f | [
"super(SASRec, self).__init__()\nself.config = config\nself.user_num = config['n_users']\nself.item_num = config['n_items']\nself.hidden_units = config['emb_dim']\nself.maxlen = config['maxlen']\nself.num_blocks = config['num_blocks']\nself.num_heads = config['num_heads']\nself.dropout_rate = config['dropout_rate']... | <|body_start_0|>
super(SASRec, self).__init__()
self.config = config
self.user_num = config['n_users']
self.item_num = config['n_items']
self.hidden_units = config['emb_dim']
self.maxlen = config['maxlen']
self.num_blocks = config['num_blocks']
self.num_he... | SASRec Class. | SASRec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SASRec:
"""SASRec Class."""
def __init__(self, config):
"""Initialize SASRec Class."""
<|body_0|>
def log2feats(self, log_seqs):
"""Encode sequential items. Args: log_seqs ([type]): [description] Returns: [type]: [description]"""
<|body_1|>
def forwa... | stack_v2_sparse_classes_36k_train_025737 | 9,120 | permissive | [
{
"docstring": "Initialize SASRec Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Encode sequential items. Args: log_seqs ([type]): [description] Returns: [type]: [description]",
"name": "log2feats",
"signature": "def log2feats(self, log_seqs)"
... | 4 | null | Implement the Python class `SASRec` described below.
Class description:
SASRec Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize SASRec Class.
- def log2feats(self, log_seqs): Encode sequential items. Args: log_seqs ([type]): [description] Returns: [type]: [description]
- def forward(s... | Implement the Python class `SASRec` described below.
Class description:
SASRec Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize SASRec Class.
- def log2feats(self, log_seqs): Encode sequential items. Args: log_seqs ([type]): [description] Returns: [type]: [description]
- def forward(s... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class SASRec:
"""SASRec Class."""
def __init__(self, config):
"""Initialize SASRec Class."""
<|body_0|>
def log2feats(self, log_seqs):
"""Encode sequential items. Args: log_seqs ([type]): [description] Returns: [type]: [description]"""
<|body_1|>
def forwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SASRec:
"""SASRec Class."""
def __init__(self, config):
"""Initialize SASRec Class."""
super(SASRec, self).__init__()
self.config = config
self.user_num = config['n_users']
self.item_num = config['n_items']
self.hidden_units = config['emb_dim']
self... | the_stack_v2_python_sparse | beta_rec/models/sasrec.py | beta-team/beta-recsys | train | 156 |
91b50466a92e35f5c8bafad4876b6472ab9e1dcb | [
"jumps = [float('inf')] * len(nums)\njumps[0] = 0\nfor i, n in enumerate(nums):\n for j in range(1, n + 1):\n if i + j < len(nums):\n jumps[i + j] = min(jumps[i + j], 1 + jumps[i])\nreturn jumps[-1]",
"jumps = 0\nc_max = 0\nn_max = 0\nfor i, n in enumerate(nums):\n n_max = max(n_max, i + n... | <|body_start_0|>
jumps = [float('inf')] * len(nums)
jumps[0] = 0
for i, n in enumerate(nums):
for j in range(1, n + 1):
if i + j < len(nums):
jumps[i + j] = min(jumps[i + j], 1 + jumps[i])
return jumps[-1]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""First solution: O(N^2) time, O(N) space"""
<|body_0|>
def jump(self, nums: List[int]) -> int:
"""Second solution: O(N) time, O(1) space"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jumps = [flo... | stack_v2_sparse_classes_36k_train_025738 | 787 | no_license | [
{
"docstring": "First solution: O(N^2) time, O(N) space",
"name": "jump",
"signature": "def jump(self, nums: List[int]) -> int"
},
{
"docstring": "Second solution: O(N) time, O(1) space",
"name": "jump",
"signature": "def jump(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: First solution: O(N^2) time, O(N) space
- def jump(self, nums: List[int]) -> int: Second solution: O(N) time, O(1) space | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: First solution: O(N^2) time, O(N) space
- def jump(self, nums: List[int]) -> int: Second solution: O(N) time, O(1) space
<|skeleton|>
cla... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""First solution: O(N^2) time, O(N) space"""
<|body_0|>
def jump(self, nums: List[int]) -> int:
"""Second solution: O(N) time, O(1) space"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums: List[int]) -> int:
"""First solution: O(N^2) time, O(N) space"""
jumps = [float('inf')] * len(nums)
jumps[0] = 0
for i, n in enumerate(nums):
for j in range(1, n + 1):
if i + j < len(nums):
jumps[i +... | the_stack_v2_python_sparse | 45.Jump_Game_II.py | welsny/solutions | train | 1 | |
795345f5cb9f06b7a06ac5215b832f960094d58b | [
"self.xs = np.atleast_2d(xs).T\nself.freqs = np.atleast_2d(freqs)\nself.width = np.atleast_1d(width)\nself.horizon = np.pi / 2\nself.mfreq = mfreq\nself.chromaticity = chromaticity\nself.dtype = dtype",
"widths, dtype = self._process_args(width, mfreq, chromaticity, dtype)\nresponse = np.exp(-0.5 * (self.xs / np.... | <|body_start_0|>
self.xs = np.atleast_2d(xs).T
self.freqs = np.atleast_2d(freqs)
self.width = np.atleast_1d(width)
self.horizon = np.pi / 2
self.mfreq = mfreq
self.chromaticity = chromaticity
self.dtype = dtype
<|end_body_0|>
<|body_start_1|>
widths, dtyp... | Base class for constructing a 1-dimensional beam. | Beam1d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` p... | stack_v2_sparse_classes_36k_train_025739 | 7,041 | no_license | [
{
"docstring": "Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` parameters, or by specifying a chromaticity and reference frequency. When providing an array of frequencies along with a single width, reference frequency, and chromaticity,... | 4 | stack_v2_sparse_classes_30k_train_012581 | Implement the Python class `Beam1d` described below.
Class description:
Base class for constructing a 1-dimensional beam.
Method signatures and docstrings:
- def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32): Set up the base parameters for defining a beam. Chromatic beams may... | Implement the Python class `Beam1d` described below.
Class description:
Base class for constructing a 1-dimensional beam.
Method signatures and docstrings:
- def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32): Set up the base parameters for defining a beam. Chromatic beams may... | f9d292f4a91c0599947e3c013b48114b2097d76d | <|skeleton|>
class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` parameters, or... | the_stack_v2_python_sparse | rfp/scripts/dewedge/beams.py | HERA-Team/hera_sandbox | train | 2 |
18c55b315909d9fdc3c61b66972d67fd8ec0e7b9 | [
"if estimator is None:\n estimator = linear_model.LinearRegression()\nif param_grid is None:\n param_grid = {}\nsuper().__init__(estimator, param_grid, **kwargs)",
"df = read_csv(xy_file)\nX = df['X'].values\ny = df['y'].values\nsuper().fit(X, y)\nyp = cross_validation.cross_val_predict(self.best_estimator_... | <|body_start_0|>
if estimator is None:
estimator = linear_model.LinearRegression()
if param_grid is None:
param_grid = {}
super().__init__(estimator, param_grid, **kwargs)
<|end_body_0|>
<|body_start_1|>
df = read_csv(xy_file)
X = df['X'].values
y... | GridSearchCV | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridSearchCV:
def __init__(self, estimator=None, param_grid=None, **kwargs):
"""estimator and param_grid can be values defined in csv."""
<|body_0|>
def fit(self, xy_file, fname_out):
"""All grid results will be saved later, although only the best result is saved."""... | stack_v2_sparse_classes_36k_train_025740 | 2,058 | permissive | [
{
"docstring": "estimator and param_grid can be values defined in csv.",
"name": "__init__",
"signature": "def __init__(self, estimator=None, param_grid=None, **kwargs)"
},
{
"docstring": "All grid results will be saved later, although only the best result is saved.",
"name": "fit",
"sig... | 2 | null | Implement the Python class `GridSearchCV` described below.
Class description:
Implement the GridSearchCV class.
Method signatures and docstrings:
- def __init__(self, estimator=None, param_grid=None, **kwargs): estimator and param_grid can be values defined in csv.
- def fit(self, xy_file, fname_out): All grid result... | Implement the Python class `GridSearchCV` described below.
Class description:
Implement the GridSearchCV class.
Method signatures and docstrings:
- def __init__(self, estimator=None, param_grid=None, **kwargs): estimator and param_grid can be values defined in csv.
- def fit(self, xy_file, fname_out): All grid result... | b7e3c860280581e37c7b5254e18ff4b19c112ded | <|skeleton|>
class GridSearchCV:
def __init__(self, estimator=None, param_grid=None, **kwargs):
"""estimator and param_grid can be values defined in csv."""
<|body_0|>
def fit(self, xy_file, fname_out):
"""All grid results will be saved later, although only the best result is saved."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridSearchCV:
def __init__(self, estimator=None, param_grid=None, **kwargs):
"""estimator and param_grid can be values defined in csv."""
if estimator is None:
estimator = linear_model.LinearRegression()
if param_grid is None:
param_grid = {}
super().__i... | the_stack_v2_python_sparse | poodle/linear_model.py | jskDr/jamespy_py3 | train | 5 | |
a54adec3134dec4eaa5d71497cebcc8620f57e5d | [
"base_options = _BaseOptions(model_asset_path=model_path)\noptions = AudioClassifierOptions(base_options=base_options, running_mode=_RunningMode.AUDIO_CLIPS)\nreturn cls.create_from_options(options)",
"def packets_callback(output_packets: Mapping[str, packet.Packet]):\n timestamp_ms = output_packets[_CLASSIFIC... | <|body_start_0|>
base_options = _BaseOptions(model_asset_path=model_path)
options = AudioClassifierOptions(base_options=base_options, running_mode=_RunningMode.AUDIO_CLIPS)
return cls.create_from_options(options)
<|end_body_0|>
<|body_start_1|>
def packets_callback(output_packets: Mappi... | Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with type TENSOR_AXIS_LABELS per output classifica... | AudioClassifier | [
"Apache-2.0",
"dtoa"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with ty... | stack_v2_sparse_classes_36k_train_025741 | 14,933 | permissive | [
{
"docstring": "Creates an `AudioClassifier` object from a TensorFlow Lite model and the default `AudioClassifierOptions`. Note that the created `AudioClassifier` instance is in audio clips mode, for classifying on independent audio clips. Args: model_path: Path to the model. Returns: `AudioClassifier` object t... | 4 | null | Implement the Python class `AudioClassifier` described below.
Class description:
Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) cat... | Implement the Python class `AudioClassifier` described below.
Class description:
Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) cat... | 007824594bf1d07c7c1467df03a43886f8a4b3ad | <|skeleton|>
class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AudioClassifier:
"""Class that performs audio classification on audio data. This API expects a TFLite model with mandatory TFLite Model Metadata that contains the mandatory AudioProperties of the solo input audio tensor and the optional (but recommended) category labels as AssociatedFiles with type TENSOR_AXI... | the_stack_v2_python_sparse | mediapipe/tasks/python/audio/audio_classifier.py | google/mediapipe | train | 23,940 |
f7a9329d5ad32224207121fe82e976e8a2743832 | [
"super(FunctionGamma, self).__init__()\nself.num = num\nself.EPSILON = 1e-07",
"num = self.num\nif num < 0.5:\n return self.PI / (math.sin(self.PI * num) * FunctionGamma(1 - num).calculateEquation())\nelse:\n num -= 1\n x = lanczos_coef[0]\n for i in range(1, len(lanczos_coef)):\n x += lanczos_... | <|body_start_0|>
super(FunctionGamma, self).__init__()
self.num = num
self.EPSILON = 1e-07
<|end_body_0|>
<|body_start_1|>
num = self.num
if num < 0.5:
return self.PI / (math.sin(self.PI * num) * FunctionGamma(1 - num).calculateEquation())
else:
n... | Class used to calculate the Gamma function. | FunctionGamma | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
<|body_0|>
def calculateEquation(self) -> float:
"""Function used to calculate the gamma function. Returns Gamma(self.num)"""
<|bod... | stack_v2_sparse_classes_36k_train_025742 | 1,589 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, num: float) -> None"
},
{
"docstring": "Function used to calculate the gamma function. Returns Gamma(self.num)",
"name": "calculateEquation",
"signature": "def calculateEquation(self) -> float"
}
] | 2 | stack_v2_sparse_classes_30k_train_003098 | Implement the Python class `FunctionGamma` described below.
Class description:
Class used to calculate the Gamma function.
Method signatures and docstrings:
- def __init__(self, num: float) -> None: Constructor.
- def calculateEquation(self) -> float: Function used to calculate the gamma function. Returns Gamma(self.... | Implement the Python class `FunctionGamma` described below.
Class description:
Class used to calculate the Gamma function.
Method signatures and docstrings:
- def __init__(self, num: float) -> None: Constructor.
- def calculateEquation(self) -> float: Function used to calculate the gamma function. Returns Gamma(self.... | c1f864dabc5ba4a83da635f37002a2e5d07b7d25 | <|skeleton|>
class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
<|body_0|>
def calculateEquation(self) -> float:
"""Function used to calculate the gamma function. Returns Gamma(self.num)"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionGamma:
"""Class used to calculate the Gamma function."""
def __init__(self, num: float) -> None:
"""Constructor."""
super(FunctionGamma, self).__init__()
self.num = num
self.EPSILON = 1e-07
def calculateEquation(self) -> float:
"""Function used to calc... | the_stack_v2_python_sparse | src/FunctionGamma.py | shvnks/comp354_calculator | train | 0 |
2a293017867d47756117337c1e69cbd15e8c88cd | [
"cluster_args = parser.add_argument_group(help='Cluster')\ncluster_args.add_argument('--region', required=True, default='-', help='Regional location (e.g. asia-east1, us-east1) of CLUSTER. See the full list of regions at https://cloud.google.com/sql/docs/instance-locations. Default: list clusters in all regions.')\... | <|body_start_0|>
cluster_args = parser.add_argument_group(help='Cluster')
cluster_args.add_argument('--region', required=True, default='-', help='Regional location (e.g. asia-east1, us-east1) of CLUSTER. See the full list of regions at https://cloud.google.com/sql/docs/instance-locations. Default: list ... | Lists AlloyDB instances in a given cluster. | List | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""Lists AlloyDB instances in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs"""
<|body_0|>
def Run(self, args):
"""Constructs and sends request. Args: args: a... | stack_v2_sparse_classes_36k_train_025743 | 3,265 | permissive | [
{
"docstring": "Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for the a... | 2 | null | Implement the Python class `List` described below.
Class description:
Lists AlloyDB instances in a given cluster.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs
- def Run(self, args): Constructs and sends r... | Implement the Python class `List` described below.
Class description:
Lists AlloyDB instances in a given cluster.
Method signatures and docstrings:
- def Args(parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs
- def Run(self, args): Constructs and sends r... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class List:
"""Lists AlloyDB instances in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs"""
<|body_0|>
def Run(self, args):
"""Constructs and sends request. Args: args: a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""Lists AlloyDB instances in a given cluster."""
def Args(parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs"""
cluster_args = parser.add_argument_group(help='Cluster')
cluster_args.add_argument('--region', r... | the_stack_v2_python_sparse | lib/surface/alloydb/instances/list.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
f9ce0754a2404c1abc3164ccd222d8899b635456 | [
"if config_path:\n cls.CONFIG_PATH = config_path\nif cls.CONFIG_PATH:\n try:\n if isfile(cls.CONFIG_PATH):\n with open(cls.CONFIG_PATH) as config_file:\n config = json.loads(config_file.read())\n for key, value in config.items():\n if value:\n... | <|body_start_0|>
if config_path:
cls.CONFIG_PATH = config_path
if cls.CONFIG_PATH:
try:
if isfile(cls.CONFIG_PATH):
with open(cls.CONFIG_PATH) as config_file:
config = json.loads(config_file.read())
... | Config | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def load_config(cls, config_path=None):
"""Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable."""
<|body_0|>
def write_values_to_file(cls, keys=None):
"""Writes the curre... | stack_v2_sparse_classes_36k_train_025744 | 6,761 | permissive | [
{
"docstring": "Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable.",
"name": "load_config",
"signature": "def load_config(cls, config_path=None)"
},
{
"docstring": "Writes the current walkoff configuration ... | 2 | stack_v2_sparse_classes_30k_val_001043 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def load_config(cls, config_path=None): Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable.
-... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def load_config(cls, config_path=None): Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable.
-... | f549633f831d34b702dfe2e77d678216fd6d7931 | <|skeleton|>
class Config:
def load_config(cls, config_path=None):
"""Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable."""
<|body_0|>
def write_values_to_file(cls, keys=None):
"""Writes the curre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
def load_config(cls, config_path=None):
"""Loads Walkoff configuration from JSON file Args: config_path (str): Optional path to the config. Defaults to the CONFIG_PATH class variable."""
if config_path:
cls.CONFIG_PATH = config_path
if cls.CONFIG_PATH:
t... | the_stack_v2_python_sparse | walkoff/config.py | MikeDeane/WALKOFF | train | 0 | |
d879b521a344a3a626862a47ad34839e085a9a35 | [
"del trainer, pl_module, batch, batch_idx, dataloader_idx\nassert outputs is not None\nfor i, image in enumerate(self.visualizer.visualize_batch(outputs)):\n filename = Path(outputs['image_path'][i])\n if self.save_images:\n file_path = self.image_save_path / filename.parent.name / filename.name\n ... | <|body_start_0|>
del trainer, pl_module, batch, batch_idx, dataloader_idx
assert outputs is not None
for i, image in enumerate(self.visualizer.visualize_batch(outputs)):
filename = Path(outputs['image_path'][i])
if self.save_images:
file_path = self.image_... | Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save the images to the filesystem, add the 'local' keyword to the `project.log_images_to` param... | ImageVisualizerCallback | [
"CC-BY-SA-4.0",
"CC-BY-SA-3.0",
"CC-BY-NC-SA-4.0",
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageVisualizerCallback:
"""Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save the images to the filesystem, add the '... | stack_v2_sparse_classes_36k_train_025745 | 4,159 | permissive | [
{
"docstring": "Show images at the end of every batch. Args: trainer (Trainer): Pytorch lightning trainer object (unused). pl_module (AnomalyModule): Lightning modules derived from BaseAnomalyLightning object as currently only they support logging images. outputs (STEP_OUTPUT | None): Outputs of the current tes... | 2 | stack_v2_sparse_classes_30k_train_008969 | Implement the Python class `ImageVisualizerCallback` described below.
Class description:
Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save ... | Implement the Python class `ImageVisualizerCallback` described below.
Class description:
Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save ... | 4abfa93dcfcb98771bc768b334c929ff9a02ce8b | <|skeleton|>
class ImageVisualizerCallback:
"""Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save the images to the filesystem, add the '... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageVisualizerCallback:
"""Callback that visualizes the inference results of a model. The callback generates a figure showing the original image, the ground truth segmentation mask, the predicted error heat map, and the predicted segmentation mask. To save the images to the filesystem, add the 'local' keywor... | the_stack_v2_python_sparse | src/anomalib/utils/callbacks/visualizer/visualizer_image.py | openvinotoolkit/anomalib | train | 2,325 |
4b32b87914d310bda0252a1927f9eb49ede9456b | [
"self.protection_source_environment = protection_source_environment\nself.protection_source_ids = protection_source_ids\nself.rpo_policy_id = rpo_policy_id",
"if dictionary is None:\n return None\nprotection_source_environment = dictionary.get('protectionSourceEnvironment')\nprotection_source_ids = dictionary.... | <|body_start_0|>
self.protection_source_environment = protection_source_environment
self.protection_source_ids = protection_source_ids
self.rpo_policy_id = rpo_policy_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
protection_source_environment ... | Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment types such as 'kView', 'kSQL', 'kVMware', etc. NOTE: 'k... | ProtectObjectParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment type... | stack_v2_sparse_classes_36k_train_025746 | 6,100 | permissive | [
{
"docstring": "Constructor for the ProtectObjectParameters class",
"name": "__init__",
"signature": "def __init__(self, protection_source_environment=None, protection_source_ids=None, rpo_policy_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | null | Implement the Python class `ProtectObjectParameters` described below.
Class description:
Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection So... | Implement the Python class `ProtectObjectParameters` described below.
Class description:
Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection So... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectObjectParameters:
"""Implementation of the 'ProtectObjectParameters' model. Specifies the parameters to protect an object. Attributes: protection_source_environment (ProtectionSourceEnvironmentEnum): Specifies the environment type of the Protection Source object. Supported environment types such as 'kV... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protect_object_parameters.py | cohesity/management-sdk-python | train | 24 |
ee1c9b9b5a049f020d7ccfad25a751d51aed0a1b | [
"context = self.current_context = Context.by_name(self.current_context_name)\nself.current_context_name = name\nreturn context",
"context = self.set_context(self.current_context_name)\nfor event in eventreceiver.read_from_socket(sockname=self.sockname, connect_backoff=self.connect_backoff):\n if event.final:\n... | <|body_start_0|>
context = self.current_context = Context.by_name(self.current_context_name)
self.current_context_name = name
return context
<|end_body_0|>
<|body_start_1|>
context = self.set_context(self.current_context_name)
for event in eventreceiver.read_from_socket(sockname... | Interpreter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interpreter:
def set_context(self, name):
"""Reload our currently configured context"""
<|body_0|>
def run(self, result_queue):
"""Run the interpreter on an event stream"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context = self.current_context ... | stack_v2_sparse_classes_36k_train_025747 | 3,132 | no_license | [
{
"docstring": "Reload our currently configured context",
"name": "set_context",
"signature": "def set_context(self, name)"
},
{
"docstring": "Run the interpreter on an event stream",
"name": "run",
"signature": "def run(self, result_queue)"
}
] | 2 | null | Implement the Python class `Interpreter` described below.
Class description:
Implement the Interpreter class.
Method signatures and docstrings:
- def set_context(self, name): Reload our currently configured context
- def run(self, result_queue): Run the interpreter on an event stream | Implement the Python class `Interpreter` described below.
Class description:
Implement the Interpreter class.
Method signatures and docstrings:
- def set_context(self, name): Reload our currently configured context
- def run(self, result_queue): Run the interpreter on an event stream
<|skeleton|>
class Interpreter:
... | 4467e6e32a5d9a5f45f256b4c3f96f798842fe80 | <|skeleton|>
class Interpreter:
def set_context(self, name):
"""Reload our currently configured context"""
<|body_0|>
def run(self, result_queue):
"""Run the interpreter on an event stream"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interpreter:
def set_context(self, name):
"""Reload our currently configured context"""
context = self.current_context = Context.by_name(self.current_context_name)
self.current_context_name = name
return context
def run(self, result_queue):
"""Run the interpreter o... | the_stack_v2_python_sparse | listener/interpreter.py | mcfletch/listener2 | train | 1 | |
0b492b71a35ba32da19b45acf5f03baec3023ec3 | [
"super().__init__(game, x, y, 'SPEEDUP')\nself.picker = None\nself.picked_at = 0\nself.picker_speed = 0\nself.picker_max_speed = 0",
"self.item_group.remove(self)\nself.rect = pygame.Rect(-1000, -1000, 0, 0)\nspeed_up = ITEMS['SPEEDUP']['SPEED']\nself.picker = picker\nself.picker_speed = picker.speed\nself.picker... | <|body_start_0|>
super().__init__(game, x, y, 'SPEEDUP')
self.picker = None
self.picked_at = 0
self.picker_speed = 0
self.picker_max_speed = 0
<|end_body_0|>
<|body_start_1|>
self.item_group.remove(self)
self.rect = pygame.Rect(-1000, -1000, 0, 0)
speed_u... | SpeedUp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedUp:
def __init__(self, game, x, y):
"""Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was picked"""
<|body_0|>
def picked_by(self, picker):
"""Once picked we remove fro... | stack_v2_sparse_classes_36k_train_025748 | 10,333 | no_license | [
{
"docstring": "Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was picked",
"name": "__init__",
"signature": "def __init__(self, game, x, y)"
},
{
"docstring": "Once picked we remove from items group - ... | 3 | null | Implement the Python class `SpeedUp` described below.
Class description:
Implement the SpeedUp class.
Method signatures and docstrings:
- def __init__(self, game, x, y): Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was pic... | Implement the Python class `SpeedUp` described below.
Class description:
Implement the SpeedUp class.
Method signatures and docstrings:
- def __init__(self, game, x, y): Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was pic... | 349367254f85e3e4273cede067ca950913a1332c | <|skeleton|>
class SpeedUp:
def __init__(self, game, x, y):
"""Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was picked"""
<|body_0|>
def picked_by(self, picker):
"""Once picked we remove fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeedUp:
def __init__(self, game, x, y):
"""Speed up increases player's speed for a few seconds, then returns it back to regular speed, so it needs to store original values and when it was picked"""
super().__init__(game, x, y, 'SPEEDUP')
self.picker = None
self.picked_at = 0
... | the_stack_v2_python_sparse | 11-videogames/Referencia/11-Items/sprites.py | pythoncanarias/eoi | train | 26 | |
d4c0e4196111b8af34ccf7cdc63f1a47a9a78e9f | [
"assert isinstance(block_string, str)\nops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nassert 's' in options and len(options['s']) == 1 or (len(options['s']) == 2 and options... | <|body_start_0|>
assert isinstance(block_string, str)
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split('(\\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[key] = value
assert 's' in... | Block Decoder for readability, straight from the official TensorFlow repository. | BlockDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockDecoder:
"""Block Decoder for readability, straight from the official TensorFlow repository."""
def _decode_block_string(block_string):
"""Get a block through a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: 'r1_k3_s11_e1_i32_o1... | stack_v2_sparse_classes_36k_train_025749 | 42,101 | permissive | [
{
"docstring": "Get a block through a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: 'r1_k3_s11_e1_i32_o16_se0.25_noskip'. Returns: BlockArgs: The namedtuple defined at the top of this file.",
"name": "_decode_block_string",
"signature": "def _decode_bl... | 4 | stack_v2_sparse_classes_30k_train_019229 | Implement the Python class `BlockDecoder` described below.
Class description:
Block Decoder for readability, straight from the official TensorFlow repository.
Method signatures and docstrings:
- def _decode_block_string(block_string): Get a block through a string notation of arguments. Args: block_string (str): A str... | Implement the Python class `BlockDecoder` described below.
Class description:
Block Decoder for readability, straight from the official TensorFlow repository.
Method signatures and docstrings:
- def _decode_block_string(block_string): Get a block through a string notation of arguments. Args: block_string (str): A str... | a835a21cc45d13bd1da4b7cf4c0a837d52c2844d | <|skeleton|>
class BlockDecoder:
"""Block Decoder for readability, straight from the official TensorFlow repository."""
def _decode_block_string(block_string):
"""Get a block through a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: 'r1_k3_s11_e1_i32_o1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockDecoder:
"""Block Decoder for readability, straight from the official TensorFlow repository."""
def _decode_block_string(block_string):
"""Get a block through a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: 'r1_k3_s11_e1_i32_o16_se0.25_nosk... | the_stack_v2_python_sparse | ImitationLearning/backbone.py | Suryavf/SelfDrivingCar | train | 13 |
336ad360bdc928acc7c2bf96e2998ca6cb6a0671 | [
"with open(filename, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n for i in input_listdict:\n writer.writerow(i)\nlog.info(f'Wrote {filename}')",
"with open(filename, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader... | <|body_start_0|>
with open(filename, 'w') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for i in input_listdict:
writer.writerow(i)
log.info(f'Wrote {filename}')
<|end_body_0|>
<|body_start_1|>
with open(filename... | CSVWrite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVWrite:
def write_csv_from_list_of_dicts(self, input_listdict, fieldnames, filename):
"""Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of dicts: [ { "Column1": "Row 1" "Column2": "Row 1" }, { "Column1": "Row 2" "Column2": "Row 2" } ] W... | stack_v2_sparse_classes_36k_train_025750 | 1,977 | no_license | [
{
"docstring": "Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of dicts: [ { \"Column1\": \"Row 1\" \"Column2\": \"Row 1\" }, { \"Column1\": \"Row 2\" \"Column2\": \"Row 2\" } ] Will generate the following CSV: Column1,Column2 Row1,Row1 Row2,Row2",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_000754 | Implement the Python class `CSVWrite` described below.
Class description:
Implement the CSVWrite class.
Method signatures and docstrings:
- def write_csv_from_list_of_dicts(self, input_listdict, fieldnames, filename): Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of ... | Implement the Python class `CSVWrite` described below.
Class description:
Implement the CSVWrite class.
Method signatures and docstrings:
- def write_csv_from_list_of_dicts(self, input_listdict, fieldnames, filename): Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of ... | 2de2d67fd76295210a313bdc35ee7f6686082d1c | <|skeleton|>
class CSVWrite:
def write_csv_from_list_of_dicts(self, input_listdict, fieldnames, filename):
"""Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of dicts: [ { "Column1": "Row 1" "Column2": "Row 1" }, { "Column1": "Row 2" "Column2": "Row 2" } ] W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSVWrite:
def write_csv_from_list_of_dicts(self, input_listdict, fieldnames, filename):
"""Expects a list of dictionaries. Fieldnames must be specified for each column. Example input list of dicts: [ { "Column1": "Row 1" "Column2": "Row 1" }, { "Column1": "Row 2" "Column2": "Row 2" } ] Will generate t... | the_stack_v2_python_sparse | app/csv_wr.py | otsu81/aws-parseley | train | 1 | |
6e5a64ab53bc1efb17b885f09fcf08c992340d53 | [
"super(FinalizeSlicedDownloadTask, self).__init__(source_resource, final_destination_resource, posix_to_set=posix_to_set, user_request_args=user_request_args)\nself._temporary_destination_resource = temporary_destination_resource\nself._final_destination_resource = final_destination_resource\nself._delete_source = ... | <|body_start_0|>
super(FinalizeSlicedDownloadTask, self).__init__(source_resource, final_destination_resource, posix_to_set=posix_to_set, user_request_args=user_request_args)
self._temporary_destination_resource = temporary_destination_resource
self._final_destination_resource = final_destinatio... | Performs final steps of sliced download. | FinalizeSlicedDownloadTask | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, temporary_destination_resource, final_destination_resource, delete_source=False, do_not_decompress=False, posix_to_set=None, print_created_message=False, system_posix_data=None, use... | stack_v2_sparse_classes_36k_train_025751 | 7,015 | permissive | [
{
"docstring": "Initializes task. Args: source_resource (resource_reference.ObjectResource): Should contain object's metadata for checking content encoding. temporary_destination_resource (resource_reference.FileObjectResource): Must contain a local path to the temporary file written to during transfers. final_... | 2 | stack_v2_sparse_classes_30k_train_007370 | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, temporary_destination_resource, final_destination_resource, delete_source=False, do_not_decompress=False, posix_t... | Implement the Python class `FinalizeSlicedDownloadTask` described below.
Class description:
Performs final steps of sliced download.
Method signatures and docstrings:
- def __init__(self, source_resource, temporary_destination_resource, final_destination_resource, delete_source=False, do_not_decompress=False, posix_t... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, temporary_destination_resource, final_destination_resource, delete_source=False, do_not_decompress=False, posix_to_set=None, print_created_message=False, system_posix_data=None, use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FinalizeSlicedDownloadTask:
"""Performs final steps of sliced download."""
def __init__(self, source_resource, temporary_destination_resource, final_destination_resource, delete_source=False, do_not_decompress=False, posix_to_set=None, print_created_message=False, system_posix_data=None, user_request_arg... | the_stack_v2_python_sparse | lib/googlecloudsdk/command_lib/storage/tasks/cp/finalize_sliced_download_task.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
58cee2df48395837050e7d020886b67649a06492 | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_bbox = cost_bbox\nself.cost_giou = cost_giou\nassert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'",
"from scipy.optimize import linear_sum_assignment\nbatch_size, num_queries = outputs['pred_logits'].shape[:2]\nout_prob = o... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'
<|end_body_0|>
<|body_start_1|>
from scipy.optimize import linear_sum_... | From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py) | HungarianMatcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMatcher:
"""From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py)"""
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification er... | stack_v2_sparse_classes_36k_train_025752 | 18,998 | permissive | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding... | 2 | stack_v2_sparse_classes_30k_train_016703 | Implement the Python class `HungarianMatcher` described below.
Class description:
From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py)
Method signatures and docstrings:
- def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1): Creates the matcher Params: cost_cl... | Implement the Python class `HungarianMatcher` described below.
Class description:
From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py)
Method signatures and docstrings:
- def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1): Creates the matcher Params: cost_cl... | 6b424dadac60631c126e864551bd7202c2e19478 | <|skeleton|>
class HungarianMatcher:
"""From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py)"""
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification er... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HungarianMatcher:
"""From DETR source: https://github.com/facebookresearch/detr (detr/models/matcher.py)"""
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification error in the ma... | the_stack_v2_python_sparse | art/estimators/object_detection/detr.py | kztakemoto/adversarial-robustness-toolbox | train | 0 |
bebd3689ed2b3dc361d1b32344dcff8391ea2af4 | [
"if isinstance(item, ChinazWebinfoItem):\n image_url = item['CoverImage']\n yield scrapy.Request(image_url)",
"paths = [result['path'] for status, result in results if status]\nprint('图片下载结果:', results)\nif len(paths) > 0:\n print('图片下载成功')\n os.rename(images_store + '/' + paths[0], images_store + '/f... | <|body_start_0|>
if isinstance(item, ChinazWebinfoItem):
image_url = item['CoverImage']
yield scrapy.Request(image_url)
<|end_body_0|>
<|body_start_1|>
paths = [result['path'] for status, result in results if status]
print('图片下载结果:', results)
if len(paths) > 0:
... | ChinazImagesPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
<|body_0|>
def item_completed(self, results, item, info):
"""图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckeck... | stack_v2_sparse_classes_36k_train_025753 | 6,372 | no_license | [
{
"docstring": "根据图片url地址发起请求 :param item: :param info: :return:",
"name": "get_media_requests",
"signature": "def get_media_requests(self, item, info)"
},
{
"docstring": "图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckecksum':'经过hash加密的一个字符串'} :param item: :... | 2 | stack_v2_sparse_classes_30k_val_000225 | Implement the Python class `ChinazImagesPipeline` described below.
Class description:
Implement the ChinazImagesPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): 根据图片url地址发起请求 :param item: :param info: :return:
- def item_completed(self, results, item, info): 图片下载 :param re... | Implement the Python class `ChinazImagesPipeline` described below.
Class description:
Implement the ChinazImagesPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): 根据图片url地址发起请求 :param item: :param info: :return:
- def item_completed(self, results, item, info): 图片下载 :param re... | 841cad4bf84c6e3af98a32f4f33ebda62055680c | <|skeleton|>
class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
<|body_0|>
def item_completed(self, results, item, info):
"""图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckeck... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
if isinstance(item, ChinazWebinfoItem):
image_url = item['CoverImage']
yield scrapy.Request(image_url)
def item_completed(self, results, item, inf... | the_stack_v2_python_sparse | scrapy_Spider/Chinaz/Chinaz/pipelines.py | aini626204777/spider | train | 0 | |
37e869cac448280284f8cbd728f29824fb7b8659 | [
"conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, energy_carriers_worksheet = self.read_excel(locator)\nself.ENERGY_CARRIERS = energy_carriers_worksheet\nself.FEEDSTOCKS = feedstocks_worksheets\nself.PIPING = distribution_systems_worksheets['THERMAL_GRID']\nself.PV = conversion... | <|body_start_0|>
conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, energy_carriers_worksheet = self.read_excel(locator)
self.ENERGY_CARRIERS = energy_carriers_worksheet
self.FEEDSTOCKS = feedstocks_worksheets
self.PIPING = distribution_systems_workshe... | Expose the worksheets in supply_systems.xls as pandas.Dataframes. | SupplySystemsDatabase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
<|body_0|>
def read_excel(self, locator):
"""Read in the excel... | stack_v2_sparse_classes_36k_train_025754 | 2,919 | permissive | [
{
"docstring": ":param cea.inputlocator.InputLocator locator: provides the path to the",
"name": "__init__",
"signature": "def __init__(self, locator)"
},
{
"docstring": "Read in the excel file, using the cache _locators",
"name": "read_excel",
"signature": "def read_excel(self, locator)... | 2 | null | Implement the Python class `SupplySystemsDatabase` described below.
Class description:
Expose the worksheets in supply_systems.xls as pandas.Dataframes.
Method signatures and docstrings:
- def __init__(self, locator): :param cea.inputlocator.InputLocator locator: provides the path to the
- def read_excel(self, locato... | Implement the Python class `SupplySystemsDatabase` described below.
Class description:
Expose the worksheets in supply_systems.xls as pandas.Dataframes.
Method signatures and docstrings:
- def __init__(self, locator): :param cea.inputlocator.InputLocator locator: provides the path to the
- def read_excel(self, locato... | b84bcefdfdfc2bc0e009b5284b74391a957995ac | <|skeleton|>
class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
<|body_0|>
def read_excel(self, locator):
"""Read in the excel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, e... | the_stack_v2_python_sparse | cea/technologies/supply_systems_database.py | architecture-building-systems/CityEnergyAnalyst | train | 166 |
8141b39e473bac486091d05e3fdfc659d8f6e57f | [
"sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings}))\nres, hp = ([[0, 0]], [(0, float('inf'))])\nfor x, negH, R in sortedBuilding:\n while x >= hp[0][1]:\n heapq.heappop(hp)\n if negH:\n heapq.heappush(hp, (negH, R))\n if res[-1][1] +... | <|body_start_0|>
sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings}))
res, hp = ([[0, 0]], [(0, float('inf'))])
for x, negH, R in sortedBuilding:
while x >= hp[0][1]:
heapq.heappop(hp)
if negH:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getSkyline(self, buildings):
""":type buildings: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def getSkylineSlow(self, buildings):
""":type buildings: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_025755 | 1,831 | no_license | [
{
"docstring": ":type buildings: List[List[int]] :rtype: List[List[int]]",
"name": "getSkyline",
"signature": "def getSkyline(self, buildings)"
},
{
"docstring": ":type buildings: List[List[int]] :rtype: List[List[int]]",
"name": "getSkylineSlow",
"signature": "def getSkylineSlow(self, b... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]]
- def getSkylineSlow(self, buildings): :type buildings: List[List[int]] :rtype: List[Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getSkyline(self, buildings): :type buildings: List[List[int]] :rtype: List[List[int]]
- def getSkylineSlow(self, buildings): :type buildings: List[List[int]] :rtype: List[Lis... | 75aef2f6c42aeb51261b9450a24099957a084d51 | <|skeleton|>
class Solution:
def getSkyline(self, buildings):
""":type buildings: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def getSkylineSlow(self, buildings):
""":type buildings: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getSkyline(self, buildings):
""":type buildings: List[List[int]] :rtype: List[List[int]]"""
sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings}))
res, hp = ([[0, 0]], [(0, float('inf'))])
for x, negH, R in s... | the_stack_v2_python_sparse | Python/0218_TheSkylineProblem/getSkyline.py | mtmmy/Leetcode | train | 3 | |
7b0cb8b97a0df3d18ace44eb59759f7c824c2ddd | [
"GlancesExport.__init__(self, config=config, args=args)\nself.host = None\nself.port = None\nself.prefix = None\nself.export_enable = self.load_conf()\nif not self.export_enable:\n sys.exit(2)\nif self.prefix is None:\n self.prefix = 'glances'\nself.client = StatsClient(self.host, int(self.port), prefix=self.... | <|body_start_0|>
GlancesExport.__init__(self, config=config, args=args)
self.host = None
self.port = None
self.prefix = None
self.export_enable = self.load_conf()
if not self.export_enable:
sys.exit(2)
if self.prefix is None:
self.prefix = ... | This class manages the Statsd export module. | Export | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Export:
"""This class manages the Statsd export module."""
def __init__(self, config=None, args=None):
"""Init the Statsd export IF."""
<|body_0|>
def load_conf(self, section='statsd'):
"""Load the Statsd configuration in the Glances configuration file"""
... | stack_v2_sparse_classes_36k_train_025756 | 3,446 | no_license | [
{
"docstring": "Init the Statsd export IF.",
"name": "__init__",
"signature": "def __init__(self, config=None, args=None)"
},
{
"docstring": "Load the Statsd configuration in the Glances configuration file",
"name": "load_conf",
"signature": "def load_conf(self, section='statsd')"
},
... | 4 | null | Implement the Python class `Export` described below.
Class description:
This class manages the Statsd export module.
Method signatures and docstrings:
- def __init__(self, config=None, args=None): Init the Statsd export IF.
- def load_conf(self, section='statsd'): Load the Statsd configuration in the Glances configur... | Implement the Python class `Export` described below.
Class description:
This class manages the Statsd export module.
Method signatures and docstrings:
- def __init__(self, config=None, args=None): Init the Statsd export IF.
- def load_conf(self, section='statsd'): Load the Statsd configuration in the Glances configur... | e790277ecbdda638bd0d212460a15b601c0d47dc | <|skeleton|>
class Export:
"""This class manages the Statsd export module."""
def __init__(self, config=None, args=None):
"""Init the Statsd export IF."""
<|body_0|>
def load_conf(self, section='statsd'):
"""Load the Statsd configuration in the Glances configuration file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Export:
"""This class manages the Statsd export module."""
def __init__(self, config=None, args=None):
"""Init the Statsd export IF."""
GlancesExport.__init__(self, config=config, args=args)
self.host = None
self.port = None
self.prefix = None
self.export_e... | the_stack_v2_python_sparse | usr/lib/python3/dist-packages/glances/exports/glances_statsd.py | kojitaniguchi/isucon-summer | train | 1 |
7f5fe0bae7e7993b2f15d7ffa59395353187b70a | [
"self.Wz = np.random.randn(i + h, h)\nself.bz = np.zeros((1, h))\nself.Wr = np.random.randn(i + h, h)\nself.br = np.zeros((1, h))\nself.Wh = np.random.randn(i + h, h)\nself.bh = np.zeros((1, h))\nself.Wy = np.random.randn(h, o)\nself.by = np.zeros((1, o))",
"concat = np.concatenate([h_prev, x_t], axis=1)\nr = sig... | <|body_start_0|>
self.Wz = np.random.randn(i + h, h)
self.bz = np.zeros((1, h))
self.Wr = np.random.randn(i + h, h)
self.br = np.zeros((1, h))
self.Wh = np.random.randn(i + h, h)
self.bh = np.zeros((1, h))
self.Wy = np.random.randn(h, o)
self.by = np.zeros... | This class represents a GRUCell | GRUCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""This class represents a GRUCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""... | stack_v2_sparse_classes_36k_train_025757 | 1,796 | permissive | [
{
"docstring": "All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "This method calculates de forward prop for one time-step x_t ... | 2 | stack_v2_sparse_classes_30k_train_002707 | Implement the Python class `GRUCell` described below.
Class description:
This class represents a GRUCell
Method signatures and docstrings:
- def __init__(self, i, h, o): All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward... | Implement the Python class `GRUCell` described below.
Class description:
This class represents a GRUCell
Method signatures and docstrings:
- def __init__(self, i, h, o): All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class GRUCell:
"""This class represents a GRUCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""This class represents a GRUCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
self.Wz = np.random.randn(i + h, h)
self.bz = np.zeros((1, h))
... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | linkem97/holbertonschool-machine_learning | train | 0 |
03b47207703a6bb03bdde3d73f42c0b18b63031f | [
"super(ToyEmbedRNN, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.output_size = output_size\nself.embed_size = embed_size\nself.dropout = nn.Dropout(p=0.5)\nself.embed = nn.Embedding(input_size, embed_size)\nself.rnn = nn.LSTM(input_size=embed_size, hidden_size=hidden_size)\ns... | <|body_start_0|>
super(ToyEmbedRNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.embed_size = embed_size
self.dropout = nn.Dropout(p=0.5)
self.embed = nn.Embedding(input_size, embed_size)
... | Recurrent neural network | ToyEmbedRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToyEmbedRNN:
"""Recurrent neural network"""
def __init__(self, input_size, hidden_size, output_size, embed_size=16):
"""Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output_size (int): number of output categories."""
<|bo... | stack_v2_sparse_classes_36k_train_025758 | 14,976 | no_license | [
{
"docstring": "Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output_size (int): number of output categories.",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, output_size, embed_size=16)"
},
{
"docstring": "Arg... | 2 | stack_v2_sparse_classes_30k_train_003821 | Implement the Python class `ToyEmbedRNN` described below.
Class description:
Recurrent neural network
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size, embed_size=16): Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output... | Implement the Python class `ToyEmbedRNN` described below.
Class description:
Recurrent neural network
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size, embed_size=16): Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output... | 610f5e0789fd87ca7390bf458b6699ed83331a4f | <|skeleton|>
class ToyEmbedRNN:
"""Recurrent neural network"""
def __init__(self, input_size, hidden_size, output_size, embed_size=16):
"""Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output_size (int): number of output categories."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToyEmbedRNN:
"""Recurrent neural network"""
def __init__(self, input_size, hidden_size, output_size, embed_size=16):
"""Args: input_size (int): input dimension of a time step. hidden_size (int): dimesion of hidden layer. output_size (int): number of output categories."""
super(ToyEmbedRNN... | the_stack_v2_python_sparse | model/qa_reject/model.py | boxiangliu/abbrev | train | 0 |
74cf2663c72e62fd7acaea89e5afe5b93977d1ae | [
"try:\n obj = QueryPlansAcquired.objects.get(pk=pk)\n self.check_object_permissions(self.request, obj)\n return obj\nexcept QueryPlansAcquired.DoesNotExist:\n raise Http404",
"det_plan = self.get_object(pk)\nplan = QueryPlansAcquiredSerializer(det_plan)\nreturn Response(plan.data)",
"client_id = Ope... | <|body_start_0|>
try:
obj = QueryPlansAcquired.objects.get(pk=pk)
self.check_object_permissions(self.request, obj)
return obj
except QueryPlansAcquired.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
det_plan = self.get_object(pk)
... | Detalle de Plan Adquirido. | QueryPlansAcquiredDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryPlansAcquiredDetailView:
"""Detalle de Plan Adquirido."""
def get_object(self, pk):
"""Obtener Objeto."""
<|body_0|>
def get(self, request, pk):
"""Obtener el Plan."""
<|body_1|>
def put(self, request, pk):
"""Elegir el plan requrido y d... | stack_v2_sparse_classes_36k_train_025759 | 44,248 | no_license | [
{
"docstring": "Obtener Objeto.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Obtener el Plan.",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "Elegir el plan requrido y desactivar los demas.",
"name": "put",
... | 3 | stack_v2_sparse_classes_30k_train_003932 | Implement the Python class `QueryPlansAcquiredDetailView` described below.
Class description:
Detalle de Plan Adquirido.
Method signatures and docstrings:
- def get_object(self, pk): Obtener Objeto.
- def get(self, request, pk): Obtener el Plan.
- def put(self, request, pk): Elegir el plan requrido y desactivar los d... | Implement the Python class `QueryPlansAcquiredDetailView` described below.
Class description:
Detalle de Plan Adquirido.
Method signatures and docstrings:
- def get_object(self, pk): Obtener Objeto.
- def get(self, request, pk): Obtener el Plan.
- def put(self, request, pk): Elegir el plan requrido y desactivar los d... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class QueryPlansAcquiredDetailView:
"""Detalle de Plan Adquirido."""
def get_object(self, pk):
"""Obtener Objeto."""
<|body_0|>
def get(self, request, pk):
"""Obtener el Plan."""
<|body_1|>
def put(self, request, pk):
"""Elegir el plan requrido y d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryPlansAcquiredDetailView:
"""Detalle de Plan Adquirido."""
def get_object(self, pk):
"""Obtener Objeto."""
try:
obj = QueryPlansAcquired.objects.get(pk=pk)
self.check_object_permissions(self.request, obj)
return obj
except QueryPlansAcquired... | the_stack_v2_python_sparse | api/views/plan.py | darwinv/api-chat-lnk | train | 0 |
b28deb77c1d43ca3c2bf6b7a3e852129f85c9f93 | [
"if self.goal_step < len(self.goal_sequence):\n return self.success_threshold['cube_face_angle']\nreturn 0.05",
"if self.goal_step < len(self.goal_sequence):\n goal = self.goal_sequence[self.goal_step]\nelse:\n goal = self.goal_sequence[-1]\n self.reached_terminal_state = True\nreturn goal"
] | <|body_start_0|>
if self.goal_step < len(self.goal_sequence):
return self.success_threshold['cube_face_angle']
return 0.05
<|end_body_0|>
<|body_start_1|>
if self.goal_step < len(self.goal_sequence):
goal = self.goal_sequence[self.goal_step]
else:
goa... | ReleaseCubeSolverGoal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseCubeSolverGoal:
def face_threshold(self):
"""Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment once the cube has been fully solved :return:"""
<|body_0|>
def _get_goal_action(self):
"""Ge... | stack_v2_sparse_classes_36k_train_025760 | 977 | permissive | [
{
"docstring": "Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment once the cube has been fully solved :return:",
"name": "face_threshold",
"signature": "def face_threshold(self)"
},
{
"docstring": "Get the required action t... | 2 | null | Implement the Python class `ReleaseCubeSolverGoal` described below.
Class description:
Implement the ReleaseCubeSolverGoal class.
Method signatures and docstrings:
- def face_threshold(self): Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment onc... | Implement the Python class `ReleaseCubeSolverGoal` described below.
Class description:
Implement the ReleaseCubeSolverGoal class.
Method signatures and docstrings:
- def face_threshold(self): Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment onc... | 9ff1111fd557b1a01911d7d8c9d59a453071c96e | <|skeleton|>
class ReleaseCubeSolverGoal:
def face_threshold(self):
"""Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment once the cube has been fully solved :return:"""
<|body_0|>
def _get_goal_action(self):
"""Ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleaseCubeSolverGoal:
def face_threshold(self):
"""Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment once the cube has been fully solved :return:"""
if self.goal_step < len(self.goal_sequence):
return self.su... | the_stack_v2_python_sparse | robogym/envs/dactyl/goals/release_cube_solver.py | lichao-218/robogym | train | 0 | |
975ea5f6598a7a6454e5ea165cf71f09c2410157 | [
"if 'tor' in args:\n self.tor = args['tor']\nelse:\n self.tor = 0.0001\nsuper(CoreSet, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)",
"m = np.shape(X)[0]\nif np.shape(X_set)[0] == 0:\n min_dist = np.tile(float('inf'), m)\nelse:\n dist_ctr = pairwise_distances(X, X_set)\n min_dist... | <|body_start_0|>
if 'tor' in args:
self.tor = args['tor']
else:
self.tor = 0.0001
super(CoreSet, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)
<|end_body_0|>
<|body_start_1|>
m = np.shape(X)[0]
if np.shape(X_set)[0] == 0:
min... | Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a greedy furthest-first traversal conditioned on all labeled examples. Paramet... | CoreSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoreSet:
"""Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a greedy furthest-first traversal condition... | stack_v2_sparse_classes_36k_train_025761 | 3,021 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, X, Y, unlabeled_x, net, handler, nclasses, args={})"
},
{
"docstring": "Selects points with maximum distance Parameters ---------- X: numpy array Embeddings of unlabeled set X_set: numpy array Embeddings of... | 3 | stack_v2_sparse_classes_30k_train_012036 | Implement the Python class `CoreSet` described below.
Class description:
Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a gr... | Implement the Python class `CoreSet` described below.
Class description:
Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a gr... | c8c3489920a24537a849eb8446efc9c2e19ab193 | <|skeleton|>
class CoreSet:
"""Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a greedy furthest-first traversal condition... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoreSet:
"""Implementation of CoreSet :footcite:`sener2018active` Strategy. A diversity-based approach using coreset selection. The embedding of each example is computed by the network’s penultimate layer and the samples at each round are selected using a greedy furthest-first traversal conditioned on all lab... | the_stack_v2_python_sparse | distil/active_learning_strategies/core_set.py | chipsh/distil | train | 1 |
d25ea14b41fa1106a227bad2f810905bd1245296 | [
"self.target = self.config.driverlicense.collection.data\nself.temp = self.config.driverlicense.collection.temp\nself.analyse(start, end)",
"cur = self.target.find()\ndf = pd.DataFrame(list(cur))\nresults = {}\nif start and end:\n df = df[df.Date >= start & df.Date <= end]\ndf['Kontakte Mio'].replace('--', Non... | <|body_start_0|>
self.target = self.config.driverlicense.collection.data
self.temp = self.config.driverlicense.collection.temp
self.analyse(start, end)
<|end_body_0|>
<|body_start_1|>
cur = self.target.find()
df = pd.DataFrame(list(cur))
results = {}
if start and... | ExtractFacts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractFacts:
def execute(self, start=None, end=None, *args, **kwargs):
""":param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:"""
<|body_0|>
def analyse(self, start, end):
"""This function gets the data from the database, cr... | stack_v2_sparse_classes_36k_train_025762 | 1,874 | no_license | [
{
"docstring": ":param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:",
"name": "execute",
"signature": "def execute(self, start=None, end=None, *args, **kwargs)"
},
{
"docstring": "This function gets the data from the database, creates a dataframe for th... | 2 | stack_v2_sparse_classes_30k_train_014585 | Implement the Python class `ExtractFacts` described below.
Class description:
Implement the ExtractFacts class.
Method signatures and docstrings:
- def execute(self, start=None, end=None, *args, **kwargs): :param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:
- def analyse(sel... | Implement the Python class `ExtractFacts` described below.
Class description:
Implement the ExtractFacts class.
Method signatures and docstrings:
- def execute(self, start=None, end=None, *args, **kwargs): :param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:
- def analyse(sel... | 30e3e8828803c50c0a612f206e53c42c3d8df752 | <|skeleton|>
class ExtractFacts:
def execute(self, start=None, end=None, *args, **kwargs):
""":param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:"""
<|body_0|>
def analyse(self, start, end):
"""This function gets the data from the database, cr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractFacts:
def execute(self, start=None, end=None, *args, **kwargs):
""":param test: control, if test don't write data to mongoDB :param args: :param kwargs: :return:"""
self.target = self.config.driverlicense.collection.data
self.temp = self.config.driverlicense.collection.temp
... | the_stack_v2_python_sparse | driverlicense/jobs/extract.py | m-rau/driverlicense | train | 0 | |
db5392730296201fc393727bab4d48779fbfa707 | [
"super().__init__(address)\nself._points = points\nself._rewards = rewards",
"rewards = ''\nfor reward, points in self._rewards.items():\n rewards += f'{reward} >>> {points} PTS\\n'\nreturn f'====== {self._address.company_name.upper()} LOYALTY CARD (ID {self.id})======\\nCurrent Points: {self._points}\\nRedeem... | <|body_start_0|>
super().__init__(address)
self._points = points
self._rewards = rewards
<|end_body_0|>
<|body_start_1|>
rewards = ''
for reward, points in self._rewards.items():
rewards += f'{reward} >>> {points} PTS\n'
return f'====== {self._address.company... | Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards. | LoyaltyCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoyaltyCard:
"""Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards."""
def __init__(self, points, rewards, address):
"""Initialise LoyaltyCard. :param points: int :param rewards: {reward (String): point value... | stack_v2_sparse_classes_36k_train_025763 | 10,626 | no_license | [
{
"docstring": "Initialise LoyaltyCard. :param points: int :param rewards: {reward (String): point value (int)} :param address: Address",
"name": "__init__",
"signature": "def __init__(self, points, rewards, address)"
},
{
"docstring": "Format how LoyaltyCards are displayed. :return: String",
... | 2 | stack_v2_sparse_classes_30k_train_021403 | Implement the Python class `LoyaltyCard` described below.
Class description:
Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards.
Method signatures and docstrings:
- def __init__(self, points, rewards, address): Initialise LoyaltyCard. :param ... | Implement the Python class `LoyaltyCard` described below.
Class description:
Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards.
Method signatures and docstrings:
- def __init__(self, points, rewards, address): Initialise LoyaltyCard. :param ... | b7695cc7cf0860aa9c8bf492b1bd06bd88b9af41 | <|skeleton|>
class LoyaltyCard:
"""Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards."""
def __init__(self, points, rewards, address):
"""Initialise LoyaltyCard. :param points: int :param rewards: {reward (String): point value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoyaltyCard:
"""Represent basic cards that reward users for loyalty to the brand. Includes restaurant stamp cards and "buy X get Y free" cards."""
def __init__(self, points, rewards, address):
"""Initialise LoyaltyCard. :param points: int :param rewards: {reward (String): point value (int)} :para... | the_stack_v2_python_sparse | Assignments/Assignment 2/card.py | sakshambhardwaj523/Python-OOP-Projects | train | 0 |
7c40f1587d8d0894021992c181afde8425bcd681 | [
"self.server = server\nserver.register_event_handler(ofcomm.message.name, self)\nself.count = 0\nself.period = period\nself.server.post_event(yapc.priv_callback(self, None), self.period)",
"if isinstance(event, yapc.priv_callback):\n self.server.post_event(yapc.priv_callback(self, None), self.period)\n outp... | <|body_start_0|>
self.server = server
server.register_event_handler(ofcomm.message.name, self)
self.count = 0
self.period = period
self.server.post_event(yapc.priv_callback(self, None), self.period)
<|end_body_0|>
<|body_start_1|>
if isinstance(event, yapc.priv_callback)... | Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011 | of_msg_count | [
"LicenseRef-scancode-x11-stanford"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class of_msg_count:
"""Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011"""
def __init__(self, server, period=5):
"""Initialize @param server yapc core @param period period before each printout"""
<|body_0|>
def processevent(self, event):
... | stack_v2_sparse_classes_36k_train_025764 | 2,198 | permissive | [
{
"docstring": "Initialize @param server yapc core @param period period before each printout",
"name": "__init__",
"signature": "def __init__(self, server, period=5)"
},
{
"docstring": "Handle event",
"name": "processevent",
"signature": "def processevent(self, event)"
}
] | 2 | null | Implement the Python class `of_msg_count` described below.
Class description:
Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011
Method signatures and docstrings:
- def __init__(self, server, period=5): Initialize @param server yapc core @param period period before each printout
- d... | Implement the Python class `of_msg_count` described below.
Class description:
Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011
Method signatures and docstrings:
- def __init__(self, server, period=5): Initialize @param server yapc core @param period period before each printout
- d... | c3f5a31b74d5587671329eea9582ac8aed0c58a4 | <|skeleton|>
class of_msg_count:
"""Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011"""
def __init__(self, server, period=5):
"""Initialize @param server yapc core @param period period before each printout"""
<|body_0|>
def processevent(self, event):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class of_msg_count:
"""Component to count number of OpenFlow messages in a second @author ykk @date Feb 2011"""
def __init__(self, server, period=5):
"""Initialize @param server yapc core @param period period before each printout"""
self.server = server
server.register_event_handler(ofc... | the_stack_v2_python_sparse | yapc/debug/openflow.py | yapkke/yapc | train | 1 |
0962c1f97ef1813fc11eb073b84040343bf7c074 | [
"def generate(n):\n if n == 0:\n yield ''\n return\n for i in range(1, n + 1):\n for left in generate(i - 1):\n for right in generate(n - i):\n yield ('(' + left + ')' + right)\nreturn list(generate(n))",
"def generate(curr, opened, remaining):\n if remainin... | <|body_start_0|>
def generate(n):
if n == 0:
yield ''
return
for i in range(1, n + 1):
for left in generate(i - 1):
for right in generate(n - i):
yield ('(' + left + ')' + right)
return li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis_1(self, n: int) -> List[str]:
"""Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+1 nodes - '(' goes down - ')' goes back up Recursion would go like this: - choose the size of the... | stack_v2_sparse_classes_36k_train_025765 | 1,594 | no_license | [
{
"docstring": "Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+1 nodes - '(' goes down - ')' goes back up Recursion would go like this: - choose the size of the first tree - then recurse to the left and right 44ms, beats 49%",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_1(self, n: int) -> List[str]: Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_1(self, n: int) -> List[str]: Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def generateParenthesis_1(self, n: int) -> List[str]:
"""Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+1 nodes - '(' goes down - ')' goes back up Recursion would go like this: - choose the size of the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis_1(self, n: int) -> List[str]:
"""Link with Catalan numbers: 1, 2, 5, 14,.. C(n) = sum(i = 0 .. n-1) of C(i)(n-1-i) Equal to number of root n-ary tree with n+1 nodes - '(' goes down - ')' goes back up Recursion would go like this: - choose the size of the first tree - ... | the_stack_v2_python_sparse | backtrack/GenerateParenthesis.py | QuentinDuval/PythonExperiments | train | 3 | |
b0b65802c20b6b2af078cc73248fedccc8d45401 | [
"self.capacity = capacity\nself.d = {}\nself.r = []",
"if key in self.d:\n self.r.remove(key)\n self.r.append(key)\n return self.d[key]\nelse:\n return -1",
"if key in self.d:\n self.d[key] = value\n self.r.remove(key)\n self.r.append(key)\nelif len(self.r) < self.capacity:\n self.d[key]... | <|body_start_0|>
self.capacity = capacity
self.d = {}
self.r = []
<|end_body_0|>
<|body_start_1|>
if key in self.d:
self.r.remove(key)
self.r.append(key)
return self.d[key]
else:
return -1
<|end_body_1|>
<|body_start_2|>
i... | LRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_025766 | 1,281 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_012520 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 6578f288a757bf76213030b73ec3319a7baa2661 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.d = {}
self.r = []
def get(self, key):
""":type key: int :rtype: int"""
if key in self.d:
self.r.remove(key)
self.r.append(key)
... | the_stack_v2_python_sparse | python/LRU-Cache/hm+list.py | yutong-xie/Leetcode-Solution | train | 0 | |
bee0836d1a0e9050ff63b65281205a654027f71c | [
"lists = filter(lambda x: x is not None, lists)\nif not lists:\n return\nlength = len(lists)\nfactor = 2\nwhile length > 0:\n i = 0\n while True:\n try:\n lists[i] = self.mergeTwoLists(lists[i], lists[i + factor / 2])\n except IndexError:\n break\n i += factor\n ... | <|body_start_0|>
lists = filter(lambda x: x is not None, lists)
if not lists:
return
length = len(lists)
factor = 2
while length > 0:
i = 0
while True:
try:
lists[i] = self.mergeTwoLists(lists[i], lists[i + f... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists_TLE1(self, lists):
"""k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again... | stack_v2_sparse_classes_36k_train_025767 | 3,498 | permissive | [
{
"docstring": "k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again Complexity: T(N) = (k/2)*2N+(k/4)*4N..+(k/2^r)*2^r*N T(... | 4 | stack_v2_sparse_classes_30k_train_021309 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists_TLE1(self, lists): k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) A... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists_TLE1(self, lists): k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) A... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def mergeKLists_TLE1(self, lists):
"""k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists_TLE1(self, lists):
"""k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again Complexity: T... | the_stack_v2_python_sparse | 022 Merge k Sorted Lists.py | Aminaba123/LeetCode | train | 1 | |
1db022d829f737e2b2ca5b9016b724622981882e | [
"n = len(prices)\nif n <= 1:\n return 0\nif k >= n:\n return self.maxProfit_unlimited_transactions(prices)\ndp = [0 for i in range(k + 1)]\nm = [-prices[0] for i in range(k + 1)]\nfor i in range(1, n):\n for t in range(k, 0, -1):\n m[t] = max(m[t], dp[t - 1] - prices[i - 1])\n dp[t] = max(dp[... | <|body_start_0|>
n = len(prices)
if n <= 1:
return 0
if k >= n:
return self.maxProfit_unlimited_transactions(prices)
dp = [0 for i in range(k + 1)]
m = [-prices[0] for i in range(k + 1)]
for i in range(1, n):
for t in range(k, 0, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_unlimited_transactions(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit_TimeLimitedExceeded(self, k... | stack_v2_sparse_classes_36k_train_025768 | 1,905 | no_license | [
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, k, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_unlimited_transactions",
"signature": "def maxProfit_unlimited_transactions(se... | 3 | stack_v2_sparse_classes_30k_train_015193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit_unlimited_transactions(self, prices): :type prices: List[int] :rtype: int
- def m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit_unlimited_transactions(self, prices): :type prices: List[int] :rtype: int
- def m... | 88afef5388e308e6da5703b66e07324fb1723731 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_unlimited_transactions(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit_TimeLimitedExceeded(self, k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
n = len(prices)
if n <= 1:
return 0
if k >= n:
return self.maxProfit_unlimited_transactions(prices)
dp = [0 for i in range(k + 1)]
m = [-pric... | the_stack_v2_python_sparse | 188-best-time-to-buy-and-sell-stock-iv.py | tiaotiao/leetcode | train | 0 | |
aaa519df947752dc00da7b9fb879fec3a1177924 | [
"torch.set_num_threads(1)\ntorch.set_num_interop_threads(1)\nif isinstance(graphnet_modules, list):\n self._modules = graphnet_modules\nelse:\n self._modules = [graphnet_modules]\nself._gcd_file = gcd_file\nself._n_workers = n_workers",
"try:\n os.makedirs(output_folder)\nexcept FileExistsError:\n ass... | <|body_start_0|>
torch.set_num_threads(1)
torch.set_num_interop_threads(1)
if isinstance(graphnet_modules, list):
self._modules = graphnet_modules
else:
self._modules = [graphnet_modules]
self._gcd_file = gcd_file
self._n_workers = n_workers
<|end_... | Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules. | GraphNeTI3Deployer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initial... | stack_v2_sparse_classes_36k_train_025769 | 6,500 | permissive | [
{
"docstring": "Initialize the deployer. Will apply graphnet i3 modules to i3 files in the order in which they appear in graphnet_modules.Each module is run independently. Args: graphnet_modules: List of graphnet i3 modules. Order of appearence in the list determines order of deployment. gcd_file: path to gcd f... | 5 | null | Implement the Python class `GraphNeTI3Deployer` described below.
Class description:
Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules.
Method signatures and docstrings:
- def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Mo... | Implement the Python class `GraphNeTI3Deployer` described below.
Class description:
Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules.
Method signatures and docstrings:
- def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Mo... | f6e03282dd665c81d06eaa1ab55a07d138064e9a | <|skeleton|>
class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initialize the deplo... | the_stack_v2_python_sparse | src/graphnet/deployment/i3modules/deployer.py | graphnet-team/graphnet | train | 55 |
00fa062314283f0ec79082ce615e928df8af2eaf | [
"atomtypes = list(set([Zi for Zi, posi in atomlist]))\natomtypes.sort()\nC6 = np.array([AtomicData.Grimme_C6[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])\nC6 *= 17.34525539265301\nR0 = np.array([AtomicData.Grimme_R0[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])\nR0 /= AtomicData.bohr_to_angs\nself.C6... | <|body_start_0|>
atomtypes = list(set([Zi for Zi, posi in atomlist]))
atomtypes.sort()
C6 = np.array([AtomicData.Grimme_C6[AtomicData.atom_names[Zi - 1]] for Zi in atomtypes])
C6 *= 17.34525539265301
R0 = np.array([AtomicData.Grimme_R0[AtomicData.atom_names[Zi - 1]] for Zi in ato... | DispersionCorrection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and ca... | stack_v2_sparse_classes_36k_train_025770 | 4,341 | no_license | [
{
"docstring": "This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and cartesian coordinates in bohr for each atom",
"name": "__init... | 3 | null | Implement the Python class `DispersionCorrection` described below.
Class description:
Implement the DispersionCorrection class.
Method signatures and docstrings:
- def __init__(self, atomlist): This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in th... | Implement the Python class `DispersionCorrection` described below.
Class description:
Implement the DispersionCorrection class.
Method signatures and docstrings:
- def __init__(self, atomlist): This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in th... | 92cb73f1a6472f88588986561349d7f2ad1b1c15 | <|skeleton|>
class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DispersionCorrection:
def __init__(self, atomlist):
"""This function is called at the start of the program. It may initialize necessary parameters based on the atoms present in the molecule. Parameters: =========== atomlist: a list of tuples (Zi, [xi,yi,zi]) with the atomic number and cartesian coordi... | the_stack_v2_python_sparse | DFTB/Dispersion.py | by-student-2017/DFTBaby-0.1.0-31Jul2019 | train | 1 | |
16d2159a79e1bf886a49d7db52e067aa0a2b22f3 | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(UnitForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'",
"name = self.cleaned_data['name']\nquery = Unit.objects.filter(name=name, caffe=self._caffe)\nif self.instance.pk:\n query = query.exclude(pk=self.in... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(UnitForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
<|end_body_0|>
<|body_start_1|>
name = self.cleaned_data['name']
query = Unit.objects.filter(name=... | Responsible for setting up a Unit. | UnitForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitForm:
"""Responsible for setting up a Unit."""
def __init__(self, *args, **kwargs):
"""Initialize all Unit's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of save m... | stack_v2_sparse_classes_36k_train_025771 | 5,569 | permissive | [
{
"docstring": "Initialize all Unit's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe relatio... | 3 | stack_v2_sparse_classes_30k_train_021578 | Implement the Python class `UnitForm` described below.
Class description:
Responsible for setting up a Unit.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Unit's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, to add C... | Implement the Python class `UnitForm` described below.
Class description:
Responsible for setting up a Unit.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Unit's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, to add C... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class UnitForm:
"""Responsible for setting up a Unit."""
def __init__(self, *args, **kwargs):
"""Initialize all Unit's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of save m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitForm:
"""Responsible for setting up a Unit."""
def __init__(self, *args, **kwargs):
"""Initialize all Unit's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(UnitForm, self).__init__(*args, **kwargs)
self.fields['name'].l... | the_stack_v2_python_sparse | caffe/reports/forms.py | VirrageS/io-kawiarnie | train | 3 |
234dcbced4e9bfcb815491e6d2b4140022b37e72 | [
"driver = login_web\nself.home_page = HomePage(driver)\nself.home_page.appointment()\nself.appointment_page = AppointmentPage(driver)\n'step2:准备数据'\n'step3:操作步骤'\n'step4:断言结果'",
"driver = login_web\nself.home_page = HomePage(driver)\nself.home_page.appointment()\nself.appointment_page = AppointmentPage(driver)\n'... | <|body_start_0|>
driver = login_web
self.home_page = HomePage(driver)
self.home_page.appointment()
self.appointment_page = AppointmentPage(driver)
'step2:准备数据'
'step3:操作步骤'
'step4:断言结果'
<|end_body_0|>
<|body_start_1|>
driver = login_web
self.home_... | TestAppointment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAppointment:
def test_newAppointment(self, login_web):
"""step1:初始化页面"""
<|body_0|>
def test_lockingTime(self, login_web):
"""step1:初始化页面"""
<|body_1|>
def test_newAppointment(self, login_web):
"""step1:初始化页面"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_025772 | 1,887 | no_license | [
{
"docstring": "step1:初始化页面",
"name": "test_newAppointment",
"signature": "def test_newAppointment(self, login_web)"
},
{
"docstring": "step1:初始化页面",
"name": "test_lockingTime",
"signature": "def test_lockingTime(self, login_web)"
},
{
"docstring": "step1:初始化页面",
"name": "tes... | 3 | stack_v2_sparse_classes_30k_val_000289 | Implement the Python class `TestAppointment` described below.
Class description:
Implement the TestAppointment class.
Method signatures and docstrings:
- def test_newAppointment(self, login_web): step1:初始化页面
- def test_lockingTime(self, login_web): step1:初始化页面
- def test_newAppointment(self, login_web): step1:初始化页面 | Implement the Python class `TestAppointment` described below.
Class description:
Implement the TestAppointment class.
Method signatures and docstrings:
- def test_newAppointment(self, login_web): step1:初始化页面
- def test_lockingTime(self, login_web): step1:初始化页面
- def test_newAppointment(self, login_web): step1:初始化页面
... | aa961f23a3aff69b08e32dc09e90506bac40d49c | <|skeleton|>
class TestAppointment:
def test_newAppointment(self, login_web):
"""step1:初始化页面"""
<|body_0|>
def test_lockingTime(self, login_web):
"""step1:初始化页面"""
<|body_1|>
def test_newAppointment(self, login_web):
"""step1:初始化页面"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAppointment:
def test_newAppointment(self, login_web):
"""step1:初始化页面"""
driver = login_web
self.home_page = HomePage(driver)
self.home_page.appointment()
self.appointment_page = AppointmentPage(driver)
'step2:准备数据'
'step3:操作步骤'
'step4:断言结果'
... | the_stack_v2_python_sparse | testcases/test_appointment.py | czz728/SAAS | train | 0 | |
41bc663414b3604903fc261ebd7fc89efe55c5ae | [
"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... | Proto file describing the Custom Audience service. Service to manage custom audiences. | CustomAudienceServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomAudienceServiceServicer:
"""Proto file describing the Custom Audience service. Service to manage custom audiences."""
def GetCustomAudience(self, request, context):
"""Returns the requested custom audience in full detail."""
<|body_0|>
def MutateCustomAudiences(sel... | stack_v2_sparse_classes_36k_train_025773 | 5,641 | permissive | [
{
"docstring": "Returns the requested custom audience in full detail.",
"name": "GetCustomAudience",
"signature": "def GetCustomAudience(self, request, context)"
},
{
"docstring": "Creates or updates custom audiences. Operation statuses are returned.",
"name": "MutateCustomAudiences",
"s... | 2 | null | Implement the Python class `CustomAudienceServiceServicer` described below.
Class description:
Proto file describing the Custom Audience service. Service to manage custom audiences.
Method signatures and docstrings:
- def GetCustomAudience(self, request, context): Returns the requested custom audience in full detail.... | Implement the Python class `CustomAudienceServiceServicer` described below.
Class description:
Proto file describing the Custom Audience service. Service to manage custom audiences.
Method signatures and docstrings:
- def GetCustomAudience(self, request, context): Returns the requested custom audience in full detail.... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class CustomAudienceServiceServicer:
"""Proto file describing the Custom Audience service. Service to manage custom audiences."""
def GetCustomAudience(self, request, context):
"""Returns the requested custom audience in full detail."""
<|body_0|>
def MutateCustomAudiences(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomAudienceServiceServicer:
"""Proto file describing the Custom Audience service. Service to manage custom audiences."""
def GetCustomAudience(self, request, context):
"""Returns the requested custom audience in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
co... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/custom_audience_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
5d2952fdb3e3a244e6f74a4d211a9caf0d835208 | [
"super(FactorizedReduce, self).__init__()\nif desc.channel_out % 2 != 0:\n raise Exception('channel_out must be divided by 2.')\nself.affine = desc.get('affine', True)\nself.desc = desc",
"desc = self.desc\nx = tf.nn.relu(x)\nx2 = tf.identity(x[:, :, 1:, 1:] if desc.data_format == 'channels_first' else x[:, 1:... | <|body_start_0|>
super(FactorizedReduce, self).__init__()
if desc.channel_out % 2 != 0:
raise Exception('channel_out must be divided by 2.')
self.affine = desc.get('affine', True)
self.desc = desc
<|end_body_0|>
<|body_start_1|>
desc = self.desc
x = tf.nn.rel... | Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config | FactorizedReduce | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
<|body_0|>
def __call__(self, x, training):
"""Forward function of FactorizedReduc... | stack_v2_sparse_classes_36k_train_025774 | 7,938 | permissive | [
{
"docstring": "Init FactorizedReduce.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward function of FactorizedReduce.",
"name": "__call__",
"signature": "def __call__(self, x, training)"
}
] | 2 | null | Implement the Python class `FactorizedReduce` described below.
Class description:
Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init FactorizedReduce.
- def __call__(self, x, training): Forward functi... | Implement the Python class `FactorizedReduce` described below.
Class description:
Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init FactorizedReduce.
- def __call__(self, x, training): Forward functi... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
<|body_0|>
def __call__(self, x, training):
"""Forward function of FactorizedReduc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
super(FactorizedReduce, self).__init__()
if desc.channel_out % 2 != 0:
raise Exception('... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/tensorflow/blocks/operations.py | Huawei-Ascend/modelzoo | train | 1 |
30f5da1e8c105f688997e87cb4a598a63ef4cf17 | [
"self.countTable = ChainingHashMap(1000)\nself.totalTable = ChainingHashMap(1000)\nself.totalWords = 0",
"textList = text.split()\nfor i in range(len(textList) - 1):\n self.totalWords += 1\n if self.totalTable[textList[i]] == None:\n self.totalTable[textList[i]] = 1\n else:\n self.totalTabl... | <|body_start_0|>
self.countTable = ChainingHashMap(1000)
self.totalTable = ChainingHashMap(1000)
self.totalWords = 0
<|end_body_0|>
<|body_start_1|>
textList = text.split()
for i in range(len(textList) - 1):
self.totalWords += 1
if self.totalTable[textLis... | A class that allows one to generate random text in the style of some provided source text | TextGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextGenerator:
"""A class that allows one to generate random text in the style of some provided source text"""
def __init__(self):
"""Initializes the text generator"""
<|body_0|>
def train(self, text):
"""Takes a body of text (as a string) and increases the appro... | stack_v2_sparse_classes_36k_train_025775 | 6,228 | no_license | [
{
"docstring": "Initializes the text generator",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Takes a body of text (as a string) and increases the appropriate frequency counts",
"name": "train",
"signature": "def train(self, text)"
},
{
"docstring": "C... | 4 | stack_v2_sparse_classes_30k_train_012300 | Implement the Python class `TextGenerator` described below.
Class description:
A class that allows one to generate random text in the style of some provided source text
Method signatures and docstrings:
- def __init__(self): Initializes the text generator
- def train(self, text): Takes a body of text (as a string) an... | Implement the Python class `TextGenerator` described below.
Class description:
A class that allows one to generate random text in the style of some provided source text
Method signatures and docstrings:
- def __init__(self): Initializes the text generator
- def train(self, text): Takes a body of text (as a string) an... | 0290deb3e1f008305fb2da353eda86210a7ba1e6 | <|skeleton|>
class TextGenerator:
"""A class that allows one to generate random text in the style of some provided source text"""
def __init__(self):
"""Initializes the text generator"""
<|body_0|>
def train(self, text):
"""Takes a body of text (as a string) and increases the appro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextGenerator:
"""A class that allows one to generate random text in the style of some provided source text"""
def __init__(self):
"""Initializes the text generator"""
self.countTable = ChainingHashMap(1000)
self.totalTable = ChainingHashMap(1000)
self.totalWords = 0
... | the_stack_v2_python_sparse | Random Text Generation/textgenerator.py | mbastola/Algorithms-Data-Structures-in-Python | train | 0 |
66b03afe0b6d2e1167e37aaa452c632a3a1c278b | [
"bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg(self.args[0], bucket_fields=['website'])\nif bucket_url.scheme == 's3':\n sys.stdout.write(self.gsutil_api.XmlPassThroughGetWebsite(bucket_url, provider=bucket_url.scheme))\nelif bucket_metadata.website and (bucket_metadata.website.mainPageSuffix or b... | <|body_start_0|>
bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg(self.args[0], bucket_fields=['website'])
if bucket_url.scheme == 's3':
sys.stdout.write(self.gsutil_api.XmlPassThroughGetWebsite(bucket_url, provider=bucket_url.scheme))
elif bucket_metadata.website and (bu... | Implementation of gsutil web command. | WebCommand | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebCommand:
"""Implementation of gsutil web command."""
def _GetWeb(self):
"""Gets website configuration for a bucket."""
<|body_0|>
def _SetWeb(self):
"""Sets website configuration for a bucket."""
<|body_1|>
def RunCommand(self):
"""Command... | stack_v2_sparse_classes_36k_train_025776 | 8,979 | permissive | [
{
"docstring": "Gets website configuration for a bucket.",
"name": "_GetWeb",
"signature": "def _GetWeb(self)"
},
{
"docstring": "Sets website configuration for a bucket.",
"name": "_SetWeb",
"signature": "def _SetWeb(self)"
},
{
"docstring": "Command entry point for the web comm... | 3 | null | Implement the Python class `WebCommand` described below.
Class description:
Implementation of gsutil web command.
Method signatures and docstrings:
- def _GetWeb(self): Gets website configuration for a bucket.
- def _SetWeb(self): Sets website configuration for a bucket.
- def RunCommand(self): Command entry point fo... | Implement the Python class `WebCommand` described below.
Class description:
Implementation of gsutil web command.
Method signatures and docstrings:
- def _GetWeb(self): Gets website configuration for a bucket.
- def _SetWeb(self): Sets website configuration for a bucket.
- def RunCommand(self): Command entry point fo... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class WebCommand:
"""Implementation of gsutil web command."""
def _GetWeb(self):
"""Gets website configuration for a bucket."""
<|body_0|>
def _SetWeb(self):
"""Sets website configuration for a bucket."""
<|body_1|>
def RunCommand(self):
"""Command... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebCommand:
"""Implementation of gsutil web command."""
def _GetWeb(self):
"""Gets website configuration for a bucket."""
bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg(self.args[0], bucket_fields=['website'])
if bucket_url.scheme == 's3':
sys.stdout.writ... | the_stack_v2_python_sparse | third_party/gsutil/gslib/commands/web.py | catapult-project/catapult | train | 2,032 |
7ab7f18474229eaef8e4e13cc2437ef5a48fc7e5 | [
"self.non_zero_dict = {}\nfor i, num in enumerate(nums):\n if num != 0:\n self.non_zero_dict[i] = num",
"result = 0\nfor key, val in self.non_zero_dict.items():\n if vec.non_zero_dict.get(key, 0):\n result += val * vec.non_zero_dict.get(key, 0)\nreturn result"
] | <|body_start_0|>
self.non_zero_dict = {}
for i, num in enumerate(nums):
if num != 0:
self.non_zero_dict[i] = num
<|end_body_0|>
<|body_start_1|>
result = 0
for key, val in self.non_zero_dict.items():
if vec.non_zero_dict.get(key, 0):
... | SparseVector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.non_zero_dict = {}
for i, num in enumerat... | stack_v2_sparse_classes_36k_train_025777 | 1,831 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type vec: 'SparseVector' :rtype: int",
"name": "dotProduct",
"signature": "def dotProduct(self, vec)"
}
] | 2 | null | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int
<|skeleton|>
class SparseVector:
def __init__(sel... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
self.non_zero_dict = {}
for i, num in enumerate(nums):
if num != 0:
self.non_zero_dict[i] = num
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
re... | the_stack_v2_python_sparse | 1570-dot_product_of_two_sparse_vectors.py | stevestar888/leetcode-problems | train | 2 | |
826fa9d0f6dc621ed82389b83440ffcf90a485c7 | [
"tf.logging.info('Create InitVariablesHook.')\nself._checkpoint_dir = checkpoint_dir\nself._global_var_initop = tf.global_variables_initializer()",
"checkpoint_path = saver_lib.latest_checkpoint(self._checkpoint_dir)\nif not checkpoint_path:\n tf.logging.info('InitVariablesHook (after_create_sess): initializin... | <|body_start_0|>
tf.logging.info('Create InitVariablesHook.')
self._checkpoint_dir = checkpoint_dir
self._global_var_initop = tf.global_variables_initializer()
<|end_body_0|>
<|body_start_1|>
checkpoint_path = saver_lib.latest_checkpoint(self._checkpoint_dir)
if not checkpoint_p... | Define the hook to initialize all global variables. | InitVariablesHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitVariablesHook:
"""Define the hook to initialize all global variables."""
def __init__(self, checkpoint_dir):
"""Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to."""
<|body_0|>
def after_create_session(self, sess... | stack_v2_sparse_classes_36k_train_025778 | 12,247 | permissive | [
{
"docstring": "Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to.",
"name": "__init__",
"signature": "def __init__(self, checkpoint_dir)"
},
{
"docstring": "Initializes all global variables after session is created. Args: session: A TensorF... | 2 | stack_v2_sparse_classes_30k_train_005652 | Implement the Python class `InitVariablesHook` described below.
Class description:
Define the hook to initialize all global variables.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir): Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to.
- def... | Implement the Python class `InitVariablesHook` described below.
Class description:
Define the hook to initialize all global variables.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir): Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to.
- def... | 01155c740705f1641ebf3134829cea0e212f2d28 | <|skeleton|>
class InitVariablesHook:
"""Define the hook to initialize all global variables."""
def __init__(self, checkpoint_dir):
"""Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to."""
<|body_0|>
def after_create_session(self, sess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitVariablesHook:
"""Define the hook to initialize all global variables."""
def __init__(self, checkpoint_dir):
"""Initializes the hook. Args: checkpoint_dir: A string, the name of the directory that checkpoints save to."""
tf.logging.info('Create InitVariablesHook.')
self._check... | the_stack_v2_python_sparse | njunmt/training/hooks.py | zhaocq-nlp/NJUNMT-tf | train | 114 |
8126a329e0e429b4df93e720052b5c970961c734 | [
"super().__init__(parent)\nself['show'] = 'headings'\nself['columns'] = [column['name'] for column in columns]\nfor column in columns:\n self.heading(column['name'], text=column['title'])\n self.column(column['name'], anchor=column['anchor'])\ntry:\n getattr(self, 'columns')\nexcept AttributeError:\n pa... | <|body_start_0|>
super().__init__(parent)
self['show'] = 'headings'
self['columns'] = [column['name'] for column in columns]
for column in columns:
self.heading(column['name'], text=column['title'])
self.column(column['name'], anchor=column['anchor'])
try:... | CustomTreeview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
<|body_0|>
def insert(self, parent, index, tags=None, **kwargs):
"""Call super() insert wi... | stack_v2_sparse_classes_36k_train_025779 | 9,918 | no_license | [
{
"docstring": "Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts",
"name": "__init__",
"signature": "def __init__(self, parent, columns)"
},
{
"docstring": "Call super() insert with convenient value specifications.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_019534 | Implement the Python class `CustomTreeview` described below.
Class description:
Implement the CustomTreeview class.
Method signatures and docstrings:
- def __init__(self, parent, columns): Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts
- def inser... | Implement the Python class `CustomTreeview` described below.
Class description:
Implement the CustomTreeview class.
Method signatures and docstrings:
- def __init__(self, parent, columns): Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts
- def inser... | 3ba9965a6d164d3fa1704015176394e26f0c3560 | <|skeleton|>
class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
<|body_0|>
def insert(self, parent, index, tags=None, **kwargs):
"""Call super() insert wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomTreeview:
def __init__(self, parent, columns):
"""Initialize CustomTreeview widget. parent -- the parent widget (as usual) columns -- a list of column descriptor dicts"""
super().__init__(parent)
self['show'] = 'headings'
self['columns'] = [column['name'] for column in co... | the_stack_v2_python_sparse | autograde/aggui.py | AndrewMHenry/capstone-ag | train | 0 | |
52bc3c47e3fff52e03365ba92b53c315dacffa69 | [
"remediation_entry = json.loads(payload)\nnotification_info = remediation_entry.get('notificationInfo', None)\nfinding_info = notification_info.get('FindingInfo', None)\nobject_id = finding_info.get('ObjectId', None)\nobject_chain = remediation_entry['notificationInfo']['FindingInfo']['ObjectChain']\nobject_chain_d... | <|body_start_0|>
remediation_entry = json.loads(payload)
notification_info = remediation_entry.get('notificationInfo', None)
finding_info = notification_info.get('FindingInfo', None)
object_id = finding_info.get('ObjectId', None)
object_chain = remediation_entry['notificationInfo... | RestrictUdpAccessFromInternet | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestrictUdpAccessFromInternet:
def parse(self, payload):
"""Parse payload received from Remediation Service. :param payload: JSON string containing parameters received from the remediation service. :type payload: str. :returns: Dictionary of parsed parameters :rtype: dict :raises: KeyErr... | stack_v2_sparse_classes_36k_train_025780 | 5,378 | permissive | [
{
"docstring": "Parse payload received from Remediation Service. :param payload: JSON string containing parameters received from the remediation service. :type payload: str. :returns: Dictionary of parsed parameters :rtype: dict :raises: KeyError, JSONDecodeError",
"name": "parse",
"signature": "def par... | 3 | stack_v2_sparse_classes_30k_val_000854 | Implement the Python class `RestrictUdpAccessFromInternet` described below.
Class description:
Implement the RestrictUdpAccessFromInternet class.
Method signatures and docstrings:
- def parse(self, payload): Parse payload received from Remediation Service. :param payload: JSON string containing parameters received fr... | Implement the Python class `RestrictUdpAccessFromInternet` described below.
Class description:
Implement the RestrictUdpAccessFromInternet class.
Method signatures and docstrings:
- def parse(self, payload): Parse payload received from Remediation Service. :param payload: JSON string containing parameters received fr... | c958afcca4cc25273e2c99526a46225a1a716aed | <|skeleton|>
class RestrictUdpAccessFromInternet:
def parse(self, payload):
"""Parse payload received from Remediation Service. :param payload: JSON string containing parameters received from the remediation service. :type payload: str. :returns: Dictionary of parsed parameters :rtype: dict :raises: KeyErr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestrictUdpAccessFromInternet:
def parse(self, payload):
"""Parse payload received from Remediation Service. :param payload: JSON string containing parameters received from the remediation service. :type payload: str. :returns: Dictionary of parsed parameters :rtype: dict :raises: KeyError, JSONDecode... | the_stack_v2_python_sparse | remediation_worker/jobs/azure_security_udp_access_restricted_from_internet/azure_security_udp_access_restricted_from_internet.py | holgerfeix/secure-state-remediation-jobs | train | 0 | |
5dafc3b18b421aa952d6172ee198606eed42905d | [
"super().__init__()\nself.piece_num = piece_num\nif self.piece_num != None:\n self.mask_embedding = nn.Embedding(piece_num + 1, piece_num)\n self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros(piece_num), np.identity(piece_num)], axis=0)))\n self.mask_embedding.weight.requires_... | <|body_start_0|>
super().__init__()
self.piece_num = piece_num
if self.piece_num != None:
self.mask_embedding = nn.Embedding(piece_num + 1, piece_num)
self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros(piece_num), np.identity(piece_num)], axi... | Piecewise AveragePooling | PieceAvgPool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PieceAvgPool:
"""Piecewise AveragePooling"""
def __init__(self, kernel_size, piece_num=None):
"""Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: input features: (B, ... | stack_v2_sparse_classes_36k_train_025781 | 1,905 | permissive | [
{
"docstring": "Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool",
"name": "__init__",
"signature": "def __init__(self, kernel_size, piece_num=None)"
},
{
"docstring": "Args: input features: (B, I_EMBED, L) Return: output features: (B, H_EMBED)",
"nam... | 2 | stack_v2_sparse_classes_30k_train_009918 | Implement the Python class `PieceAvgPool` described below.
Class description:
Piecewise AveragePooling
Method signatures and docstrings:
- def __init__(self, kernel_size, piece_num=None): Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool
- def forward(self, x, mask=None): Args:... | Implement the Python class `PieceAvgPool` described below.
Class description:
Piecewise AveragePooling
Method signatures and docstrings:
- def __init__(self, kernel_size, piece_num=None): Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool
- def forward(self, x, mask=None): Args:... | b4c049fd30db39b67984edfadc49b4354d52be83 | <|skeleton|>
class PieceAvgPool:
"""Piecewise AveragePooling"""
def __init__(self, kernel_size, piece_num=None):
"""Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: input features: (B, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PieceAvgPool:
"""Piecewise AveragePooling"""
def __init__(self, kernel_size, piece_num=None):
"""Args: kernel_size: kernel_size for CNN piece_num: piece_num of PCNN, None for common pool"""
super().__init__()
self.piece_num = piece_num
if self.piece_num != None:
... | the_stack_v2_python_sparse | pasaie/module/pool/avg_pool.py | tracy-talent/AIPolicy | train | 0 |
0d45420f9fe08f495301927c0b660680c93873ef | [
"if iso in cls._formats:\n return (iso,) + tuple(cls._formats[iso].split(str_))\nall = {}\nopt_iso = ''\nmax_l = 0\nfor key in cls._formats.iterkeys():\n i, p, c = cls.split(str_, key)\n l = len(p)\n if l > max_l:\n max_l = l\n opt_iso = i\n if l in all:\n all[l].append((i, p, c)... | <|body_start_0|>
if iso in cls._formats:
return (iso,) + tuple(cls._formats[iso].split(str_))
all = {}
opt_iso = ''
max_l = 0
for key in cls._formats.iterkeys():
i, p, c = cls.split(str_, key)
l = len(p)
if l > max_l:
... | The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter. | PostalCode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostalCode:
"""The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter."""
def split(cls, str_, iso=''):
... | stack_v2_sparse_classes_36k_train_025782 | 8,410 | no_license | [
{
"docstring": "Split string <str_> in (postalcode, remainder) following the specs of country <iso>. Returns iso, postal code and the remaining part of <str_>. When iso is filled but postal code remains empty, no postal code could be found according to the rules of iso. When iso is empty but postal code is not,... | 2 | null | Implement the Python class `PostalCode` described below.
Class description:
The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter.
... | Implement the Python class `PostalCode` described below.
Class description:
The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter.
... | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | <|skeleton|>
class PostalCode:
"""The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter."""
def split(cls, str_, iso=''):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostalCode:
"""The PostalCode class is a wrapper around PostCodeFormat and an internal database of postalcode formats. It provides the class methods split() and get(), both of which must be called with the two character iso country code as first parameter."""
def split(cls, str_, iso=''):
"""Spli... | the_stack_v2_python_sparse | extra-addons/account_banking/sepa/postalcode.py | sgeerish/sirr_production | train | 0 |
d4debfa56e0886cd9149ac9660403776113a9204 | [
"try:\n regexes = await self.nyuki.storage.regexes.get()\nexcept AutoReconnect:\n return Response(status=503)\nreturn Response(regexes)",
"request = await request.json()\ntry:\n regex = new_regex(request['title'], request['pattern'])\nexcept KeyError as exc:\n return Response(status=400, body={'error'... | <|body_start_0|>
try:
regexes = await self.nyuki.storage.regexes.get()
except AutoReconnect:
return Response(status=503)
return Response(regexes)
<|end_body_0|>
<|body_start_1|>
request = await request.json()
try:
regex = new_regex(request['ti... | ApiFactoryRegexes | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"LicenseRef-scancode-warran... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiFactoryRegexes:
async def get(self, request):
"""Return the list of all regexes"""
<|body_0|>
async def put(self, request):
"""Insert a new regex"""
<|body_1|>
async def delete(self, request):
"""Delete all regexes and return the list"""
... | stack_v2_sparse_classes_36k_train_025783 | 10,772 | permissive | [
{
"docstring": "Return the list of all regexes",
"name": "get",
"signature": "async def get(self, request)"
},
{
"docstring": "Insert a new regex",
"name": "put",
"signature": "async def put(self, request)"
},
{
"docstring": "Delete all regexes and return the list",
"name": "... | 3 | null | Implement the Python class `ApiFactoryRegexes` described below.
Class description:
Implement the ApiFactoryRegexes class.
Method signatures and docstrings:
- async def get(self, request): Return the list of all regexes
- async def put(self, request): Insert a new regex
- async def delete(self, request): Delete all re... | Implement the Python class `ApiFactoryRegexes` described below.
Class description:
Implement the ApiFactoryRegexes class.
Method signatures and docstrings:
- async def get(self, request): Return the list of all regexes
- async def put(self, request): Insert a new regex
- async def delete(self, request): Delete all re... | f185fababee380660930243515652093855acfe7 | <|skeleton|>
class ApiFactoryRegexes:
async def get(self, request):
"""Return the list of all regexes"""
<|body_0|>
async def put(self, request):
"""Insert a new regex"""
<|body_1|>
async def delete(self, request):
"""Delete all regexes and return the list"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiFactoryRegexes:
async def get(self, request):
"""Return the list of all regexes"""
try:
regexes = await self.nyuki.storage.regexes.get()
except AutoReconnect:
return Response(status=503)
return Response(regexes)
async def put(self, request):
... | the_stack_v2_python_sparse | nyuki/workflow/api/factory.py | d-nery/nyuki | train | 0 | |
6440e43eeb24e41f882ccb95d12ebfb8d7b5b3b5 | [
"proj = pk and self.get_object(request.user, pk) or None\ncontext = {'project': proj, 'forms': self.formset(instance=proj)}\nreturn render(request, self.edit_template, context)",
"proj = pk and self.get_object(request.user, pk) or None\ncontext = {'project': proj}\nfs = self.formset(request.POST, instance=proj)\n... | <|body_start_0|>
proj = pk and self.get_object(request.user, pk) or None
context = {'project': proj, 'forms': self.formset(instance=proj)}
return render(request, self.edit_template, context)
<|end_body_0|>
<|body_start_1|>
proj = pk and self.get_object(request.user, pk) or None
... | Experimental WBS edit view. | ProjectWBSView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectWBSView:
"""Experimental WBS edit view."""
def show_forms(self, request, pk):
"""Render the formset for the given project."""
<|body_0|>
def upsert_instance(self, request, pk, **kwargs):
"""Save the main form (and subform is the instance is not new) and re... | stack_v2_sparse_classes_36k_train_025784 | 4,052 | no_license | [
{
"docstring": "Render the formset for the given project.",
"name": "show_forms",
"signature": "def show_forms(self, request, pk)"
},
{
"docstring": "Save the main form (and subform is the instance is not new) and redirect to the collection view.",
"name": "upsert_instance",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_007892 | Implement the Python class `ProjectWBSView` described below.
Class description:
Experimental WBS edit view.
Method signatures and docstrings:
- def show_forms(self, request, pk): Render the formset for the given project.
- def upsert_instance(self, request, pk, **kwargs): Save the main form (and subform is the instan... | Implement the Python class `ProjectWBSView` described below.
Class description:
Experimental WBS edit view.
Method signatures and docstrings:
- def show_forms(self, request, pk): Render the formset for the given project.
- def upsert_instance(self, request, pk, **kwargs): Save the main form (and subform is the instan... | 4dcf0e6a37e8753ae9d69d663c0c280fcca0a26c | <|skeleton|>
class ProjectWBSView:
"""Experimental WBS edit view."""
def show_forms(self, request, pk):
"""Render the formset for the given project."""
<|body_0|>
def upsert_instance(self, request, pk, **kwargs):
"""Save the main form (and subform is the instance is not new) and re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectWBSView:
"""Experimental WBS edit view."""
def show_forms(self, request, pk):
"""Render the formset for the given project."""
proj = pk and self.get_object(request.user, pk) or None
context = {'project': proj, 'forms': self.formset(instance=proj)}
return render(requ... | the_stack_v2_python_sparse | apps/work/views.py | ESCL/pjtracker | train | 1 |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = AsignacionCliente.objects.filter(id=kwargs['id']).first()\nform = AsignacionClienteForm(instance=asearch)\nlist_assignC = None\nif query:\n list_assignC = AsignacionCliente.objects.filter(Q(server__name__icontains=query) | Q(client_... | <|body_start_0|>
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = AsignacionCliente.objects.filter(id=kwargs['id']).first()
form = AsignacionClienteForm(instance=asearch)
list_assignC = None
if query:
list_assignC = AsignacionClien... | Clase para editar las asignaciones de los clientes | AssignClientEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignClientEditView:
"""Clase para editar las asignaciones de los clientes"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_025785 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003892 | Implement the Python class `AssignClientEditView` described below.
Class description:
Clase para editar las asignaciones de los clientes
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `AssignClientEditView` described below.
Class description:
Clase para editar las asignaciones de los clientes
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class AssignClientEditV... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class AssignClientEditView:
"""Clase para editar las asignaciones de los clientes"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssignClientEditView:
"""Clase para editar las asignaciones de los clientes"""
def get(self, request, *args, **kwargs):
"""Método get"""
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = AsignacionCliente.objects.filter(id=kwargs['id']).first()
... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
1151650be6e24ccde1faed55433809427ce2bc60 | [
"super().__init__()\nself.embed_dim = embed_dim\nself.k_embed_size = kdim if kdim else embed_dim\nself.v_embed_size = vdim if vdim else embed_dim\nself.num_heads = num_attn_heads\nself.attention_dropout = dropout\nself.head_embed_size = embed_dim // num_attn_heads\nself.head_scaling = math.sqrt(self.head_embed_size... | <|body_start_0|>
super().__init__()
self.embed_dim = embed_dim
self.k_embed_size = kdim if kdim else embed_dim
self.v_embed_size = vdim if vdim else embed_dim
self.num_heads = num_attn_heads
self.attention_dropout = dropout
self.head_embed_size = embed_dim // num_... | Multi-Head Attention | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multi-Head Attention"""
def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_attention=False):
"""___QUESTION-7-MULTIHEAD-ATTENTION-NOTE You shouldn't need to change the __init__ of this class fo... | stack_v2_sparse_classes_36k_train_025786 | 28,210 | no_license | [
{
"docstring": "___QUESTION-7-MULTIHEAD-ATTENTION-NOTE You shouldn't need to change the __init__ of this class for your attention implementation",
"name": "__init__",
"signature": "def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_atte... | 2 | stack_v2_sparse_classes_30k_train_001113 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-Head Attention
Method signatures and docstrings:
- def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_attention=False): ___QUESTION-7-MULTIHEAD-ATTENTION-NOTE Y... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-Head Attention
Method signatures and docstrings:
- def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_attention=False): ___QUESTION-7-MULTIHEAD-ATTENTION-NOTE Y... | 7f109bcf3cc17d2c669e18fb2ad3357aa4e0fc2e | <|skeleton|>
class MultiHeadAttention:
"""Multi-Head Attention"""
def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_attention=False):
"""___QUESTION-7-MULTIHEAD-ATTENTION-NOTE You shouldn't need to change the __init__ of this class fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Multi-Head Attention"""
def __init__(self, embed_dim, num_attn_heads, kdim=None, vdim=None, dropout=0.0, self_attention=False, encoder_decoder_attention=False):
"""___QUESTION-7-MULTIHEAD-ATTENTION-NOTE You shouldn't need to change the __init__ of this class for your attent... | the_stack_v2_python_sparse | NLG/table/modules/Transformer.py | Lyz1213/msc_dissertation | train | 2 |
fda012309a0db17998c7739733f7afee064c0767 | [
"updated = 0\nnow = datetime.datetime.now()\nfor t in queryset:\n t.last_run = now - datetime.timedelta(seconds=t.run_every)\n t.save()\n updated += 1\nif updated == 1:\n message = '1 task has been rescheduled'\nelse:\n message = '%d tasks have been rescheduled' % updated\nself.message_user(request, ... | <|body_start_0|>
updated = 0
now = datetime.datetime.now()
for t in queryset:
t.last_run = now - datetime.timedelta(seconds=t.run_every)
t.save()
updated += 1
if updated == 1:
message = '1 task has been rescheduled'
else:
... | Schedule admin | ScheduleAdmin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleAdmin:
"""Schedule admin"""
def run_now(self, request, queryset):
"""Reschedule selected tasks"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Handle timeout"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
updated = 0
... | stack_v2_sparse_classes_36k_train_025787 | 2,711 | permissive | [
{
"docstring": "Reschedule selected tasks",
"name": "run_now",
"signature": "def run_now(self, request, queryset)"
},
{
"docstring": "Handle timeout",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008028 | Implement the Python class `ScheduleAdmin` described below.
Class description:
Schedule admin
Method signatures and docstrings:
- def run_now(self, request, queryset): Reschedule selected tasks
- def save_model(self, request, obj, form, change): Handle timeout | Implement the Python class `ScheduleAdmin` described below.
Class description:
Schedule admin
Method signatures and docstrings:
- def run_now(self, request, queryset): Reschedule selected tasks
- def save_model(self, request, obj, form, change): Handle timeout
<|skeleton|>
class ScheduleAdmin:
"""Schedule admin"... | d43c14f02266b5a4e1fca2db3296cef612d63374 | <|skeleton|>
class ScheduleAdmin:
"""Schedule admin"""
def run_now(self, request, queryset):
"""Reschedule selected tasks"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Handle timeout"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleAdmin:
"""Schedule admin"""
def run_now(self, request, queryset):
"""Reschedule selected tasks"""
updated = 0
now = datetime.datetime.now()
for t in queryset:
t.last_run = now - datetime.timedelta(seconds=t.run_every)
t.save()
up... | the_stack_v2_python_sparse | services/web/apps/main/schedule/views.py | fantmas2/noc | train | 0 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.hid_dim = hid_dim\nself.seq_cont_dim = seq_cont_dim\nself.non_seq_cont_dim = non_seq_cont_dim\nself.emb_seq_num_classes = emb_seq_num_classes\nself.emb_non_seq_num_classes = emb_non_seq_num_classes\nself.has_non_seq = len(self.emb_non_seq_num_classes) > 0 or self.non_seq_cont_dim\nself.lin... | <|body_start_0|>
super().__init__()
self.hid_dim = hid_dim
self.seq_cont_dim = seq_cont_dim
self.non_seq_cont_dim = non_seq_cont_dim
self.emb_seq_num_classes = emb_seq_num_classes
self.emb_non_seq_num_classes = emb_non_seq_num_classes
self.has_non_seq = len(self.e... | OutputLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputLayer:
def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes):
"""Initialize model with params."""
<|body_0|>
def forward(self, decoder_output):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_36k_train_025788 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_013238 | Implement the Python class `OutputLayer` described below.
Class description:
Implement the OutputLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes): Initialize model with params.
- def forward(self, decoder_output)... | Implement the Python class `OutputLayer` described below.
Class description:
Implement the OutputLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes): Initialize model with params.
- def forward(self, decoder_output)... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class OutputLayer:
def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes):
"""Initialize model with params."""
<|body_0|>
def forward(self, decoder_output):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputLayer:
def __init__(self, hid_dim, seq_cont_dim, non_seq_cont_dim, emb_seq_num_classes, emb_non_seq_num_classes):
"""Initialize model with params."""
super().__init__()
self.hid_dim = hid_dim
self.seq_cont_dim = seq_cont_dim
self.non_seq_cont_dim = non_seq_cont_di... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 | |
3d3d45405a158553142f0fafaeff3e78b3dae552 | [
"Service.__init__(self, upstream_get, conf=conf)\nself.httpc = requests.request\nself.httpc_params = {}",
"if not method:\n method = self.http_method\nentity_id = request_args.get('entity_id')\nif not entity_id:\n raise AttributeError('Missing entity_id')\nif tenant:\n _url = construct_tenant_well_known_... | <|body_start_0|>
Service.__init__(self, upstream_get, conf=conf)
self.httpc = requests.request
self.httpc_params = {}
<|end_body_0|>
<|body_start_1|>
if not method:
method = self.http_method
entity_id = request_args.get('entity_id')
if not entity_id:
... | EntityConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityConfiguration:
def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None):
"""The service that talks to the OIDC federation well-known endpoint."""
<|body_0|>
def get_request_parameters(self, request_args=None, method='', request_body_t... | stack_v2_sparse_classes_36k_train_025789 | 2,904 | permissive | [
{
"docstring": "The service that talks to the OIDC federation well-known endpoint.",
"name": "__init__",
"signature": "def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None)"
},
{
"docstring": "Builds the request message and constructs the HTTP headers. This ... | 2 | stack_v2_sparse_classes_30k_test_000782 | Implement the Python class `EntityConfiguration` described below.
Class description:
Implement the EntityConfiguration class.
Method signatures and docstrings:
- def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None): The service that talks to the OIDC federation well-known endpoi... | Implement the Python class `EntityConfiguration` described below.
Class description:
Implement the EntityConfiguration class.
Method signatures and docstrings:
- def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None): The service that talks to the OIDC federation well-known endpoi... | 815d62a4f7fd22bec70935e121a1a621647c32ae | <|skeleton|>
class EntityConfiguration:
def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None):
"""The service that talks to the OIDC federation well-known endpoint."""
<|body_0|>
def get_request_parameters(self, request_args=None, method='', request_body_t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityConfiguration:
def __init__(self, upstream_get: Callable, conf: Optional[Union[dict, Configuration]]=None):
"""The service that talks to the OIDC federation well-known endpoint."""
Service.__init__(self, upstream_get, conf=conf)
self.httpc = requests.request
self.httpc_pa... | the_stack_v2_python_sparse | src/fedservice/entity/client/entity_configuration.py | rohe/fedservice | train | 4 | |
f0795cf6d7be8e484e0ff4136b646b68c4ed6a1d | [
"self._hardware = hardware\nself._state = state\nself._resources = resources",
"labware_id = labware_id if labware_id else self._resources.id_generator.generate_id()\ntry:\n definition = self._state.labware.get_definition_by_uri(uri_from_details(load_name=load_name, namespace=namespace, version=version))\nexce... | <|body_start_0|>
self._hardware = hardware
self._state = state
self._resources = resources
<|end_body_0|>
<|body_start_1|>
labware_id = labware_id if labware_id else self._resources.id_generator.generate_id()
try:
definition = self._state.labware.get_definition_by_ur... | Implementation logic for labware, pipette, and module loading. | EquipmentHandler | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentHandler:
"""Implementation logic for labware, pipette, and module loading."""
def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None:
"""Initialize an EquipmentHandler instance."""
<|body_0|>
async def load_labware(self... | stack_v2_sparse_classes_36k_train_025790 | 4,518 | permissive | [
{
"docstring": "Initialize an EquipmentHandler instance.",
"name": "__init__",
"signature": "def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None"
},
{
"docstring": "Load labware by assigning an identifier and pulling required data. Args: load_name: T... | 3 | null | Implement the Python class `EquipmentHandler` described below.
Class description:
Implementation logic for labware, pipette, and module loading.
Method signatures and docstrings:
- def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None: Initialize an EquipmentHandler instanc... | Implement the Python class `EquipmentHandler` described below.
Class description:
Implementation logic for labware, pipette, and module loading.
Method signatures and docstrings:
- def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None: Initialize an EquipmentHandler instanc... | a255b76c8a07457787d575da12b2d5bdb6220a91 | <|skeleton|>
class EquipmentHandler:
"""Implementation logic for labware, pipette, and module loading."""
def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None:
"""Initialize an EquipmentHandler instance."""
<|body_0|>
async def load_labware(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquipmentHandler:
"""Implementation logic for labware, pipette, and module loading."""
def __init__(self, hardware: HardwareAPI, state: StateView, resources: ResourceProviders) -> None:
"""Initialize an EquipmentHandler instance."""
self._hardware = hardware
self._state = state
... | the_stack_v2_python_sparse | api/src/opentrons/protocol_engine/execution/equipment.py | Corey-ONeal/opentrons-app_ws-remote | train | 0 |
569923170ca20907b2fd81531243201ef4511f84 | [
"self.trainval = trainval\nself.log = logging.getLogger('avalanche')\nif os.path.isabs(data_folder):\n self.data_folder = data_folder\nelse:\n self.data_folder = os.path.join(os.path.dirname(__file__), data_folder)\ntry:\n os.makedirs(self.data_folder, exist_ok=True)\n self.log.info('Directory %s create... | <|body_start_0|>
self.trainval = trainval
self.log = logging.getLogger('avalanche')
if os.path.isabs(data_folder):
self.data_folder = data_folder
else:
self.data_folder = os.path.join(os.path.dirname(__file__), data_folder)
try:
os.makedirs(sel... | INATURALIST downloader. | INATURALIST_DATA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
<|body_0|>
def download_inaturalist(self):
"""Download and extract inaturali... | stack_v2_sparse_classes_36k_train_025791 | 6,358 | permissive | [
{
"docstring": "Args: data_folder (string): folder in which to download inaturalist dataset.",
"name": "__init__",
"signature": "def __init__(self, data_folder='data/', trainval=True)"
},
{
"docstring": "Download and extract inaturalist data :param extra: download also additional INATURALIST dat... | 2 | null | Implement the Python class `INATURALIST_DATA` described below.
Class description:
INATURALIST downloader.
Method signatures and docstrings:
- def __init__(self, data_folder='data/', trainval=True): Args: data_folder (string): folder in which to download inaturalist dataset.
- def download_inaturalist(self): Download ... | Implement the Python class `INATURALIST_DATA` described below.
Class description:
INATURALIST downloader.
Method signatures and docstrings:
- def __init__(self, data_folder='data/', trainval=True): Args: data_folder (string): folder in which to download inaturalist dataset.
- def download_inaturalist(self): Download ... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
<|body_0|>
def download_inaturalist(self):
"""Download and extract inaturali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class INATURALIST_DATA:
"""INATURALIST downloader."""
def __init__(self, data_folder='data/', trainval=True):
"""Args: data_folder (string): folder in which to download inaturalist dataset."""
self.trainval = trainval
self.log = logging.getLogger('avalanche')
if os.path.isabs(da... | the_stack_v2_python_sparse | avalanche/benchmarks/datasets/inaturalist/inaturalist_data.py | ContinualAI/avalanche | train | 1,424 |
6112804ff0682934c96fd99245790c51a5ad52b8 | [
"cate = Category(name='Django', views=1, likes=0)\ncate.save()\nself.assertEqual(cate.views >= 0, True)",
"cate = Category(name='first second three')\ncate.save()\nself.assertEqual(cate.slug, 'first-second-three')"
] | <|body_start_0|>
cate = Category(name='Django', views=1, likes=0)
cate.save()
self.assertEqual(cate.views >= 0, True)
<|end_body_0|>
<|body_start_1|>
cate = Category(name='first second three')
cate.save()
self.assertEqual(cate.slug, 'first-second-three')
<|end_body_1|>
| CategoryMethodTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryMethodTests:
def test_ensure_views_are_positive(self):
"""测试分类django的查看次数是否大于0,大于则返回True"""
<|body_0|>
def test_slug_line_creation(self):
"""检查slug是否正确"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cate = Category(name='Django', views=1, l... | stack_v2_sparse_classes_36k_train_025792 | 2,644 | no_license | [
{
"docstring": "测试分类django的查看次数是否大于0,大于则返回True",
"name": "test_ensure_views_are_positive",
"signature": "def test_ensure_views_are_positive(self)"
},
{
"docstring": "检查slug是否正确",
"name": "test_slug_line_creation",
"signature": "def test_slug_line_creation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014215 | Implement the Python class `CategoryMethodTests` described below.
Class description:
Implement the CategoryMethodTests class.
Method signatures and docstrings:
- def test_ensure_views_are_positive(self): 测试分类django的查看次数是否大于0,大于则返回True
- def test_slug_line_creation(self): 检查slug是否正确 | Implement the Python class `CategoryMethodTests` described below.
Class description:
Implement the CategoryMethodTests class.
Method signatures and docstrings:
- def test_ensure_views_are_positive(self): 测试分类django的查看次数是否大于0,大于则返回True
- def test_slug_line_creation(self): 检查slug是否正确
<|skeleton|>
class CategoryMethodT... | aeb2cd95599667767c0be3c5f23a040a416652cc | <|skeleton|>
class CategoryMethodTests:
def test_ensure_views_are_positive(self):
"""测试分类django的查看次数是否大于0,大于则返回True"""
<|body_0|>
def test_slug_line_creation(self):
"""检查slug是否正确"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryMethodTests:
def test_ensure_views_are_positive(self):
"""测试分类django的查看次数是否大于0,大于则返回True"""
cate = Category(name='Django', views=1, likes=0)
cate.save()
self.assertEqual(cate.views >= 0, True)
def test_slug_line_creation(self):
"""检查slug是否正确"""
cate... | the_stack_v2_python_sparse | python/DjangoWebProject/django_newswebsite/news/tests.py | Olaful/Olaful.github.io | train | 0 | |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'dep':\n if not request.user.is_superuser:\n kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department.id)\n else:\n kwargs['queryset'] = Department.objects.all()\nelif db_field.name == 'faculty' and request.user.is_superuser:\n kwargs['queryset'] ... | <|body_start_0|>
if db_field.name == 'dep':
if not request.user.is_superuser:
kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department.id)
else:
kwargs['queryset'] = Department.objects.all()
elif db_field.name == 'faculty' ... | EventAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
<|body_0|>
def get_queryset(self, request):
"""Returns events that lays in SV scope in case of staff, returns all events otherwise."""
... | stack_v2_sparse_classes_36k_train_025793 | 9,167 | permissive | [
{
"docstring": "limits department to user's departments.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Returns events that lays in SV scope in case of staff, returns all events otherwise.",
"name": "get... | 3 | stack_v2_sparse_classes_30k_train_019444 | Implement the Python class `EventAdmin` described below.
Class description:
Implement the EventAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits department to user's departments.
- def get_queryset(self, request): Returns events that lays in SV sc... | Implement the Python class `EventAdmin` described below.
Class description:
Implement the EventAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits department to user's departments.
- def get_queryset(self, request): Returns events that lays in SV sc... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
<|body_0|>
def get_queryset(self, request):
"""Returns events that lays in SV scope in case of staff, returns all events otherwise."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits department to user's departments."""
if db_field.name == 'dep':
if not request.user.is_superuser:
kwargs['queryset'] = Department.objects.filter(id=request.user.profile.department... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
d28f1bd9788243583dd2f1eb0ae5c814827583d6 | [
"self.activate = False\nself.menu = menu\nself.name = name\nself.profileJoinName = profilePluginFileName + '.& /' + name\nself.profilePluginFileName = profilePluginFileName\nself.radioVar = radioVar\nmenu.add_radiobutton(label=name.replace('_', ' '), command=self.clickRadio, value=self.profileJoinName, variable=sel... | <|body_start_0|>
self.activate = False
self.menu = menu
self.name = name
self.profileJoinName = profilePluginFileName + '.& /' + name
self.profilePluginFileName = profilePluginFileName
self.radioVar = radioVar
menu.add_radiobutton(label=name.replace('_', ' '), com... | A class to display a profile menu radio button. | ProfileMenuRadio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
<|body_0|>
def clickRadio(self):
"""Workaround for Tkinter bug, invoke and set the v... | stack_v2_sparse_classes_36k_train_025794 | 4,695 | no_license | [
{
"docstring": "Create a profile menu radio.",
"name": "__init__",
"signature": "def __init__(self, profilePluginFileName, menu, name, radioVar, value)"
},
{
"docstring": "Workaround for Tkinter bug, invoke and set the value when clicked.",
"name": "clickRadio",
"signature": "def clickRa... | 2 | stack_v2_sparse_classes_30k_train_011091 | Implement the Python class `ProfileMenuRadio` described below.
Class description:
A class to display a profile menu radio button.
Method signatures and docstrings:
- def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio.
- def clickRadio(self): Workaround for Tkinter bug,... | Implement the Python class `ProfileMenuRadio` described below.
Class description:
A class to display a profile menu radio button.
Method signatures and docstrings:
- def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio.
- def clickRadio(self): Workaround for Tkinter bug,... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
<|body_0|>
def clickRadio(self):
"""Workaround for Tkinter bug, invoke and set the v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
self.activate = False
self.menu = menu
self.name = name
self.profileJoinName = profile... | the_stack_v2_python_sparse | skeinforge_application/skeinforge_plugins/profile.py | amsler/skeinforge | train | 10 |
9ed4dee164fb5b4150e1ec382fc30273511fe59a | [
"self.k = self.k + 1\nself.t = self.t - self.grid_sys.dt\nself.J_next = self.J\nself.J = np.zeros(self.grid_sys.nodes_n, dtype=float)\nself.pi = np.zeros(self.grid_sys.nodes_n, dtype=int)\nself.J_interpol = self.grid_sys.compute_bivariatespline_2D_interpolation_function(self.J_next, kx=3, ky=3)",
"self.Q = np.zer... | <|body_start_0|>
self.k = self.k + 1
self.t = self.t - self.grid_sys.dt
self.J_next = self.J
self.J = np.zeros(self.grid_sys.nodes_n, dtype=float)
self.pi = np.zeros(self.grid_sys.nodes_n, dtype=int)
self.J_interpol = self.grid_sys.compute_bivariatespline_2D_interpolation... | Dynamic programming on a grid sys | DynamicProgramming2DRectBivariateSpline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicProgramming2DRectBivariateSpline:
"""Dynamic programming on a grid sys"""
def initialize_backward_step(self):
"""One step of value iteration"""
<|body_0|>
def compute_backward_step(self):
"""One step of value iteration"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_025795 | 28,371 | permissive | [
{
"docstring": "One step of value iteration",
"name": "initialize_backward_step",
"signature": "def initialize_backward_step(self)"
},
{
"docstring": "One step of value iteration",
"name": "compute_backward_step",
"signature": "def compute_backward_step(self)"
}
] | 2 | null | Implement the Python class `DynamicProgramming2DRectBivariateSpline` described below.
Class description:
Dynamic programming on a grid sys
Method signatures and docstrings:
- def initialize_backward_step(self): One step of value iteration
- def compute_backward_step(self): One step of value iteration | Implement the Python class `DynamicProgramming2DRectBivariateSpline` described below.
Class description:
Dynamic programming on a grid sys
Method signatures and docstrings:
- def initialize_backward_step(self): One step of value iteration
- def compute_backward_step(self): One step of value iteration
<|skeleton|>
cl... | baed84610d6090d42b814183931709fcdf61d012 | <|skeleton|>
class DynamicProgramming2DRectBivariateSpline:
"""Dynamic programming on a grid sys"""
def initialize_backward_step(self):
"""One step of value iteration"""
<|body_0|>
def compute_backward_step(self):
"""One step of value iteration"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicProgramming2DRectBivariateSpline:
"""Dynamic programming on a grid sys"""
def initialize_backward_step(self):
"""One step of value iteration"""
self.k = self.k + 1
self.t = self.t - self.grid_sys.dt
self.J_next = self.J
self.J = np.zeros(self.grid_sys.nodes_... | the_stack_v2_python_sparse | pyro/planning/dynamicprogramming.py | SherbyRobotics/pyro | train | 35 |
994c51a633dd074bcf6213fe8fa7c9f5c9f0e653 | [
"self.name = name\nself.subnet = subnet\nself.gateway_ip = gateway_ip\nself.enabled = enabled\nself.fixed_ip_assignments = fixed_ip_assignments\nself.reserved_ip_ranges = reserved_ip_ranges",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nsubnet = dictionary.get('subnet')\ngateway_ip = d... | <|body_start_0|>
self.name = name
self.subnet = subnet
self.gateway_ip = gateway_ip
self.enabled = enabled
self.fixed_ip_assignments = fixed_ip_assignments
self.reserved_ip_ranges = reserved_ip_ranges
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gateway IP (next hop) of the static route enabled (string): The enabled state of the static route fi... | UpdateNetworkStaticRouteModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkStaticRouteModel:
"""Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gateway IP (next hop) of the static route e... | stack_v2_sparse_classes_36k_train_025796 | 2,861 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkStaticRouteModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, subnet=None, gateway_ip=None, enabled=None, fixed_ip_assignments=None, reserved_ip_ranges=None)"
},
{
"docstring": "Creates an instance of this model from a d... | 2 | null | Implement the Python class `UpdateNetworkStaticRouteModel` described below.
Class description:
Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gate... | Implement the Python class `UpdateNetworkStaticRouteModel` described below.
Class description:
Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gate... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkStaticRouteModel:
"""Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gateway IP (next hop) of the static route e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkStaticRouteModel:
"""Implementation of the 'updateNetworkStaticRoute' model. TODO: type model description here. Attributes: name (string): The name of the static route subnet (string): The subnet of the static route gateway_ip (string): The gateway IP (next hop) of the static route enabled (strin... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_static_route_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
31a2c14aba6c01fe2ee5b515215a8d1f2ba64b8f | [
"mapAI = defaultdict(list)\nmapBK = defaultdict(list)\nfor i, Row in enumerate(A):\n for j, n in enumerate(Row):\n if n != 0:\n mapAI[j].append(i)\nfor j, Row in enumerate(B):\n for k, n in enumerate(Row):\n if n != 0:\n mapBK[j].append(k)\nres = [[0 for _ in range(len(B[0]... | <|body_start_0|>
mapAI = defaultdict(list)
mapBK = defaultdict(list)
for i, Row in enumerate(A):
for j, n in enumerate(Row):
if n != 0:
mapAI[j].append(i)
for j, Row in enumerate(B):
for k, n in enumerate(Row):
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def multiply_2(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_025797 | 1,735 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "multiply",
"signature": "def multiply(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "multiply_2",
"signature": "def m... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def multiply_2(self, A, B): :type A: List[List[int]] :type B: List[List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def multiply_2(self, A, B): :type A: List[List[int]] :type B: List[List[int]... | a6e6e5be3dd5f9501d0aa4caa6744621ab887f51 | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def multiply_2(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
mapAI = defaultdict(list)
mapBK = defaultdict(list)
for i, Row in enumerate(A):
for j, n in enumerate(Row):
if n != 0:
... | the_stack_v2_python_sparse | Python/311.sparse_matrix_multiplication.py | jxlxt/leetcode | train | 0 | |
1ae7e8e16ce85d382e8cb412e4f166a8f0ce2602 | [
"cnt = 0\np = -1\ns = -1\nfor i, n in enumerate(A):\n if n > R:\n if p >= 0:\n cnt += (i - p - 1) * (p - s)\n s = i\n p = -1\n elif L <= n <= R:\n if p >= 0:\n cnt += (i - p - 1) * (p - s)\n cnt += i - s\n p = i\nif p >= 0:\n cnt += (len(A) - ... | <|body_start_0|>
cnt = 0
p = -1
s = -1
for i, n in enumerate(A):
if n > R:
if p >= 0:
cnt += (i - p - 1) * (p - s)
s = i
p = -1
elif L <= n <= R:
if p >= 0:
cnt... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
"""09/17/2020 16:36"""
<|body_0|>
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
"""Segment tree. TLE Time complexity: O(n^2 * log(n))"""
<|body_1... | stack_v2_sparse_classes_36k_train_025798 | 4,112 | no_license | [
{
"docstring": "09/17/2020 16:36",
"name": "numSubarrayBoundedMax",
"signature": "def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int"
},
{
"docstring": "Segment tree. TLE Time complexity: O(n^2 * log(n))",
"name": "numSubarrayBoundedMax",
"signature": "def numSubarrayBo... | 3 | stack_v2_sparse_classes_30k_train_001719 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int: 09/17/2020 16:36
- def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: Segment t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int: 09/17/2020 16:36
- def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: Segment t... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
"""09/17/2020 16:36"""
<|body_0|>
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
"""Segment tree. TLE Time complexity: O(n^2 * log(n))"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
"""09/17/2020 16:36"""
cnt = 0
p = -1
s = -1
for i, n in enumerate(A):
if n > R:
if p >= 0:
cnt += (i - p - 1) * (p - s)
s = i... | the_stack_v2_python_sparse | leetcode/solved/811_Number_of_Subarrays_with_Bounded_Maximum/solution.py | sungminoh/algorithms | train | 0 | |
93e2f7c74ea961ebad6fda4b1e002b5d5bf84956 | [
"super().__init__(args, logger, on_episode_end, log_start_t)\nassert isinstance(self.home_mac, EnsembleMAC), 'Ensemble experiment enforces \"mac\"=ensemble in configuration'\nself.home_mac: EnsembleMAC = self.home_mac",
"self.home_mac.load_state_dict(agent=native)\nself.home_mac.load_state_dict(ensemble={0: forei... | <|body_start_0|>
super().__init__(args, logger, on_episode_end, log_start_t)
assert isinstance(self.home_mac, EnsembleMAC), 'Ensemble experiment enforces "mac"=ensemble in configuration'
self.home_mac: EnsembleMAC = self.home_mac
<|end_body_0|>
<|body_start_1|>
self.home_mac.load_state_... | EnsembleExperiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsembleExperiment:
def __init__(self, args, logger, on_episode_end=None, log_start_t=0):
"""LeaguePlay performs training of a single multi-agent and offers loading of new adversarial agents. :param args: :param logger: :param on_episode_end:"""
<|body_0|>
def load_ensemble(... | stack_v2_sparse_classes_36k_train_025799 | 1,638 | no_license | [
{
"docstring": "LeaguePlay performs training of a single multi-agent and offers loading of new adversarial agents. :param args: :param logger: :param on_episode_end:",
"name": "__init__",
"signature": "def __init__(self, args, logger, on_episode_end=None, log_start_t=0)"
},
{
"docstring": "Build... | 2 | stack_v2_sparse_classes_30k_train_005886 | Implement the Python class `EnsembleExperiment` described below.
Class description:
Implement the EnsembleExperiment class.
Method signatures and docstrings:
- def __init__(self, args, logger, on_episode_end=None, log_start_t=0): LeaguePlay performs training of a single multi-agent and offers loading of new adversari... | Implement the Python class `EnsembleExperiment` described below.
Class description:
Implement the EnsembleExperiment class.
Method signatures and docstrings:
- def __init__(self, args, logger, on_episode_end=None, log_start_t=0): LeaguePlay performs training of a single multi-agent and offers loading of new adversari... | c5c65992140c0fd61218513eb197189d560798cc | <|skeleton|>
class EnsembleExperiment:
def __init__(self, args, logger, on_episode_end=None, log_start_t=0):
"""LeaguePlay performs training of a single multi-agent and offers loading of new adversarial agents. :param args: :param logger: :param on_episode_end:"""
<|body_0|>
def load_ensemble(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnsembleExperiment:
def __init__(self, args, logger, on_episode_end=None, log_start_t=0):
"""LeaguePlay performs training of a single multi-agent and offers loading of new adversarial agents. :param args: :param logger: :param on_episode_end:"""
super().__init__(args, logger, on_episode_end, l... | the_stack_v2_python_sparse | src/runs/train/ensemble_experiment.py | PMatthaei/ma-league | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.