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
fecb3e22946d38845977e65758ca3ade8bc44058
[ "super().__init__()\nself.lca_layer = lca_layer\nself.num_lca_dim = num_lca_dim\nself.num_simulations = num_simulations\nself.num_time_steps = num_time_steps", "dev = ff_input.device\nactive = torch.ones(size=[int(self.num_simulations), 1], device=dev)\npre_activities = torch.zeros(size=[int(self.num_simulations)...
<|body_start_0|> super().__init__() self.lca_layer = lca_layer self.num_lca_dim = num_lca_dim self.num_simulations = num_simulations self.num_time_steps = num_time_steps <|end_body_0|> <|body_start_1|> dev = ff_input.device active = torch.ones(size=[int(self.num_...
LCAModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LCAModel: def __init__(self, lca_layer: LCALayer, num_lca_dim: int, num_simulations: int=10000, num_time_steps: int=3000): """A model that simulates a leaky competing accumulator model (Usher and McClelland). References: Usher M, McClelland JL. The time course of perceptual choice: the l...
stack_v2_sparse_classes_36k_train_010100
11,741
permissive
[ { "docstring": "A model that simulates a leaky competing accumulator model (Usher and McClelland). References: Usher M, McClelland JL. The time course of perceptual choice: the leaky, competing accumulator model. Psychol Rev. 2001 Jul;108(3):550-92. doi: 10.1037/0033-295x.108.3.550. PMID: 11488378. Args: lca_la...
2
stack_v2_sparse_classes_30k_train_004254
Implement the Python class `LCAModel` described below. Class description: Implement the LCAModel class. Method signatures and docstrings: - def __init__(self, lca_layer: LCALayer, num_lca_dim: int, num_simulations: int=10000, num_time_steps: int=3000): A model that simulates a leaky competing accumulator model (Usher...
Implement the Python class `LCAModel` described below. Class description: Implement the LCAModel class. Method signatures and docstrings: - def __init__(self, lca_layer: LCALayer, num_lca_dim: int, num_simulations: int=10000, num_time_steps: int=3000): A model that simulates a leaky competing accumulator model (Usher...
424971b04d55a2cddbae4c05a0aae2d7b3502c20
<|skeleton|> class LCAModel: def __init__(self, lca_layer: LCALayer, num_lca_dim: int, num_simulations: int=10000, num_time_steps: int=3000): """A model that simulates a leaky competing accumulator model (Usher and McClelland). References: Usher M, McClelland JL. The time course of perceptual choice: the l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LCAModel: def __init__(self, lca_layer: LCALayer, num_lca_dim: int, num_simulations: int=10000, num_time_steps: int=3000): """A model that simulates a leaky competing accumulator model (Usher and McClelland). References: Usher M, McClelland JL. The time course of perceptual choice: the leaky, competin...
the_stack_v2_python_sparse
Scripts/Debug/lca/onnx_lca.py
PrincetonUniversity/PsyNeuLink
train
79
d5248ef4b524621538e7af886947d13b71a01b66
[ "self.magnitude = magnitude\nself.c_i = c_i\nself.nsamples = nsamples\nself.stdev_spread = stdev_spread\nloss_c = model.output[0][c_i]\ngrad_symbolic = K.gradients(loss_c, model.input)[0]\nself.iterate = K.function([model.input], grad_symbolic)", "total_gradients = np.zeros_like(x_value)\nstdev = self.stdev_sprea...
<|body_start_0|> self.magnitude = magnitude self.c_i = c_i self.nsamples = nsamples self.stdev_spread = stdev_spread loss_c = model.output[0][c_i] grad_symbolic = K.gradients(loss_c, model.input)[0] self.iterate = K.function([model.input], grad_symbolic) <|end_bod...
SmoothedMask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmoothedMask: def __init__(self, model, c_i, stdev_spread=0.15, nsamples=25, magnitude=True): """Define the smoothGrad Mask class to return the smooth grad mask model : the deep model used c_i : the index of the class concerned stdev_spread: Amount of noise to add to the input, as fracti...
stack_v2_sparse_classes_36k_train_010101
9,618
no_license
[ { "docstring": "Define the smoothGrad Mask class to return the smooth grad mask model : the deep model used c_i : the index of the class concerned stdev_spread: Amount of noise to add to the input, as fraction of the total spread (x_max - x_min). Defaults to 15%. Level of noise nsamples: Number of samples to av...
2
stack_v2_sparse_classes_30k_train_013919
Implement the Python class `SmoothedMask` described below. Class description: Implement the SmoothedMask class. Method signatures and docstrings: - def __init__(self, model, c_i, stdev_spread=0.15, nsamples=25, magnitude=True): Define the smoothGrad Mask class to return the smooth grad mask model : the deep model use...
Implement the Python class `SmoothedMask` described below. Class description: Implement the SmoothedMask class. Method signatures and docstrings: - def __init__(self, model, c_i, stdev_spread=0.15, nsamples=25, magnitude=True): Define the smoothGrad Mask class to return the smooth grad mask model : the deep model use...
60da35f58ffe9e24e99b6b20dd7a46b02815ad79
<|skeleton|> class SmoothedMask: def __init__(self, model, c_i, stdev_spread=0.15, nsamples=25, magnitude=True): """Define the smoothGrad Mask class to return the smooth grad mask model : the deep model used c_i : the index of the class concerned stdev_spread: Amount of noise to add to the input, as fracti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmoothedMask: def __init__(self, model, c_i, stdev_spread=0.15, nsamples=25, magnitude=True): """Define the smoothGrad Mask class to return the smooth grad mask model : the deep model used c_i : the index of the class concerned stdev_spread: Amount of noise to add to the input, as fraction of the tota...
the_stack_v2_python_sparse
Classif_Paintings/saliencyMaps.py
ngonthier/Icono_Art_Analysis
train
2
a4951c685ffbc51514c66de5e3738a1605064731
[ "if decay < 0.0 or decay > 1.0:\n raise ValueError('Decay must be between 0 and 1')\nself.decay = decay\nself.num_updates = 0 if use_num_updates else None\nself.shadow_params = [p.clone().detach() for p in parameters if p.requires_grad]", "decay = self.decay\nif self.num_updates is not None:\n self.num_upda...
<|body_start_0|> if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.decay = decay self.num_updates = 0 if use_num_updates else None self.shadow_params = [p.clone().detach() for p in parameters if p.requires_grad] <|end_body_0|> <|body_start...
Maintains (exponential) moving average of a set of parameters.
ExponentialMovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExponentialMovingAverage: """Maintains (exponential) moving average of a set of parameters.""" def __init__(self, parameters, decay, use_num_updates=True): """Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay....
stack_v2_sparse_classes_36k_train_010102
7,328
no_license
[ { "docstring": "Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay. use_num_updates: Whether to use number of updates when computing averages.", "name": "__init__", "signature": "def __init__(self, parameters, decay, use_num_updat...
3
stack_v2_sparse_classes_30k_val_000483
Implement the Python class `ExponentialMovingAverage` described below. Class description: Maintains (exponential) moving average of a set of parameters. Method signatures and docstrings: - def __init__(self, parameters, decay, use_num_updates=True): Args: parameters: Iterable of `torch.nn.Parameter`; usually the resu...
Implement the Python class `ExponentialMovingAverage` described below. Class description: Maintains (exponential) moving average of a set of parameters. Method signatures and docstrings: - def __init__(self, parameters, decay, use_num_updates=True): Args: parameters: Iterable of `torch.nn.Parameter`; usually the resu...
aede6493126fdefa3961c8f3fc06bd84d2a9a8b8
<|skeleton|> class ExponentialMovingAverage: """Maintains (exponential) moving average of a set of parameters.""" def __init__(self, parameters, decay, use_num_updates=True): """Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExponentialMovingAverage: """Maintains (exponential) moving average of a set of parameters.""" def __init__(self, parameters, decay, use_num_updates=True): """Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay. use_num_upda...
the_stack_v2_python_sparse
tasks/tumor_segmentation_task.py
Animatory/BrainTumorSegmentation
train
0
f95e38ae5063b1b3aac06d3f32bb7fa3f487967d
[ "metrics_window = self.metrics_window[1:]\nmetrics_window.append(round_metric)\naverage_metric = tf.reduce_mean(metrics_window)\nlearning_rate = self.learning_rate\nbest = self.best\nwait = self.wait\ncooldown_counter = self.cooldown_counter\nif cooldown_counter > 0:\n cooldown_counter -= 1\n wait = 0\nif sel...
<|body_start_0|> metrics_window = self.metrics_window[1:] metrics_window.append(round_metric) average_metric = tf.reduce_mean(metrics_window) learning_rate = self.learning_rate best = self.best wait = self.wait cooldown_counter = self.cooldown_counter if c...
A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be reduced when a plateau occurs. minimize: A boolean, when `True` the metric will be ...
ReduceLROnPlateau
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReduceLROnPlateau: """A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be reduced when a plateau occurs. minimiz...
stack_v2_sparse_classes_36k_train_010103
6,991
permissive
[ { "docstring": "Updates the `ReduceLROnPlateau` callback based on the round metric.", "name": "update", "signature": "def update(self, round_metric)" }, { "docstring": "Determines if a round metric improves a given ReduceLROnPlateau`.", "name": "improves_best", "signature": "def improves...
2
null
Implement the Python class `ReduceLROnPlateau` described below. Class description: A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be...
Implement the Python class `ReduceLROnPlateau` described below. Class description: A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be...
329e60fa56b87f691303638ceb9dfa1fc5083953
<|skeleton|> class ReduceLROnPlateau: """A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be reduced when a plateau occurs. minimiz...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReduceLROnPlateau: """A callback for decaying a learning rate when a metric stops improving. Attributes: learning_rate: The current learning rate. monitor: The name of the metric governing the callback. decay_factor: Factor by which the learning rate will be reduced when a plateau occurs. minimize: A boolean,...
the_stack_v2_python_sparse
adaptive_lr_decay/callbacks.py
google-research/federated
train
595
b73e89959b4f49cc07ccee74978f068a3bb2c3ce
[ "if self.note:\n return self.note.note\nreturn None", "if user:\n self.deleted_by = user\nself.deleted_at = deleted_at\nself.save()" ]
<|body_start_0|> if self.note: return self.note.note return None <|end_body_0|> <|body_start_1|> if user: self.deleted_by = user self.deleted_at = deleted_at self.save() <|end_body_1|>
SubmissionReview Model Class
SubmissionReview
[ "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubmissionReview: """SubmissionReview Model Class""" def get_note_text(self): """Custom Property returns associated note text""" <|body_0|> def set_deleted(self, deleted_at=timezone.now(), user=None): """Sets the deleted_at and deleted_by fields""" <|body...
stack_v2_sparse_classes_36k_train_010104
2,651
permissive
[ { "docstring": "Custom Property returns associated note text", "name": "get_note_text", "signature": "def get_note_text(self)" }, { "docstring": "Sets the deleted_at and deleted_by fields", "name": "set_deleted", "signature": "def set_deleted(self, deleted_at=timezone.now(), user=None)" ...
2
null
Implement the Python class `SubmissionReview` described below. Class description: SubmissionReview Model Class Method signatures and docstrings: - def get_note_text(self): Custom Property returns associated note text - def set_deleted(self, deleted_at=timezone.now(), user=None): Sets the deleted_at and deleted_by fie...
Implement the Python class `SubmissionReview` described below. Class description: SubmissionReview Model Class Method signatures and docstrings: - def get_note_text(self): Custom Property returns associated note text - def set_deleted(self, deleted_at=timezone.now(), user=None): Sets the deleted_at and deleted_by fie...
e5bdec91cb47179172b515bbcb91701262ff3377
<|skeleton|> class SubmissionReview: """SubmissionReview Model Class""" def get_note_text(self): """Custom Property returns associated note text""" <|body_0|> def set_deleted(self, deleted_at=timezone.now(), user=None): """Sets the deleted_at and deleted_by fields""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubmissionReview: """SubmissionReview Model Class""" def get_note_text(self): """Custom Property returns associated note text""" if self.note: return self.note.note return None def set_deleted(self, deleted_at=timezone.now(), user=None): """Sets the delete...
the_stack_v2_python_sparse
onadata/apps/logger/models/submission_review.py
onaio/onadata
train
177
933bde235606baf6d6bcc568464e99ed3c46cf02
[ "with self.assertRaises(TypeError):\n get_majorana_operator(1.0)\nwith self.assertRaises(TypeError):\n _fermion_operator_to_majorana_operator([1.0])\nwith self.assertRaises(TypeError):\n _fermion_term_to_majorana_operator(1.0)", "fermion_op = -2j * (FermionOperator(((0, 0), (1, 0))) - FermionOperator(((0...
<|body_start_0|> with self.assertRaises(TypeError): get_majorana_operator(1.0) with self.assertRaises(TypeError): _fermion_operator_to_majorana_operator([1.0]) with self.assertRaises(TypeError): _fermion_term_to_majorana_operator(1.0) <|end_body_0|> <|body_st...
Test class get Majorana Operator.
GetMajoranaOperatorTest
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetMajoranaOperatorTest: """Test class get Majorana Operator.""" def test_raises(self): """Test raises errors.""" <|body_0|> def test_get_majorana_operator_fermion_operator(self): """Test conversion FermionOperator to MajoranaOperator.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_010105
8,235
permissive
[ { "docstring": "Test raises errors.", "name": "test_raises", "signature": "def test_raises(self)" }, { "docstring": "Test conversion FermionOperator to MajoranaOperator.", "name": "test_get_majorana_operator_fermion_operator", "signature": "def test_get_majorana_operator_fermion_operator...
3
stack_v2_sparse_classes_30k_train_012680
Implement the Python class `GetMajoranaOperatorTest` described below. Class description: Test class get Majorana Operator. Method signatures and docstrings: - def test_raises(self): Test raises errors. - def test_get_majorana_operator_fermion_operator(self): Test conversion FermionOperator to MajoranaOperator. - def ...
Implement the Python class `GetMajoranaOperatorTest` described below. Class description: Test class get Majorana Operator. Method signatures and docstrings: - def test_raises(self): Test raises errors. - def test_get_majorana_operator_fermion_operator(self): Test conversion FermionOperator to MajoranaOperator. - def ...
788481753c798a72c5cb3aa9f2aa9da3ce3190b0
<|skeleton|> class GetMajoranaOperatorTest: """Test class get Majorana Operator.""" def test_raises(self): """Test raises errors.""" <|body_0|> def test_get_majorana_operator_fermion_operator(self): """Test conversion FermionOperator to MajoranaOperator.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetMajoranaOperatorTest: """Test class get Majorana Operator.""" def test_raises(self): """Test raises errors.""" with self.assertRaises(TypeError): get_majorana_operator(1.0) with self.assertRaises(TypeError): _fermion_operator_to_majorana_operator([1.0]) ...
the_stack_v2_python_sparse
src/openfermion/transforms/opconversions/conversions_test.py
quantumlib/OpenFermion
train
1,481
748fb9809f78fc8eac9e2b45c3711fdce7bdbe3f
[ "Base.__init__(self, target, opts)\nself.host, self.port, self.scheme, self.path = self._parse_url(self.target)\nreturn", "url = self.target\nif self.opts['attack_url']:\n url = self.opts['attack_url']\nif self.opts['login_url']:\n url = self.opts['login_url']\nwith timeout(self.opts['timeout']):\n self....
<|body_start_0|> Base.__init__(self, target, opts) self.host, self.port, self.scheme, self.path = self._parse_url(self.target) return <|end_body_0|> <|body_start_1|> url = self.target if self.opts['attack_url']: url = self.opts['attack_url'] if self.opts['log...
Login Cracker module
Crack
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Crack: """Login Cracker module""" def __init__(self, target, opts): """init""" <|body_0|> def crack_http_auth_web(self): """DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3""" <|body_1|> def crack_tomcat_web(self...
stack_v2_sparse_classes_36k_train_010106
3,279
no_license
[ { "docstring": "init", "name": "__init__", "signature": "def __init__(self, target, opts)" }, { "docstring": "DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3", "name": "crack_http_auth_web", "signature": "def crack_http_auth_web(self)" }, { ...
4
stack_v2_sparse_classes_30k_test_000572
Implement the Python class `Crack` described below. Class description: Login Cracker module Method signatures and docstrings: - def __init__(self, target, opts): init - def crack_http_auth_web(self): DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3 - def crack_tomcat_web(self): D...
Implement the Python class `Crack` described below. Class description: Login Cracker module Method signatures and docstrings: - def __init__(self, target, opts): init - def crack_http_auth_web(self): DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3 - def crack_tomcat_web(self): D...
ddc052c8d7d43a60fc00ea40d85111d5bd7a282e
<|skeleton|> class Crack: """Login Cracker module""" def __init__(self, target, opts): """init""" <|body_0|> def crack_http_auth_web(self): """DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3""" <|body_1|> def crack_tomcat_web(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Crack: """Login Cracker module""" def __init__(self, target, opts): """init""" Base.__init__(self, target, opts) self.host, self.port, self.scheme, self.path = self._parse_url(self.target) return def crack_http_auth_web(self): """DESCR: Check HTTP auth type (b...
the_stack_v2_python_sparse
src/modules/web/crack.py
noptrix/nullscan
train
52
560e7574f656daea9f6767e1ee6723757a833af8
[ "if root:\n queue = [root]\nelse:\n return '[]'\nres = [root.val]\nwhile queue:\n node = queue.pop(0)\n if node.left:\n res.append(node.left.val)\n queue.append(node.left)\n else:\n res.append(None)\n if node.right:\n res.append(node.right.val)\n queue.append(nod...
<|body_start_0|> if root: queue = [root] else: return '[]' res = [root.val] while queue: node = queue.pop(0) if node.left: res.append(node.left.val) queue.append(node.left) else: r...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_010107
2,373
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_val_000114
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
c811c7fb2d203852eb35019f9e3c6b5f1a5a2133
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if root: queue = [root] else: return '[]' res = [root.val] while queue: node = queue.pop(0) if node.left: ...
the_stack_v2_python_sparse
leetcode/297.二叉树的序列化与反序列化.py
guojiangwei/data-structure
train
0
e85e9f9f8890b0728d0f4ea677c3528ba5239040
[ "super(ListOfListsAction, self).__init__(option_strings, dest, **kwargs)\nself.dtype = type\nif self.dtype is None:\n self.dtype = np.int32", "decoded_list = []\nremoved1 = values.replace('[', '')\nremoved2 = removed1.replace(']', '')\nout_list = removed2.split(':')\nfor line in out_list:\n in_list = []\n ...
<|body_start_0|> super(ListOfListsAction, self).__init__(option_strings, dest, **kwargs) self.dtype = type if self.dtype is None: self.dtype = np.int32 <|end_body_0|> <|body_start_1|> decoded_list = [] removed1 = values.replace('[', '') removed2 = removed1.re...
This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string.
ListOfListsAction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListOfListsAction: """This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string.""" def __init__(self, option_strings, dest, type, **kwargs): """Initialize a ListOfLists...
stack_v2_sparse_classes_36k_train_010108
28,110
permissive
[ { "docstring": "Initialize a ListOfListsAction object. If no type is specified, an integer is assumed by default as the type for the elements of the list-of-lists. Parameters ---------- option_strings : string String to parse dest : object Object to store the output (in this case the parsed list-of-lists). type...
2
null
Implement the Python class `ListOfListsAction` described below. Class description: This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string. Method signatures and docstrings: - def __init__(self, option...
Implement the Python class `ListOfListsAction` described below. Class description: This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string. Method signatures and docstrings: - def __init__(self, option...
f6a3da8818308c9edcd9fedbcf831dd5968efcdd
<|skeleton|> class ListOfListsAction: """This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string.""" def __init__(self, option_strings, dest, type, **kwargs): """Initialize a ListOfLists...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListOfListsAction: """This class extends the argparse.Action class by instantiating an argparser that constructs a list-of-lists from an input (command-line option or argument) given as a string.""" def __init__(self, option_strings, dest, type, **kwargs): """Initialize a ListOfListsAction object...
the_stack_v2_python_sparse
common/parsing_utils.py
ECP-CANDLE/Benchmarks
train
65
cece3091c1a56091f60fd4fcacc1f6469411addc
[ "try:\n dst_state = Status.objects.get(id=self.context.get('dst_state'))\nexcept Status.DoesNotExist:\n self.data.set_outputs('message', '对应的节点不存在')\n return False\nprocessors = self.data.get_one_of_inputs('processors')\nif not processors:\n self.data.set_outputs('message', '设置处理人为空')\n return False\...
<|body_start_0|> try: dst_state = Status.objects.get(id=self.context.get('dst_state')) except Status.DoesNotExist: self.data.set_outputs('message', '对应的节点不存在') return False processors = self.data.get_one_of_inputs('processors') if not processors: ...
ModifyProcessorComponent
[ "MIT", "LGPL-2.1-or-later", "LGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModifyProcessorComponent: def _execute(self): """修改节点对应的处理人""" <|body_0|> def update_context(self): """手动操作的时候更新context""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: dst_state = Status.objects.get(id=self.context.get('dst_state'))...
stack_v2_sparse_classes_36k_train_010109
3,288
permissive
[ { "docstring": "修改节点对应的处理人", "name": "_execute", "signature": "def _execute(self)" }, { "docstring": "手动操作的时候更新context", "name": "update_context", "signature": "def update_context(self)" } ]
2
stack_v2_sparse_classes_30k_train_008654
Implement the Python class `ModifyProcessorComponent` described below. Class description: Implement the ModifyProcessorComponent class. Method signatures and docstrings: - def _execute(self): 修改节点对应的处理人 - def update_context(self): 手动操作的时候更新context
Implement the Python class `ModifyProcessorComponent` described below. Class description: Implement the ModifyProcessorComponent class. Method signatures and docstrings: - def _execute(self): 修改节点对应的处理人 - def update_context(self): 手动操作的时候更新context <|skeleton|> class ModifyProcessorComponent: def _execute(self):...
2d708bd0d869d391456e0fb8d644af3b9f031acf
<|skeleton|> class ModifyProcessorComponent: def _execute(self): """修改节点对应的处理人""" <|body_0|> def update_context(self): """手动操作的时候更新context""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModifyProcessorComponent: def _execute(self): """修改节点对应的处理人""" try: dst_state = Status.objects.get(id=self.context.get('dst_state')) except Status.DoesNotExist: self.data.set_outputs('message', '对应的节点不存在') return False processors = self.data....
the_stack_v2_python_sparse
itsm/trigger/action/components/modify_processor.py
TencentBlueKing/bk-itsm
train
100
e34e584ad7d0eb51c4937d8790831c8680a02c9e
[ "post_reply = get_object_or_404(PostReply, pk=post_reply_id)\nserializer = PostReplySerializerUpdate(post_reply, data=request.data, context={'request': request}, partial=True)\nif serializer.is_valid():\n serializer.save()\n return Response(PostReplySerializer(serializer.instance).data)\nreturn Response(seria...
<|body_start_0|> post_reply = get_object_or_404(PostReply, pk=post_reply_id) serializer = PostReplySerializerUpdate(post_reply, data=request.data, context={'request': request}, partial=True) if serializer.is_valid(): serializer.save() return Response(PostReplySerializer(s...
PostReplyDetail
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostReplyDetail: def patch(request, post_reply_id): """Update post reply""" <|body_0|> def delete(request, post_reply_id): """Delete post reply""" <|body_1|> <|end_skeleton|> <|body_start_0|> post_reply = get_object_or_404(PostReply, pk=post_reply_i...
stack_v2_sparse_classes_36k_train_010110
1,780
permissive
[ { "docstring": "Update post reply", "name": "patch", "signature": "def patch(request, post_reply_id)" }, { "docstring": "Delete post reply", "name": "delete", "signature": "def delete(request, post_reply_id)" } ]
2
stack_v2_sparse_classes_30k_train_015448
Implement the Python class `PostReplyDetail` described below. Class description: Implement the PostReplyDetail class. Method signatures and docstrings: - def patch(request, post_reply_id): Update post reply - def delete(request, post_reply_id): Delete post reply
Implement the Python class `PostReplyDetail` described below. Class description: Implement the PostReplyDetail class. Method signatures and docstrings: - def patch(request, post_reply_id): Update post reply - def delete(request, post_reply_id): Delete post reply <|skeleton|> class PostReplyDetail: def patch(req...
b93fa2fea8d45df9f19c3c58037e59dad4981921
<|skeleton|> class PostReplyDetail: def patch(request, post_reply_id): """Update post reply""" <|body_0|> def delete(request, post_reply_id): """Delete post reply""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PostReplyDetail: def patch(request, post_reply_id): """Update post reply""" post_reply = get_object_or_404(PostReply, pk=post_reply_id) serializer = PostReplySerializerUpdate(post_reply, data=request.data, context={'request': request}, partial=True) if serializer.is_valid(): ...
the_stack_v2_python_sparse
v1/replies/views/post_reply.py
lawiz22/PLOUC-Backend-master
train
0
5c580eb8776cf69b4e6395e0d76d1c4baad5a31f
[ "self.prototype = prototype\nself.config = ConfigParser()\nif fileName:\n if not os.path.isfile(fileName):\n path = Resource.getWritableResourcePath()\n fileName = os.path.join(path, fileName)\n self.config.read(fileName)\nself.fileName = fileName\nfor section, options in prototype.items():\n ...
<|body_start_0|> self.prototype = prototype self.config = ConfigParser() if fileName: if not os.path.isfile(fileName): path = Resource.getWritableResourcePath() fileName = os.path.join(path, fileName) self.config.read(fileName) self...
A configuration registry.
Config
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """A configuration registry.""" def __init__(self, prototype, fileName=None): """@param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry""" <|body_0|> def get(self, section, option): """Read a c...
stack_v2_sparse_classes_36k_train_010111
5,757
no_license
[ { "docstring": "@param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry", "name": "__init__", "signature": "def __init__(self, prototype, fileName=None)" }, { "docstring": "Read a configuration key. @param section: Section name @param ...
3
null
Implement the Python class `Config` described below. Class description: A configuration registry. Method signatures and docstrings: - def __init__(self, prototype, fileName=None): @param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry - def get(self, secti...
Implement the Python class `Config` described below. Class description: A configuration registry. Method signatures and docstrings: - def __init__(self, prototype, fileName=None): @param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry - def get(self, secti...
9d72169506172c40e7bbd69ceb4b649279c5b239
<|skeleton|> class Config: """A configuration registry.""" def __init__(self, prototype, fileName=None): """@param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry""" <|body_0|> def get(self, section, option): """Read a c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Config: """A configuration registry.""" def __init__(self, prototype, fileName=None): """@param prototype: The configuration protype mapping @param fileName: The file that holds this configuration registry""" self.prototype = prototype self.config = ConfigParser() if fileN...
the_stack_v2_python_sparse
minifof/src/foflib/Config.py
jay3sh/altcanvas
train
1
05cd67a57b00d1fa61a3dcfea266762edda91c78
[ "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 Feed service. Service to manage feeds.
FeedServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeedServiceServicer: """Proto file describing the Feed service. Service to manage feeds.""" def GetFeed(self, request, context): """Returns the requested feed in full detail.""" <|body_0|> def MutateFeeds(self, request, context): """Creates, updates, or removes f...
stack_v2_sparse_classes_36k_train_010112
5,053
permissive
[ { "docstring": "Returns the requested feed in full detail.", "name": "GetFeed", "signature": "def GetFeed(self, request, context)" }, { "docstring": "Creates, updates, or removes feeds. Operation statuses are returned.", "name": "MutateFeeds", "signature": "def MutateFeeds(self, request,...
2
stack_v2_sparse_classes_30k_train_008236
Implement the Python class `FeedServiceServicer` described below. Class description: Proto file describing the Feed service. Service to manage feeds. Method signatures and docstrings: - def GetFeed(self, request, context): Returns the requested feed in full detail. - def MutateFeeds(self, request, context): Creates, ...
Implement the Python class `FeedServiceServicer` described below. Class description: Proto file describing the Feed service. Service to manage feeds. Method signatures and docstrings: - def GetFeed(self, request, context): Returns the requested feed in full detail. - def MutateFeeds(self, request, context): Creates, ...
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
<|skeleton|> class FeedServiceServicer: """Proto file describing the Feed service. Service to manage feeds.""" def GetFeed(self, request, context): """Returns the requested feed in full detail.""" <|body_0|> def MutateFeeds(self, request, context): """Creates, updates, or removes f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeedServiceServicer: """Proto file describing the Feed service. Service to manage feeds.""" def GetFeed(self, request, context): """Returns the requested feed in full detail.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
google/ads/google_ads/v5/proto/services/feed_service_pb2_grpc.py
fiboknacky/google-ads-python
train
0
6ea84b27e1aacc2fef00b14632368c2a2a487eb4
[ "self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else '__unused').set(thing_classes=['G1/G2', 'S', 'M', 'E'])\nself.cpu_device = torch.device('cpu')\nself.instance_mode = instance_mode\nself.parallel = parallel\nif parallel:\n num_gpu = torch.cuda.device_count()\n self.predi...
<|body_start_0|> self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else '__unused').set(thing_classes=['G1/G2', 'S', 'M', 'E']) self.cpu_device = torch.device('cpu') self.instance_mode = instance_mode self.parallel = parallel if parallel: ...
VisualizationDemo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VisualizationDemo: def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): """Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Use...
stack_v2_sparse_classes_36k_train_010113
13,593
permissive
[ { "docstring": "Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Useful since the visualization logic can be slow.", "name": "__init__", "signature": "def __init_...
2
stack_v2_sparse_classes_30k_train_008199
Implement the Python class `VisualizationDemo` described below. Class description: Implement the VisualizationDemo class. Method signatures and docstrings: - def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_...
Implement the Python class `VisualizationDemo` described below. Class description: Implement the VisualizationDemo class. Method signatures and docstrings: - def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_...
16f8128167c143dfd9cb6cf25046725a5cf1273a
<|skeleton|> class VisualizationDemo: def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): """Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Use...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VisualizationDemo: def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False): """Copied from Facebook Detectron2 Demo. Apache 2.0 Licence. Args: cfg (CfgNode): instance_mode (ColorMode): parallel (bool): whether to run the model in different processes from visualization. Useful since the ...
the_stack_v2_python_sparse
bin/pcnaDeep/predictor.py
kuanyoow/PCNAdeep
train
0
39781d0d9c73f7a4cd9c61c994578beffed84f9c
[ "self.modern_dem_name = modern_dem_name\nself.modeled_dem_name = modeled_dem_name\nself.grid, self.z = self.read_topography(modern_dem_name)\nself.grid.set_watershed_boundary_condition_outlet_id(outlet_id, self.z, nodata_value=-9999)\nself.mgrid, self.mz = self.read_topography(modeled_dem_name)\nself.mgrid.set_wate...
<|body_start_0|> self.modern_dem_name = modern_dem_name self.modeled_dem_name = modeled_dem_name self.grid, self.z = self.read_topography(modern_dem_name) self.grid.set_watershed_boundary_condition_outlet_id(outlet_id, self.z, nodata_value=-9999) self.mgrid, self.mz = self.read_t...
Calculator for topographic metrics used in sensitivity analysis and model evaluation.
GroupedDifferences
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupedDifferences: """Calculator for topographic metrics used in sensitivity analysis and model evaluation.""" def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None): """Initialize GroupedDiffe...
stack_v2_sparse_classes_36k_train_010114
5,390
no_license
[ { "docstring": "Initialize GroupedDifferences with names of postglacial and modern DEMs.", "name": "__init__", "signature": "def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None)" }, { "docstring": "Read a...
5
stack_v2_sparse_classes_30k_train_014027
Implement the Python class `GroupedDifferences` described below. Class description: Calculator for topographic metrics used in sensitivity analysis and model evaluation. Method signatures and docstrings: - def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weigh...
Implement the Python class `GroupedDifferences` described below. Class description: Calculator for topographic metrics used in sensitivity analysis and model evaluation. Method signatures and docstrings: - def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weigh...
3506ec741a7c8a170ea654d40c6119fefe1b93ba
<|skeleton|> class GroupedDifferences: """Calculator for topographic metrics used in sensitivity analysis and model evaluation.""" def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None): """Initialize GroupedDiffe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupedDifferences: """Calculator for topographic metrics used in sensitivity analysis and model evaluation.""" def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None): """Initialize GroupedDifferences with n...
the_stack_v2_python_sparse
metric_and_objective_function_calculation/metric_calculator/grouped_differences.py
kbarnhart/inverting_topography_postglacial
train
4
8047289b9f6d2fc1a28e952a519c7ea304faae95
[ "procrowre = re.compile('\\\\s*([-/_a-zA-Z0-9%]+)\\\\s*=\\\\s*\"([^\"]+)\"')\nlstss = []\nfor line in rules_file_contents.split('\\n'):\n s = line.strip()\n m = procrowre.match(s)\n if not m:\n continue\n lstss.append((m.group(1), m.group(2)))\nreturn lstss", "rulerowre = re.compile('^\\\\s*([0...
<|body_start_0|> procrowre = re.compile('\\s*([-/_a-zA-Z0-9%]+)\\s*=\\s*"([^"]+)"') lstss = [] for line in rules_file_contents.split('\n'): s = line.strip() m = procrowre.match(s) if not m: continue lstss.append((m.group(1), m.group...
ExtRulesParser
[ "MIT", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtRulesParser: def parseLstsFiles(self, rules_file_contents): """Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#...
stack_v2_sparse_classes_36k_train_010115
3,149
permissive
[ { "docstring": "Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = \"<lstsfilename1>\" <lsts#2> = \"<lstsfilename2>\" ... Returns list of numbers and lsts filenames: [ (lsts#1, \"lstsfilename1\"), (lsts#2, \"lstsfilename2\"), ... ]", "name"...
2
null
Implement the Python class `ExtRulesParser` described below. Class description: Implement the ExtRulesParser class. Method signatures and docstrings: - def parseLstsFiles(self, rules_file_contents): Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = ...
Implement the Python class `ExtRulesParser` described below. Class description: Implement the ExtRulesParser class. Method signatures and docstrings: - def parseLstsFiles(self, rules_file_contents): Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = ...
9c3f119c8bf5cc565e6a3e8e9e6205037e326d89
<|skeleton|> class ExtRulesParser: def parseLstsFiles(self, rules_file_contents): """Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExtRulesParser: def parseLstsFiles(self, rules_file_contents): """Parse the lsts files in the given string. The string is assumed to be in TVT extended rules format, that is <lsts#1> = "<lstsfilename1>" <lsts#2> = "<lstsfilename2>" ... Returns list of numbers and lsts filenames: [ (lsts#1, "lstsfilena...
the_stack_v2_python_sparse
TemaLib/tema/rules/rules_parser.py
tema-tut/tema-tg
train
1
757de08854639016817e7589d3f65d5282b76581
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TemporaryAccessPassAuthenticationMethod()", "from .authentication_method import AuthenticationMethod\nfrom .authentication_method import AuthenticationMethod\nfields: Dict[str, Callable[[Any], None]] = {'createdDateTime': lambda n: set...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return TemporaryAccessPassAuthenticationMethod() <|end_body_0|> <|body_start_1|> from .authentication_method import AuthenticationMethod from .authentication_method import AuthenticationMethod ...
TemporaryAccessPassAuthenticationMethod
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemporaryAccessPassAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read t...
stack_v2_sparse_classes_36k_train_010116
4,574
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TemporaryAccessPassAuthenticationMethod", "name": "create_from_discriminator_value", "signature": "def creat...
3
stack_v2_sparse_classes_30k_train_020438
Implement the Python class `TemporaryAccessPassAuthenticationMethod` described below. Class description: Implement the TemporaryAccessPassAuthenticationMethod class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod...
Implement the Python class `TemporaryAccessPassAuthenticationMethod` described below. Class description: Implement the TemporaryAccessPassAuthenticationMethod class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class TemporaryAccessPassAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemporaryAccessPassAuthenticationMethod: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TemporaryAccessPassAuthenticationMethod: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminat...
the_stack_v2_python_sparse
msgraph/generated/models/temporary_access_pass_authentication_method.py
microsoftgraph/msgraph-sdk-python
train
135
0e2229b616d9f49e9080b271842340ed4c456852
[ "eps = 1e-09\nout = -np.sum(y * np.log(x + eps), axis=1).mean()\nreturn out", "eps = 1e-09\ndx = -y / (len(y) * (x + eps))\nreturn dx" ]
<|body_start_0|> eps = 1e-09 out = -np.sum(y * np.log(x + eps), axis=1).mean() return out <|end_body_0|> <|body_start_1|> eps = 1e-09 dx = -y / (len(y) * (x + eps)) return dx <|end_body_1|>
Cross entropy loss module.
CrossEntropyModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CrossEntropyModule: """Cross entropy loss module.""" def forward(self, x, y): """Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss""" <|body_0|> def backward(self, x, y): """Backward pass. Args: x: input to the mod...
stack_v2_sparse_classes_36k_train_010117
5,181
no_license
[ { "docstring": "Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss", "name": "forward", "signature": "def forward(self, x, y)" }, { "docstring": "Backward pass. Args: x: input to the module y: labels of the input Returns: dx: gradient of the loss w...
2
stack_v2_sparse_classes_30k_train_019244
Implement the Python class `CrossEntropyModule` described below. Class description: Cross entropy loss module. Method signatures and docstrings: - def forward(self, x, y): Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss - def backward(self, x, y): Backward pass. Args...
Implement the Python class `CrossEntropyModule` described below. Class description: Cross entropy loss module. Method signatures and docstrings: - def forward(self, x, y): Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss - def backward(self, x, y): Backward pass. Args...
b2cd0d67337b101f3e204e519625e1aaf3cea43b
<|skeleton|> class CrossEntropyModule: """Cross entropy loss module.""" def forward(self, x, y): """Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss""" <|body_0|> def backward(self, x, y): """Backward pass. Args: x: input to the mod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CrossEntropyModule: """Cross entropy loss module.""" def forward(self, x, y): """Forward pass. Args: x: input to the module y: labels of the input Returns: out: cross entropy loss""" eps = 1e-09 out = -np.sum(y * np.log(x + eps), axis=1).mean() return out def backward...
the_stack_v2_python_sparse
assignment_1/code/modules.py
Ivan-Yovchev/uvadlc_practicals_2019
train
0
90e03ffb126dfed8c9ede8b699f7557e3da83338
[ "pygame.sprite.Sprite.__init__(self)\nif image:\n self.image = image\nelse:\n self.image = Puff.IMAGE.copy()\nself.rect = self.image.get_rect()\nif alpha:\n self.image.set_alpha(int(alpha))\nelse:\n self.image.set_alpha(255)\nself.rect.centerx = coord[0]\nself.rect.centery = coord[1]\nself.countdown = l...
<|body_start_0|> pygame.sprite.Sprite.__init__(self) if image: self.image = image else: self.image = Puff.IMAGE.copy() self.rect = self.image.get_rect() if alpha: self.image.set_alpha(int(alpha)) else: self.image.set_alpha(2...
A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out
Puff
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alph...
stack_v2_sparse_classes_36k_train_010118
2,118
permissive
[ { "docstring": "Creates a puff of smoke coord(list) --> (x,y) center point of the puff life(int) --> frames before dissapearing (PRESET: 60 frames)(-1 = infinite) alpha(int) --> Alpha value of the surface (PRESET: fully opaque) alpha_decrease --> Alpha decrease per frame (PRESET: No decrease) image(Surface) -->...
2
stack_v2_sparse_classes_30k_train_013864
Implement the Python class `Puff` described below. Class description: A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out Method ...
Implement the Python class `Puff` described below. Class description: A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out Method ...
35b7127f9af204798615d820ec664a00eb45e1d2
<|skeleton|> class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alph...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alpha=None, alpha...
the_stack_v2_python_sparse
Puff.py
Saevon/Arkanoid
train
0
9fd2f125908c23b13157f808aa7dc788f6e5be25
[ "self.BranchLength = 0.0\nif branch_length:\n self.BranchLength = branch_length\nself.Name = name\nself.Printed = False\nself.NumChildren = 0\nself.NumChildrenPrinted = 0\nself.LastChild = None", "delimiter = '-'\npdelimiter = '+'\nif self.Printed:\n delimiter = ' '\n pdelimiter = '|'\nlast_ct = 0\nif se...
<|body_start_0|> self.BranchLength = 0.0 if branch_length: self.BranchLength = branch_length self.Name = name self.Printed = False self.NumChildren = 0 self.NumChildrenPrinted = 0 self.LastChild = None <|end_body_0|> <|body_start_1|> delimiter...
Helper to display text phyolo tree
TextNode
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextNode: """Helper to display text phyolo tree""" def __init__(self, branch_length, name): """Set up defaults""" <|body_0|> def display(self, max_dist, scale): """Display current node - should refactor this""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_010119
3,462
permissive
[ { "docstring": "Set up defaults", "name": "__init__", "signature": "def __init__(self, branch_length, name)" }, { "docstring": "Display current node - should refactor this", "name": "display", "signature": "def display(self, max_dist, scale)" } ]
2
null
Implement the Python class `TextNode` described below. Class description: Helper to display text phyolo tree Method signatures and docstrings: - def __init__(self, branch_length, name): Set up defaults - def display(self, max_dist, scale): Display current node - should refactor this
Implement the Python class `TextNode` described below. Class description: Helper to display text phyolo tree Method signatures and docstrings: - def __init__(self, branch_length, name): Set up defaults - def display(self, max_dist, scale): Display current node - should refactor this <|skeleton|> class TextNode: ...
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
<|skeleton|> class TextNode: """Helper to display text phyolo tree""" def __init__(self, branch_length, name): """Set up defaults""" <|body_0|> def display(self, max_dist, scale): """Display current node - should refactor this""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextNode: """Helper to display text phyolo tree""" def __init__(self, branch_length, name): """Set up defaults""" self.BranchLength = 0.0 if branch_length: self.BranchLength = branch_length self.Name = name self.Printed = False self.NumChildren ...
the_stack_v2_python_sparse
scripts/venv/lib/python2.7/site-packages/cogent/format/text_tree.py
sauloal/cnidaria
train
3
4c60bb1677a5ac5a61022814e06d6496222ff4ed
[ "values, outdict = BaseWidget.process_form(self, instance=instance, field=field, form=form, empty_marker=empty_marker, emptyReturnsMarker=emptyReturnsMarker)\nfor index in range(len(values)):\n item = values[index]\n min_panic = self._get_spec_value(form, item['uid'], 'minpanic')\n max_panic = self._get_sp...
<|body_start_0|> values, outdict = BaseWidget.process_form(self, instance=instance, field=field, form=form, empty_marker=empty_marker, emptyReturnsMarker=emptyReturnsMarker) for index in range(len(values)): item = values[index] min_panic = self._get_spec_value(form, item['uid'], ...
AnalysisSpecificationWidget
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnalysisSpecificationWidget: def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for AnalysisSpecsResultsField consumption. If neither hidemin nor hidemax are specified, only services which have float()able entr...
stack_v2_sparse_classes_36k_train_010120
2,735
no_license
[ { "docstring": "Return a list of dictionaries fit for AnalysisSpecsResultsField consumption. If neither hidemin nor hidemax are specified, only services which have float()able entries in result,min and max field will be included. If hidemin and/or hidemax specified, results might contain empty min and/or max fi...
2
stack_v2_sparse_classes_30k_train_017640
Implement the Python class `AnalysisSpecificationWidget` described below. Class description: Implement the AnalysisSpecificationWidget class. Method signatures and docstrings: - def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): Return a list of dictionaries fit for AnalysisSp...
Implement the Python class `AnalysisSpecificationWidget` described below. Class description: Implement the AnalysisSpecificationWidget class. Method signatures and docstrings: - def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): Return a list of dictionaries fit for AnalysisSp...
683e87144bdca23c8b5b21161797773b5e694b90
<|skeleton|> class AnalysisSpecificationWidget: def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for AnalysisSpecsResultsField consumption. If neither hidemin nor hidemax are specified, only services which have float()able entr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnalysisSpecificationWidget: def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for AnalysisSpecsResultsField consumption. If neither hidemin nor hidemax are specified, only services which have float()able entries in result,...
the_stack_v2_python_sparse
bhp/lims/browser/widgets/analysisspecificationwidget.py
tdiphale/bhp.lims-1
train
1
561f4daf5df80351697eb628ceeca0f6f434710c
[ "\"\"\"\n solution1: 构造所有的可能子序列\n 复杂度: O(N2)\n \"\"\"\nif not S:\n return 0\nresult = set([''])\nfor x in S:\n new_str = set()\n for item in result:\n new_str.add(item + x)\n for item in new_str:\n if item not in result:\n result.add(item)\nreturn len(result...
<|body_start_0|> """ solution1: 构造所有的可能子序列 复杂度: O(N2) """ if not S: return 0 result = set(['']) for x in S: new_str = set() for item in result: new_str.add(item + x) for item i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def distinctSubseqII0(self, S): """:type S: str :rtype: int""" <|body_0|> def distinctSubseqII1(self, S): """solution2: end[c]标记所有以‘c’结尾的子序列 (跟顺序无关) 若‘c’在之前的序列里没出现过,则加 end[c] = sum[end] + 1; c为新增项 若‘c’在之前的序列里出现过,end[c] = sum[end] + 1,替换掉之前的项, 因为c与其他项的组合,包含之...
stack_v2_sparse_classes_36k_train_010121
1,864
no_license
[ { "docstring": ":type S: str :rtype: int", "name": "distinctSubseqII0", "signature": "def distinctSubseqII0(self, S)" }, { "docstring": "solution2: end[c]标记所有以‘c’结尾的子序列 (跟顺序无关) 若‘c’在之前的序列里没出现过,则加 end[c] = sum[end] + 1; c为新增项 若‘c’在之前的序列里出现过,end[c] = sum[end] + 1,替换掉之前的项, 因为c与其他项的组合,包含之前以c结尾的项 一个c...
2
stack_v2_sparse_classes_30k_train_000041
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def distinctSubseqII0(self, S): :type S: str :rtype: int - def distinctSubseqII1(self, S): solution2: end[c]标记所有以‘c’结尾的子序列 (跟顺序无关) 若‘c’在之前的序列里没出现过,则加 end[c] = sum[end] + 1; c为新增项...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def distinctSubseqII0(self, S): :type S: str :rtype: int - def distinctSubseqII1(self, S): solution2: end[c]标记所有以‘c’结尾的子序列 (跟顺序无关) 若‘c’在之前的序列里没出现过,则加 end[c] = sum[end] + 1; c为新增项...
00abbb9909dc8a10f274a6e8605c665ba361fa3e
<|skeleton|> class Solution: def distinctSubseqII0(self, S): """:type S: str :rtype: int""" <|body_0|> def distinctSubseqII1(self, S): """solution2: end[c]标记所有以‘c’结尾的子序列 (跟顺序无关) 若‘c’在之前的序列里没出现过,则加 end[c] = sum[end] + 1; c为新增项 若‘c’在之前的序列里出现过,end[c] = sum[end] + 1,替换掉之前的项, 因为c与其他项的组合,包含之...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def distinctSubseqII0(self, S): """:type S: str :rtype: int""" """ solution1: 构造所有的可能子序列 复杂度: O(N2) """ if not S: return 0 result = set(['']) for x in S: new_str = set() for it...
the_stack_v2_python_sparse
01_string/06所有可能组合/940.DistinctSubsequencesII.py
harverywxu/algorithm_python
train
0
8caafb2e69682d5c6ff187dd10554eb4fc693cb5
[ "if auth_header is None or type(auth_header) != str or (not auth_header.startswith('Basic ')):\n return None\nreturn auth_header.split(' ')[1]", "if b64_auth_header is None or type(b64_auth_header) != str:\n return None\ntry:\n return base64.b64decode(b64_auth_header.encode('ascii')).decode('ascii')\nexc...
<|body_start_0|> if auth_header is None or type(auth_header) != str or (not auth_header.startswith('Basic ')): return None return auth_header.split(' ')[1] <|end_body_0|> <|body_start_1|> if b64_auth_header is None or type(b64_auth_header) != str: return None try...
BasicAuth class.
BasicAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicAuth: """BasicAuth class.""" def extract_base64_authorization_header(self, auth_header: str) -> str: """Returns Base64 of the Authorization header""" <|body_0|> def decode_base64_authorization_header(self, b64_auth_header: str) -> str: """Returns decoded val...
stack_v2_sparse_classes_36k_train_010122
1,999
no_license
[ { "docstring": "Returns Base64 of the Authorization header", "name": "extract_base64_authorization_header", "signature": "def extract_base64_authorization_header(self, auth_header: str) -> str" }, { "docstring": "Returns decoded value of a Base64 string", "name": "decode_base64_authorization...
4
stack_v2_sparse_classes_30k_train_012952
Implement the Python class `BasicAuth` described below. Class description: BasicAuth class. Method signatures and docstrings: - def extract_base64_authorization_header(self, auth_header: str) -> str: Returns Base64 of the Authorization header - def decode_base64_authorization_header(self, b64_auth_header: str) -> str...
Implement the Python class `BasicAuth` described below. Class description: BasicAuth class. Method signatures and docstrings: - def extract_base64_authorization_header(self, auth_header: str) -> str: Returns Base64 of the Authorization header - def decode_base64_authorization_header(self, b64_auth_header: str) -> str...
0aa1f87942a34efe436a8bebf95cc267cd846e04
<|skeleton|> class BasicAuth: """BasicAuth class.""" def extract_base64_authorization_header(self, auth_header: str) -> str: """Returns Base64 of the Authorization header""" <|body_0|> def decode_base64_authorization_header(self, b64_auth_header: str) -> str: """Returns decoded val...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasicAuth: """BasicAuth class.""" def extract_base64_authorization_header(self, auth_header: str) -> str: """Returns Base64 of the Authorization header""" if auth_header is None or type(auth_header) != str or (not auth_header.startswith('Basic ')): return None return a...
the_stack_v2_python_sparse
0x06-Basic_authentication/api/v1/auth/basic_auth.py
maleksal/holbertonschool-web_back_end
train
1
bc4a2db3a55671a2b192212ad1b0db2993ccb623
[ "super(LightweightConvolution2D, self).__init__()\nassert n_feat % wshare == 0\nself.wshare = wshare\nself.use_kernel_mask = use_kernel_mask\nself.dropout_rate = dropout_rate\nself.kernel_size = kernel_size\nself.padding_size = int(kernel_size / 2)\nself.linear1 = nn.Linear(n_feat, n_feat * 2)\nself.linear2 = nn.Li...
<|body_start_0|> super(LightweightConvolution2D, self).__init__() assert n_feat % wshare == 0 self.wshare = wshare self.use_kernel_mask = use_kernel_mask self.dropout_rate = dropout_rate self.kernel_size = kernel_size self.padding_size = int(kernel_size / 2) ...
Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_size (int): kernel size (length) use_kernel_mask (boo...
LightweightConvolution2D
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LightweightConvolution2D: """Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_s...
stack_v2_sparse_classes_36k_train_010123
4,229
permissive
[ { "docstring": "Construct Lightweight 2-Dimensional Convolution layer.", "name": "__init__", "signature": "def __init__(self, wshare, n_feat, dropout_rate, kernel_size, use_kernel_mask=False, use_bias=False)" }, { "docstring": "Forward of 'Lightweight 2-Dimensional Convolution'. This function ta...
2
stack_v2_sparse_classes_30k_train_011709
Implement the Python class `LightweightConvolution2D` described below. Class description: Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features drop...
Implement the Python class `LightweightConvolution2D` described below. Class description: Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features drop...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class LightweightConvolution2D: """Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LightweightConvolution2D: """Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_size (int): ke...
the_stack_v2_python_sparse
espnet/nets/pytorch_backend/transformer/lightconv2d.py
espnet/espnet
train
7,242
9f3251ec709deeea020781473d4bb072437f9d16
[ "self.extension = extension\nself.zipname = zipname\nself.temp_directory = Path('unzipped-{}'.format(zipname[:-4]))", "self.unzip_files()\nself.process_files()\nself.zip_files()", "self.temp_directory.mkdir()\nwith zipfile.ZipFile(self.zipname) as zp:\n zp.extractall(str(self.temp_directory))", "with zipfi...
<|body_start_0|> self.extension = extension self.zipname = zipname self.temp_directory = Path('unzipped-{}'.format(zipname[:-4])) <|end_body_0|> <|body_start_1|> self.unzip_files() self.process_files() self.zip_files() <|end_body_1|> <|body_start_2|> self.temp_d...
Represents process of zipping and unzipping
ZipProcessor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZipProcessor: """Represents process of zipping and unzipping""" def __init__(self, zipname, extension): """Initializes variable""" <|body_0|> def process_zip(self): """Run process""" <|body_1|> def unzip_files(self): """Unzip files""" ...
stack_v2_sparse_classes_36k_train_010124
1,313
no_license
[ { "docstring": "Initializes variable", "name": "__init__", "signature": "def __init__(self, zipname, extension)" }, { "docstring": "Run process", "name": "process_zip", "signature": "def process_zip(self)" }, { "docstring": "Unzip files", "name": "unzip_files", "signature...
4
null
Implement the Python class `ZipProcessor` described below. Class description: Represents process of zipping and unzipping Method signatures and docstrings: - def __init__(self, zipname, extension): Initializes variable - def process_zip(self): Run process - def unzip_files(self): Unzip files - def zip_files(self): Zi...
Implement the Python class `ZipProcessor` described below. Class description: Represents process of zipping and unzipping Method signatures and docstrings: - def __init__(self, zipname, extension): Initializes variable - def process_zip(self): Run process - def unzip_files(self): Unzip files - def zip_files(self): Zi...
1837d3234e5b4b5d46cd264bf4a0c4da75bfc3d2
<|skeleton|> class ZipProcessor: """Represents process of zipping and unzipping""" def __init__(self, zipname, extension): """Initializes variable""" <|body_0|> def process_zip(self): """Run process""" <|body_1|> def unzip_files(self): """Unzip files""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZipProcessor: """Represents process of zipping and unzipping""" def __init__(self, zipname, extension): """Initializes variable""" self.extension = extension self.zipname = zipname self.temp_directory = Path('unzipped-{}'.format(zipname[:-4])) def process_zip(self): ...
the_stack_v2_python_sparse
lab07-cachingWebpage-scalingZipedImage/scale-zipped-images/scale_zip.py
7ss8n/ProgrammingBasics2-Python
train
0
d65bec5d7bf6d022f0e3faabb8f4b54a381bde70
[ "self.value = value\nself.prev_node = prev_node\nself.next_node = next_node", "if not new_value:\n return False\nelse:\n if not self.value:\n self.value = new_value\n else:\n current = self\n while current.next_node:\n current = current.next_node\n current.next_node...
<|body_start_0|> self.value = value self.prev_node = prev_node self.next_node = next_node <|end_body_0|> <|body_start_1|> if not new_value: return False else: if not self.value: self.value = new_value else: curr...
Node
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Node: def __init__(self, value=None, prev_node=None, next_node=None): """Constructor for a new Node on the linked list""" <|body_0|> def add_value(self, new_value=None): """Adds a new value to the linked list""" <|body_1|> def delete(self): """De...
stack_v2_sparse_classes_36k_train_010125
4,372
permissive
[ { "docstring": "Constructor for a new Node on the linked list", "name": "__init__", "signature": "def __init__(self, value=None, prev_node=None, next_node=None)" }, { "docstring": "Adds a new value to the linked list", "name": "add_value", "signature": "def add_value(self, new_value=None...
3
null
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def __init__(self, value=None, prev_node=None, next_node=None): Constructor for a new Node on the linked list - def add_value(self, new_value=None): Adds a new value to the linked list -...
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def __init__(self, value=None, prev_node=None, next_node=None): Constructor for a new Node on the linked list - def add_value(self, new_value=None): Adds a new value to the linked list -...
27ffb6b32d6d18d279c51cfa45bf305a409be5c2
<|skeleton|> class Node: def __init__(self, value=None, prev_node=None, next_node=None): """Constructor for a new Node on the linked list""" <|body_0|> def add_value(self, new_value=None): """Adds a new value to the linked list""" <|body_1|> def delete(self): """De...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Node: def __init__(self, value=None, prev_node=None, next_node=None): """Constructor for a new Node on the linked list""" self.value = value self.prev_node = prev_node self.next_node = next_node def add_value(self, new_value=None): """Adds a new value to the linked...
the_stack_v2_python_sparse
src/daily-coding-problem/medium/sort-linked-list/sort_linked_list.py
nwthomas/code-challenges
train
2
4b828af27dba1b0203f10ad0c536c68364991282
[ "os.environ['SDL_VIDEO_CENTERED'] = '1'\npg.init()\npg.display.set_caption('Drag the Red Square')\nself.screen = pg.display.set_mode(SCREEN_SIZE)\nself.screen_rect = self.screen.get_rect()\nself.clock = pg.time.Clock()\nself.fps = 60.0\nself.done = False\nself.keys = pg.key.get_pressed()\nself.player = Character(0,...
<|body_start_0|> os.environ['SDL_VIDEO_CENTERED'] = '1' pg.init() pg.display.set_caption('Drag the Red Square') self.screen = pg.display.set_mode(SCREEN_SIZE) self.screen_rect = self.screen.get_rect() self.clock = pg.time.Clock() self.fps = 60.0 self.done ...
A control class to manage our event and game loops.
Control
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Control: """A control class to manage our event and game loops.""" def __init__(self): """Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.""" <|body_0|> def event_loop(self): """This is the event loop f...
stack_v2_sparse_classes_36k_train_010126
3,624
no_license
[ { "docstring": "Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This is the event loop for the whole program. Regardless of the complexity of a program, there ...
3
null
Implement the Python class `Control` described below. Class description: A control class to manage our event and game loops. Method signatures and docstrings: - def __init__(self): Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere. - def event_loop(self): Thi...
Implement the Python class `Control` described below. Class description: A control class to manage our event and game loops. Method signatures and docstrings: - def __init__(self): Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere. - def event_loop(self): Thi...
7fc4e0d98d06b4e28b09844babb2452e229a603c
<|skeleton|> class Control: """A control class to manage our event and game loops.""" def __init__(self): """Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.""" <|body_0|> def event_loop(self): """This is the event loop f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Control: """A control class to manage our event and game loops.""" def __init__(self): """Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.""" os.environ['SDL_VIDEO_CENTERED'] = '1' pg.init() pg.display.set_captio...
the_stack_v2_python_sparse
meks-pygame-samples/drag_text.py
pk00749/Example_Python
train
1
e81ce1a1a3ddec77988f145c8be6e1e2010c7c62
[ "action = rule['action']\nuser_id = rule.get('user_id', '*')\nroom_id = rule.get('room_id', '*')\nalias = rule.get('alias', '*')\nif action in ('allow', 'deny'):\n self.action = action\nelse:\n raise ConfigError(\"%s rules can only have action of 'allow' or 'deny'\" % (option_name,))\nself._alias_matches_all ...
<|body_start_0|> action = rule['action'] user_id = rule.get('user_id', '*') room_id = rule.get('room_id', '*') alias = rule.get('alias', '*') if action in ('allow', 'deny'): self.action = action else: raise ConfigError("%s rules can only have actio...
Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room.
_RoomDirectoryRule
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _RoomDirectoryRule: """Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room.""" def __init__(self, option_name: str, rule: JsonDict): """Args: option_name: Name of the config option this rule belongs to rule: The rule as specifi...
stack_v2_sparse_classes_36k_train_010127
5,480
permissive
[ { "docstring": "Args: option_name: Name of the config option this rule belongs to rule: The rule as specified in the config", "name": "__init__", "signature": "def __init__(self, option_name: str, rule: JsonDict)" }, { "docstring": "Tests if this rule matches the given user_id, room_id and alias...
2
null
Implement the Python class `_RoomDirectoryRule` described below. Class description: Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room. Method signatures and docstrings: - def __init__(self, option_name: str, rule: JsonDict): Args: option_name: Name of the con...
Implement the Python class `_RoomDirectoryRule` described below. Class description: Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room. Method signatures and docstrings: - def __init__(self, option_name: str, rule: JsonDict): Args: option_name: Name of the con...
d35bed8369514fe727b4fe1afb68f48cc8b2655a
<|skeleton|> class _RoomDirectoryRule: """Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room.""" def __init__(self, option_name: str, rule: JsonDict): """Args: option_name: Name of the config option this rule belongs to rule: The rule as specifi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _RoomDirectoryRule: """Helper class to test whether a room directory action is allowed, like creating an alias or publishing a room.""" def __init__(self, option_name: str, rule: JsonDict): """Args: option_name: Name of the config option this rule belongs to rule: The rule as specified in the con...
the_stack_v2_python_sparse
synapse/config/room_directory.py
matrix-org/synapse
train
12,215
4ae90d6909c1f41eb1eb5177b62e646a975fd720
[ "value = {'args': args, 'on_schedule': on_time}\nkey = JobModel.convert_name_into_job(name)\nid = self.client.api.create_changeset(key, value, targets)\nreturn id", "status = self.client.api.get_current_device_status(device_id)\nmstatus = [self.prepare_model(s) for s in status]\nfor s in mstatus:\n if s.name =...
<|body_start_0|> value = {'args': args, 'on_schedule': on_time} key = JobModel.convert_name_into_job(name) id = self.client.api.create_changeset(key, value, targets) return id <|end_body_0|> <|body_start_1|> status = self.client.api.get_current_device_status(device_id) m...
JobCollection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobCollection: def schedule(self, name, args, targets, on_time=None): """Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (list): Targets of the changeset (devices). Returns: A :py:class:`JobModel` object. Raises: :py:class:`a...
stack_v2_sparse_classes_36k_train_010128
2,691
no_license
[ { "docstring": "Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (list): Targets of the changeset (devices). Returns: A :py:class:`JobModel` object. Raises: :py:class:`adm.errors.APIError` If the server returns an error.", "name": "schedule", ...
3
null
Implement the Python class `JobCollection` described below. Class description: Implement the JobCollection class. Method signatures and docstrings: - def schedule(self, name, args, targets, on_time=None): Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (l...
Implement the Python class `JobCollection` described below. Class description: Implement the JobCollection class. Method signatures and docstrings: - def schedule(self, name, args, targets, on_time=None): Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (l...
d27b0d6ee47b9c4f320f518705074f1032fedf8a
<|skeleton|> class JobCollection: def schedule(self, name, args, targets, on_time=None): """Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (list): Targets of the changeset (devices). Returns: A :py:class:`JobModel` object. Raises: :py:class:`a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobCollection: def schedule(self, name, args, targets, on_time=None): """Schedule a new Job Args: name (str): Name of the job. args (dict): Arguments of the job as key, value. targets (list): Targets of the changeset (devices). Returns: A :py:class:`JobModel` object. Raises: :py:class:`adm.errors.APIE...
the_stack_v2_python_sparse
zdevicemanager/client/models/job.py
zerynth/core-zerynth-toolchain
train
0
94664bc0d86ea23078f31e65d3b6953f12d89f95
[ "super(CustomSchedule, self).__init__()\nself.d_model = d_model\nself.d_model = tf.cast(self.d_model, tf.float32)\nself.warmup_steps = warmup_steps", "arg1 = tf.math.rsqrt(step)\narg2 = step * self.warmup_steps ** (-1.5)\nreturn tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)" ]
<|body_start_0|> super(CustomSchedule, self).__init__() self.d_model = d_model self.d_model = tf.cast(self.d_model, tf.float32) self.warmup_steps = warmup_steps <|end_body_0|> <|body_start_1|> arg1 = tf.math.rsqrt(step) arg2 = step * self.warmup_steps ** (-1.5) r...
for decaying the lrate
CustomSchedule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomSchedule: """for decaying the lrate""" def __init__(self, d_model, warmup_steps=4000): """initializer""" <|body_0|> def __call__(self, step): """call method""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(CustomSchedule, self).__init...
stack_v2_sparse_classes_36k_train_010129
3,937
no_license
[ { "docstring": "initializer", "name": "__init__", "signature": "def __init__(self, d_model, warmup_steps=4000)" }, { "docstring": "call method", "name": "__call__", "signature": "def __call__(self, step)" } ]
2
stack_v2_sparse_classes_30k_train_003204
Implement the Python class `CustomSchedule` described below. Class description: for decaying the lrate Method signatures and docstrings: - def __init__(self, d_model, warmup_steps=4000): initializer - def __call__(self, step): call method
Implement the Python class `CustomSchedule` described below. Class description: for decaying the lrate Method signatures and docstrings: - def __init__(self, d_model, warmup_steps=4000): initializer - def __call__(self, step): call method <|skeleton|> class CustomSchedule: """for decaying the lrate""" def _...
d86b0e0cae2dd07c761f84a493abc895007873ee
<|skeleton|> class CustomSchedule: """for decaying the lrate""" def __init__(self, d_model, warmup_steps=4000): """initializer""" <|body_0|> def __call__(self, step): """call method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomSchedule: """for decaying the lrate""" def __init__(self, d_model, warmup_steps=4000): """initializer""" super(CustomSchedule, self).__init__() self.d_model = d_model self.d_model = tf.cast(self.d_model, tf.float32) self.warmup_steps = warmup_steps def _...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-train.py
mag389/holbertonschool-machine_learning
train
2
dcad37a8101e1054ceb0404e5dcec42041a1f2a3
[ "BaseController.__init__(self, veh_id, car_following_params, delay=delay, fail_safe=fail_safe, noise=noise)\nself.v_desired = v0\nself.acc = acc\nself.b = b\nself.b_l = b_l\nself.s0 = s0\nself.tau = tau", "v = env.k.vehicle.get_speed(self.veh_id)\nh = env.k.vehicle.get_headway(self.veh_id)\nv_l = env.k.vehicle.ge...
<|body_start_0|> BaseController.__init__(self, veh_id, car_following_params, delay=delay, fail_safe=fail_safe, noise=noise) self.v_desired = v0 self.acc = acc self.b = b self.b_l = b_l self.s0 = s0 self.tau = tau <|end_body_0|> <|body_start_1|> v = env.k....
Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseController for usage example. Attributes ---------- ...
GippsController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GippsController: """Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseControlle...
stack_v2_sparse_classes_36k_train_010130
17,548
permissive
[ { "docstring": "Instantiate a Gipps' controller.", "name": "__init__", "signature": "def __init__(self, veh_id, car_following_params=None, v0=30, acc=1.5, b=-1, b_l=-1, s0=2, tau=1, delay=0, noise=0, fail_safe=None)" }, { "docstring": "See parent class.", "name": "get_accel", "signature"...
2
stack_v2_sparse_classes_30k_train_008078
Implement the Python class `GippsController` described below. Class description: Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChap...
Implement the Python class `GippsController` described below. Class description: Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChap...
badac3da17f04d8d8ae5691ee8ba2af9d56fac35
<|skeleton|> class GippsController: """Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseControlle...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GippsController: """Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseController for usage e...
the_stack_v2_python_sparse
flow/controllers/car_following_models.py
parthjaggi/flow
train
6
00c378a2f62a81f689737e0ab72de5577b10c6b2
[ "super(CLI, self).__init__(protocol_attr, rse_settings, logger=logger)\nif not logger:\n logger = logging.getLogger('%s.null' % __name__)\nself.logger = logger", "dest = os.path.abspath(dest)\nif ':' not in dest:\n dest = 'file://' + dest\ncmd = 'gfal-copy -vf -p -t %s -T %s %s %s' % (transfer_timeout, tran...
<|body_start_0|> super(CLI, self).__init__(protocol_attr, rse_settings, logger=logger) if not logger: logger = logging.getLogger('%s.null' % __name__) self.logger = logger <|end_body_0|> <|body_start_1|> dest = os.path.abspath(dest) if ':' not in dest: de...
Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands.
CLI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CLI: """Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands.""" def __init__(self, protocol_attr, rse_settings, logger=logging.log): """Initializes the object with information about the referred RSE. :param props: Properties derived from the RSE Reposi...
stack_v2_sparse_classes_36k_train_010131
29,035
permissive
[ { "docstring": "Initializes the object with information about the referred RSE. :param props: Properties derived from the RSE Repository", "name": "__init__", "signature": "def __init__(self, protocol_attr, rse_settings, logger=logging.log)" }, { "docstring": "Provides access to files stored ins...
3
null
Implement the Python class `CLI` described below. Class description: Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands. Method signatures and docstrings: - def __init__(self, protocol_attr, rse_settings, logger=logging.log): Initializes the object with information about the referred ...
Implement the Python class `CLI` described below. Class description: Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands. Method signatures and docstrings: - def __init__(self, protocol_attr, rse_settings, logger=logging.log): Initializes the object with information about the referred ...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class CLI: """Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands.""" def __init__(self, protocol_attr, rse_settings, logger=logging.log): """Initializes the object with information about the referred RSE. :param props: Properties derived from the RSE Reposi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CLI: """Implementing access to RSEs using the srm protocol through CLI with 'gfal' commands.""" def __init__(self, protocol_attr, rse_settings, logger=logging.log): """Initializes the object with information about the referred RSE. :param props: Properties derived from the RSE Repository""" ...
the_stack_v2_python_sparse
lib/rucio/rse/protocols/gfal.py
rucio/rucio
train
232
23367faf94eea5a02c092d577c9e7764d4ed1799
[ "super().__init__(**kwargs)\nself.dirty_path = os.path.expanduser(path)\nreturn", "params = {}\nif self._mimetype:\n params['mime'] = self._mimetype\nif self._name:\n params['name'] = self._name\nreturn 'file://{path}{params}'.format(path=self.quote(self.dirty_path), params='?{}'.format(self.urlencode(param...
<|body_start_0|> super().__init__(**kwargs) self.dirty_path = os.path.expanduser(path) return <|end_body_0|> <|body_start_1|> params = {} if self._mimetype: params['mime'] = self._mimetype if self._name: params['name'] = self._name return ...
A wrapper for File based attachment sources
AttachFile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttachFile: """A wrapper for File based attachment sources""" def __init__(self, path, **kwargs): """Initialize Local File Attachment Object""" <|body_0|> def url(self, privacy=False, *args, **kwargs): """Returns the URL built dynamically based on specified argum...
stack_v2_sparse_classes_36k_train_010132
4,970
permissive
[ { "docstring": "Initialize Local File Attachment Object", "name": "__init__", "signature": "def __init__(self, path, **kwargs)" }, { "docstring": "Returns the URL built dynamically based on specified arguments.", "name": "url", "signature": "def url(self, privacy=False, *args, **kwargs)"...
4
null
Implement the Python class `AttachFile` described below. Class description: A wrapper for File based attachment sources Method signatures and docstrings: - def __init__(self, path, **kwargs): Initialize Local File Attachment Object - def url(self, privacy=False, *args, **kwargs): Returns the URL built dynamically bas...
Implement the Python class `AttachFile` described below. Class description: A wrapper for File based attachment sources Method signatures and docstrings: - def __init__(self, path, **kwargs): Initialize Local File Attachment Object - def url(self, privacy=False, *args, **kwargs): Returns the URL built dynamically bas...
be3baed7e3d33bae973f1714df4ebbf65aa33f85
<|skeleton|> class AttachFile: """A wrapper for File based attachment sources""" def __init__(self, path, **kwargs): """Initialize Local File Attachment Object""" <|body_0|> def url(self, privacy=False, *args, **kwargs): """Returns the URL built dynamically based on specified argum...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttachFile: """A wrapper for File based attachment sources""" def __init__(self, path, **kwargs): """Initialize Local File Attachment Object""" super().__init__(**kwargs) self.dirty_path = os.path.expanduser(path) return def url(self, privacy=False, *args, **kwargs): ...
the_stack_v2_python_sparse
apprise/attachment/AttachFile.py
caronc/apprise
train
8,426
75c38782e22c39493cdf913402a5fa2e072334b7
[ "self.X = X\nself.K = K\nself.centrX = []\nself.C = []\nself.U = []\nself.Z = []\nself.centrX = self._centralized()\nself.C = self._cov()\nself.U = self._U()\nself.Z = self._Z()", "print('样本矩阵X:\\n', self.X)\ncentrX = []\nmean = np.array([np.mean(attr) for attr in self.X.T])\nprint('样本集的特征均值:\\n', mean)\ncentrX =...
<|body_start_0|> self.X = X self.K = K self.centrX = [] self.C = [] self.U = [] self.Z = [] self.centrX = self._centralized() self.C = self._cov() self.U = self._U() self.Z = self._Z() <|end_body_0|> <|body_start_1|> print('样本矩阵X:\...
用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征
CPCA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CPCA: """用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征""" def __init__(self, X, K): """:param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶""" <|body_0|> def _centralized(self): """矩阵X的中心化""" <|body_1|> def _cov(self): """求样本矩阵X的协方差矩阵C...
stack_v2_sparse_classes_36k_train_010133
3,330
no_license
[ { "docstring": ":param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶", "name": "__init__", "signature": "def __init__(self, X, K)" }, { "docstring": "矩阵X的中心化", "name": "_centralized", "signature": "def _centralized(self)" }, { "docstring": "求样本矩阵X的协方差矩阵C", "name": "_cov", "sign...
5
null
Implement the Python class `CPCA` described below. Class description: 用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征 Method signatures and docstrings: - def __init__(self, X, K): :param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶 - def _centralized(self): 矩阵X的中心化 - def _cov(self): 求样本矩阵X的协方差矩阵C - def _U(self)...
Implement the Python class `CPCA` described below. Class description: 用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征 Method signatures and docstrings: - def __init__(self, X, K): :param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶 - def _centralized(self): 矩阵X的中心化 - def _cov(self): 求样本矩阵X的协方差矩阵C - def _U(self)...
f2a1b2f8b6b292815d92a294d49954616d3624d5
<|skeleton|> class CPCA: """用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征""" def __init__(self, X, K): """:param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶""" <|body_0|> def _centralized(self): """矩阵X的中心化""" <|body_1|> def _cov(self): """求样本矩阵X的协方差矩阵C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CPCA: """用PCA求样本矩阵X的K阶降维矩阵Z Note:请保证输入的样本矩阵X shape=(m, n),m行样例,n个特征""" def __init__(self, X, K): """:param X,训练样本矩阵X :param K,X的降维矩阵的阶数,即X要特征降维成k阶""" self.X = X self.K = K self.centrX = [] self.C = [] self.U = [] self.Z = [] self.centrX = se...
the_stack_v2_python_sparse
47+洪杰+上海/第三周/PCA_numpy_detail.py
Yang-chen205/badou-Turing
train
1
7b63555531bf5c131e83c747dedb5da57e05de29
[ "super().__init__()\nself.layers = nn.ModuleList(map(lambda x: AttentionLayer(**attention_layer), range(n_layers)))\npositional_encoding = position_encoding_init(max_len, features)\nself.register_buffer('positional_encoding', positional_encoding)\nself.p2x = nn.Linear(features, features * 2)", "gamma, beta = self...
<|body_start_0|> super().__init__() self.layers = nn.ModuleList(map(lambda x: AttentionLayer(**attention_layer), range(n_layers))) positional_encoding = position_encoding_init(max_len, features) self.register_buffer('positional_encoding', positional_encoding) self.p2x = nn.Linear...
Residual attention stacks based on the Attention Is All You Need paper
ResidualAttentionEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResidualAttentionEncoder: """Residual attention stacks based on the Attention Is All You Need paper""" def __init__(self, features, attention_layer, max_len=200, n_layers=3): """features - the number of features per parameter c_features - the number of side conditioning features per ...
stack_v2_sparse_classes_36k_train_010134
2,486
permissive
[ { "docstring": "features - the number of features per parameter c_features - the number of side conditioning features per batch item attention_layer - a dictionary containing instantiation parameters for the AttentionLayer module max_len - the maximum needed size of the positional encodings n_layers - number of...
2
stack_v2_sparse_classes_30k_train_001440
Implement the Python class `ResidualAttentionEncoder` described below. Class description: Residual attention stacks based on the Attention Is All You Need paper Method signatures and docstrings: - def __init__(self, features, attention_layer, max_len=200, n_layers=3): features - the number of features per parameter c...
Implement the Python class `ResidualAttentionEncoder` described below. Class description: Residual attention stacks based on the Attention Is All You Need paper Method signatures and docstrings: - def __init__(self, features, attention_layer, max_len=200, n_layers=3): features - the number of features per parameter c...
327844cea18a6dfe35e0dc8f5de0832343487366
<|skeleton|> class ResidualAttentionEncoder: """Residual attention stacks based on the Attention Is All You Need paper""" def __init__(self, features, attention_layer, max_len=200, n_layers=3): """features - the number of features per parameter c_features - the number of side conditioning features per ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResidualAttentionEncoder: """Residual attention stacks based on the Attention Is All You Need paper""" def __init__(self, features, attention_layer, max_len=200, n_layers=3): """features - the number of features per parameter c_features - the number of side conditioning features per batch item at...
the_stack_v2_python_sparse
neuralDX7/models/attention/attention_encoder.py
jGambit/NeuralDX7
train
0
199689dc56fd6fd4410d7620620842f97fb43cf0
[ "self.num_feat_per_dim = num_feat_per_dim\nself.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))\nself.freq = to.randn(num_feat_per_dim, inp_dim)\nif not isinstance(bandwidth, to.Tensor):\n bandwidth = to.from_numpy(np.asanyarray(bandwidth))\nself.freq *= to.sqrt(to.tensor(2.0) / atleast_2D(bandwidth))\nself.s...
<|body_start_0|> self.num_feat_per_dim = num_feat_per_dim self.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim)) self.freq = to.randn(num_feat_per_dim, inp_dim) if not isinstance(bandwidth, to.Tensor): bandwidth = to.from_numpy(np.asanyarray(bandwidth)) self.freq *= ...
Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
RandFourierFeat
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandFourierFeat: """Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007""" def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: [float, np.ndarray, to.Tensor]): """Gaussian kernel: $k(x,y) = \\exp...
stack_v2_sparse_classes_36k_train_010135
13,729
permissive
[ { "docstring": "Gaussian kernel: $k(x,y) = \\\\exp(-\\\\sigma**2 / (2*d) * ||x-y||^2)$ Sample from $\\\\mathcal{N}(0,1)$ and scale the result by $\\\\sigma / \\\\sqrt{2*d}$ :param inp_dim: flat dimension of the inputs i.e. the observations, called $d$ in [1] :param num_feat_per_dim: number of random Fourier fea...
2
null
Implement the Python class `RandFourierFeat` described below. Class description: Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007 Method signatures and docstrings: - def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: [float, ...
Implement the Python class `RandFourierFeat` described below. Class description: Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007 Method signatures and docstrings: - def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: [float, ...
a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5
<|skeleton|> class RandFourierFeat: """Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007""" def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: [float, np.ndarray, to.Tensor]): """Gaussian kernel: $k(x,y) = \\exp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandFourierFeat: """Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007""" def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: [float, np.ndarray, to.Tensor]): """Gaussian kernel: $k(x,y) = \\exp(-\\sigma**2 ...
the_stack_v2_python_sparse
Pyrado/pyrado/policies/features.py
jacarvalho/SimuRLacra
train
0
5a7342122b64427f7e2a282639173fd793391f3f
[ "super(UserExtended, self).__init__(parent=parent)\nself.applicationInfoWidget = QtWidgets.QLabel()\nself._userId = userId\nself._applications = applications\nself.setLayout(QtWidgets.QVBoxLayout())\nself.user = User(name, userId, group=None, applications=applications)\nself.layout().addWidget(self.user)\nself.layo...
<|body_start_0|> super(UserExtended, self).__init__(parent=parent) self.applicationInfoWidget = QtWidgets.QLabel() self._userId = userId self._applications = applications self.setLayout(QtWidgets.QVBoxLayout()) self.user = User(name, userId, group=None, applications=appli...
Extended user information.
UserExtended
[ "Apache-2.0", "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserExtended: """Extended user information.""" def __init__(self, name, userId, applications, group=None, parent=None): """Initialise widget with initial component *value* and *parent*.""" <|body_0|> def updateInformation(self, name, userId, applications): """Upd...
stack_v2_sparse_classes_36k_train_010136
7,036
permissive
[ { "docstring": "Initialise widget with initial component *value* and *parent*.", "name": "__init__", "signature": "def __init__(self, name, userId, applications, group=None, parent=None)" }, { "docstring": "Update widget with *name*, *userId* and *applications*.", "name": "updateInformation"...
2
stack_v2_sparse_classes_30k_train_004528
Implement the Python class `UserExtended` described below. Class description: Extended user information. Method signatures and docstrings: - def __init__(self, name, userId, applications, group=None, parent=None): Initialise widget with initial component *value* and *parent*. - def updateInformation(self, name, userI...
Implement the Python class `UserExtended` described below. Class description: Extended user information. Method signatures and docstrings: - def __init__(self, name, userId, applications, group=None, parent=None): Initialise widget with initial component *value* and *parent*. - def updateInformation(self, name, userI...
f55f52787484fcf931c4653e7e241791f052c04f
<|skeleton|> class UserExtended: """Extended user information.""" def __init__(self, name, userId, applications, group=None, parent=None): """Initialise widget with initial component *value* and *parent*.""" <|body_0|> def updateInformation(self, name, userId, applications): """Upd...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserExtended: """Extended user information.""" def __init__(self, name, userId, applications, group=None, parent=None): """Initialise widget with initial component *value* and *parent*.""" super(UserExtended, self).__init__(parent=parent) self.applicationInfoWidget = QtWidgets.QLa...
the_stack_v2_python_sparse
source/ftrack_connect/ui/widget/user.py
IngenuityEngine/ftrack-connect
train
0
b62173335183be65b5f41cc1779a5b84b3e2cbfb
[ "super(IQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=...
<|body_start_0|> super(IQN, self).__init__() obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape)) if head_hidden_size is None: head_hidden_size = encoder_hidden_size_list[-1] if isinstance(obs_shape, int) or len(obs_shape) == 1: self.encoder = FCE...
IQN
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[n...
stack_v2_sparse_classes_36k_train_010137
30,380
permissive
[ { "docstring": "Overview: Init the IQN Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to p...
2
stack_v2_sparse_classes_30k_train_006548
Implement the Python class `IQN` described below. Class description: Implement the IQN class. Method signatures and docstrings: - def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None,...
Implement the Python class `IQN` described below. Class description: Implement the IQN class. Method signatures and docstrings: - def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None,...
eb483fa6e46602d58c8e7d2ca1e566adca28e703
<|skeleton|> class IQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IQN: def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[nn.Module]=nn.R...
the_stack_v2_python_sparse
ding/model/template/q_learning.py
shengxuesun/DI-engine
train
1
0d134d5aeb37a1cdb23591dab954b13759e1bb7b
[ "if isinstance(data, str):\n try:\n data = yaml.safe_load(data)\n except Exception:\n pass\nreturn data", "dtype = TYPES.UNKNOWN\nif pd.isnull(typed_data):\n dtype = TYPES.NULL\nelif isinstance(typed_data, bool):\n dtype = TYPES.BOOLEAN\nelif isinstance(typed_data, FLOAT_TYPES):\n dty...
<|body_start_0|> if isinstance(data, str): try: data = yaml.safe_load(data) except Exception: pass return data <|end_body_0|> <|body_start_1|> dtype = TYPES.UNKNOWN if pd.isnull(typed_data): dtype = TYPES.NULL e...
A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys())))
TypedDataConverter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TypedDataConverter: """A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys())))""" def convert(data): """Convert `data` to a typed value If a `data` is a str...
stack_v2_sparse_classes_36k_train_010138
2,137
permissive
[ { "docstring": "Convert `data` to a typed value If a `data` is a string, parse `data` with yaml. Else, return `data` unchanged Note: this method is very slow, since it relies on the complex and python-based implementation of yaml.", "name": "convert", "signature": "def convert(data)" }, { "docst...
2
stack_v2_sparse_classes_30k_val_000004
Implement the Python class `TypedDataConverter` described below. Class description: A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys()))) Method signatures and docstrings: - def convert(da...
Implement the Python class `TypedDataConverter` described below. Class description: A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys()))) Method signatures and docstrings: - def convert(da...
f71cc98a250c68365ee19b15f7b1eba72677209a
<|skeleton|> class TypedDataConverter: """A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys())))""" def convert(data): """Convert `data` to a typed value If a `data` is a str...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TypedDataConverter: """A class to coerce types on data. To see available types: .. code-block:: python >>> from whylogs.core.types.typeddataconverter import TYPES >>> print("\\n".join(sorted(TYPES.keys())))""" def convert(data): """Convert `data` to a typed value If a `data` is a string, parse `d...
the_stack_v2_python_sparse
src/whylogs/core/types/typeddataconverter.py
valer-whylabs/whylogs
train
0
05d5e58eecd206a5be107e6939df042a2ec5d78b
[ "super(ItemModelMLP, self).__init__()\nself._input_embedding_dimension = input_embedding_dimension\nself.item_input_embedding = tf.keras.layers.Embedding(vocab_size, input_embedding_dimension, name='item_embedding', embeddings_initializer=tf.keras.initializers.RandomUniform(minval=-0.1, maxval=0.1))\nself.item_mode...
<|body_start_0|> super(ItemModelMLP, self).__init__() self._input_embedding_dimension = input_embedding_dimension self.item_input_embedding = tf.keras.layers.Embedding(vocab_size, input_embedding_dimension, name='item_embedding', embeddings_initializer=tf.keras.initializers.RandomUniform(minval=...
An MLP model that can be used as an item tower.
ItemModelMLP
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ItemModelMLP: """An MLP model that can be used as an item tower.""" def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): """Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user represent...
stack_v2_sparse_classes_36k_train_010139
2,480
permissive
[ { "docstring": "Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user representation. vocab_size: The vocabulary size for input tokens/items. input_embedding_dimension: The embedding dimension for input tokens/items. num_layers: Number of layers in the MLP. dropou...
2
stack_v2_sparse_classes_30k_train_002819
Implement the Python class `ItemModelMLP` described below. Class description: An MLP model that can be used as an item tower. Method signatures and docstrings: - def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): Initializes the parameteric attention model. Args: out...
Implement the Python class `ItemModelMLP` described below. Class description: An MLP model that can be used as an item tower. Method signatures and docstrings: - def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): Initializes the parameteric attention model. Args: out...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ItemModelMLP: """An MLP model that can be used as an item tower.""" def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): """Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user represent...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ItemModelMLP: """An MLP model that can be used as an item tower.""" def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): """Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user representation. vocab_...
the_stack_v2_python_sparse
multiple_user_representations/models/mlp_item_model.py
Jimmy-INL/google-research
train
1
ce4fb20f945c73eeacb94de47603e434754a23fd
[ "if filters is None:\n filters = {}\nresponse = self.client.get(self.list_url, filters, format='json')\nself.assertEqual(response.status_code, 200)\nreturn response.data", "response = self.do_list()\nself.assertEqual(len(response), 0)\nresponse = self.do_list({'item': 10})\nresponse = self.do_list({'item': 100...
<|body_start_0|> if filters is None: filters = {} response = self.client.get(self.list_url, filters, format='json') self.assertEqual(response.status_code, 200) return response.data <|end_body_0|> <|body_start_1|> response = self.do_list() self.assertEqual(len...
Tests for the StockItem TestReport templates.
TestReportTests
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestReportTests: """Tests for the StockItem TestReport templates.""" def do_list(self, filters=None): """Helper function to request list of labels with provided filters""" <|body_0|> def test_list(self): """Test the API list endpoint""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_010140
1,475
permissive
[ { "docstring": "Helper function to request list of labels with provided filters", "name": "do_list", "signature": "def do_list(self, filters=None)" }, { "docstring": "Test the API list endpoint", "name": "test_list", "signature": "def test_list(self)" } ]
2
null
Implement the Python class `TestReportTests` described below. Class description: Tests for the StockItem TestReport templates. Method signatures and docstrings: - def do_list(self, filters=None): Helper function to request list of labels with provided filters - def test_list(self): Test the API list endpoint
Implement the Python class `TestReportTests` described below. Class description: Tests for the StockItem TestReport templates. Method signatures and docstrings: - def do_list(self, filters=None): Helper function to request list of labels with provided filters - def test_list(self): Test the API list endpoint <|skele...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestReportTests: """Tests for the StockItem TestReport templates.""" def do_list(self, filters=None): """Helper function to request list of labels with provided filters""" <|body_0|> def test_list(self): """Test the API list endpoint""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestReportTests: """Tests for the StockItem TestReport templates.""" def do_list(self, filters=None): """Helper function to request list of labels with provided filters""" if filters is None: filters = {} response = self.client.get(self.list_url, filters, format='json'...
the_stack_v2_python_sparse
InvenTree/label/test_api.py
inventree/InvenTree
train
3,077
4a0dc7be60ff96c3a52cde3d05cd70679b6f8b20
[ "self.domain = domain\nself.ip = ip\nself.ucenter = ucenter\nself.user = user\nself.password = password\nself.server = Server(self.ip, get_info=ALL)\nself.conn = Connection(self.server, user=self.domain + '\\\\' + self.user, password=self.password, auto_bind=True, authentication=NTLM)", "att_list = ['displayName'...
<|body_start_0|> self.domain = domain self.ip = ip self.ucenter = ucenter self.user = user self.password = password self.server = Server(self.ip, get_info=ALL) self.conn = Connection(self.server, user=self.domain + '\\' + self.user, password=self.password, auto_bi...
AD域操作
Adoper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Adoper: """AD域操作""" def __init__(self, domain, ip, ucenter, user, password): """:param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:""" <|body_0|> def searchuser(self, orgunit): """:param orgunit: 组织单...
stack_v2_sparse_classes_36k_train_010141
4,132
no_license
[ { "docstring": ":param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:", "name": "__init__", "signature": "def __init__(self, domain, ip, ucenter, user, password)" }, { "docstring": ":param orgunit: 组织单元名,格式为aaa.bbb 即bbb组织下的aaa组织,不包含域地...
4
stack_v2_sparse_classes_30k_train_010626
Implement the Python class `Adoper` described below. Class description: AD域操作 Method signatures and docstrings: - def __init__(self, domain, ip, ucenter, user, password): :param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn: - def searchuser(self, orgunit)...
Implement the Python class `Adoper` described below. Class description: AD域操作 Method signatures and docstrings: - def __init__(self, domain, ip, ucenter, user, password): :param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn: - def searchuser(self, orgunit)...
2a733b34f337d4497051660f473a4cfb977fc15b
<|skeleton|> class Adoper: """AD域操作""" def __init__(self, domain, ip, ucenter, user, password): """:param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:""" <|body_0|> def searchuser(self, orgunit): """:param orgunit: 组织单...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Adoper: """AD域操作""" def __init__(self, domain, ip, ucenter, user, password): """:param domain:域名,格式为xxx.xxx.xxx :param ip:服务器地址,格式为域名xxx.xxx.xxx :param user:管理账户 :param password:密码 :param basedn:""" self.domain = domain self.ip = ip self.ucenter = ucenter self.user...
the_stack_v2_python_sparse
VMwareAutoApi/kdldapapi/ldaptool/adoper.py
vkhaibao/PyProject
train
1
7bc7a81f1d601bbf60f793307cc49475c38fc110
[ "ai = float('INF')\nfor j in range(len(nums) - 1):\n ai = min(ai, nums[j])\n for k in range(j + 1, len(nums)):\n if nums[k] > ai and nums[k] < nums[j]:\n return True\nreturn False", "if len(nums) < 3:\n return False\nintervals = []\ns = 0\nfor i in range(1, len(nums)):\n if nums[i] <...
<|body_start_0|> ai = float('INF') for j in range(len(nums) - 1): ai = min(ai, nums[j]) for k in range(j + 1, len(nums)): if nums[k] > ai and nums[k] < nums[j]: return True return False <|end_body_0|> <|body_start_1|> if len(nu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find132pattern_brute_force_optimize(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def find132pattern_record_intervals(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def find132pattern_nlogn(self, nums): ...
stack_v2_sparse_classes_36k_train_010142
2,996
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "find132pattern_brute_force_optimize", "signature": "def find132pattern_brute_force_optimize(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "find132pattern_record_intervals", "signature": "def find...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find132pattern_brute_force_optimize(self, nums): :type nums: List[int] :rtype: bool - def find132pattern_record_intervals(self, nums): :type nums: List[int] :rtype: bool - de...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find132pattern_brute_force_optimize(self, nums): :type nums: List[int] :rtype: bool - def find132pattern_record_intervals(self, nums): :type nums: List[int] :rtype: bool - de...
0e99f9a5226507706b3ee66fd04bae813755ef40
<|skeleton|> class Solution: def find132pattern_brute_force_optimize(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def find132pattern_record_intervals(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def find132pattern_nlogn(self, nums): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def find132pattern_brute_force_optimize(self, nums): """:type nums: List[int] :rtype: bool""" ai = float('INF') for j in range(len(nums) - 1): ai = min(ai, nums[j]) for k in range(j + 1, len(nums)): if nums[k] > ai and nums[k] < nums[j]...
the_stack_v2_python_sparse
medium/heapstack/test_456_132_Pattern.py
wuxu1019/leetcode_sophia
train
1
ada6b8f20ce70a8e13fcdc0109a4dc0d66a4bf96
[ "super(Player, self).__init__()\nself.width = 75\nself.height = 15\nself.image = pygame.Surface([self.width, self.height])\nself.image.fill(white)\nself.rect = self.image.get_rect()\nself.screenheight = pygame.display.get_surface().get_height()\nself.screenwidth = pygame.display.get_surface().get_width()\nself.rect...
<|body_start_0|> super(Player, self).__init__() self.width = 75 self.height = 15 self.image = pygame.Surface([self.width, self.height]) self.image.fill(white) self.rect = self.image.get_rect() self.screenheight = pygame.display.get_surface().get_height() s...
This class represents the bar at the bottom that the player controls.
Player
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Player: """This class represents the bar at the bottom that the player controls.""" def __init__(self): """Constructor for Player.""" <|body_0|> def update(self, vel): """Update the player position.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010143
15,458
no_license
[ { "docstring": "Constructor for Player.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Update the player position.", "name": "update", "signature": "def update(self, vel)" } ]
2
stack_v2_sparse_classes_30k_train_019821
Implement the Python class `Player` described below. Class description: This class represents the bar at the bottom that the player controls. Method signatures and docstrings: - def __init__(self): Constructor for Player. - def update(self, vel): Update the player position.
Implement the Python class `Player` described below. Class description: This class represents the bar at the bottom that the player controls. Method signatures and docstrings: - def __init__(self): Constructor for Player. - def update(self, vel): Update the player position. <|skeleton|> class Player: """This cla...
4419e1237986416379618981c7136dabed995a58
<|skeleton|> class Player: """This class represents the bar at the bottom that the player controls.""" def __init__(self): """Constructor for Player.""" <|body_0|> def update(self, vel): """Update the player position.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Player: """This class represents the bar at the bottom that the player controls.""" def __init__(self): """Constructor for Player.""" super(Player, self).__init__() self.width = 75 self.height = 15 self.image = pygame.Surface([self.width, self.height]) self...
the_stack_v2_python_sparse
project-3/breakout.py
kajal-puri/game-ai-bonn-ss18
train
0
4812224be3f79bdeb9b29422ef2e3aded8352afc
[ "self.clear_table()\nself.unhinge_db()\nself.logger.info('Vacuum analyzing tables now that db is unhinged')\nself.execute('VACUUM ANALYZE;')\nself.logger.info('Creating mrt_w_roas')\nsql = 'CREATE UNLOGGED TABLE IF NOT EXISTS\\n mrt_w_roas AS (\\n SELECT DISTINCT ON (m.prefix, m.as_path, m...
<|body_start_0|> self.clear_table() self.unhinge_db() self.logger.info('Vacuum analyzing tables now that db is unhinged') self.execute('VACUUM ANALYZE;') self.logger.info('Creating mrt_w_roas') sql = 'CREATE UNLOGGED TABLE IF NOT EXISTS\n mrt_w_roas AS (\n ...
Announcements table class
MRT_W_Roas_Table
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MRT_W_Roas_Table: """Announcements table class""" def _create_tables(self): """Creates tables if they do not exist""" <|body_0|> def clear_table(self): """Clears the tables. Should be called at the start of every run""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_010144
2,215
permissive
[ { "docstring": "Creates tables if they do not exist", "name": "_create_tables", "signature": "def _create_tables(self)" }, { "docstring": "Clears the tables. Should be called at the start of every run", "name": "clear_table", "signature": "def clear_table(self)" } ]
2
stack_v2_sparse_classes_30k_test_000448
Implement the Python class `MRT_W_Roas_Table` described below. Class description: Announcements table class Method signatures and docstrings: - def _create_tables(self): Creates tables if they do not exist - def clear_table(self): Clears the tables. Should be called at the start of every run
Implement the Python class `MRT_W_Roas_Table` described below. Class description: Announcements table class Method signatures and docstrings: - def _create_tables(self): Creates tables if they do not exist - def clear_table(self): Clears the tables. Should be called at the start of every run <|skeleton|> class MRT_W...
91c92584b31bd128d818c7fee86c738367c0712e
<|skeleton|> class MRT_W_Roas_Table: """Announcements table class""" def _create_tables(self): """Creates tables if they do not exist""" <|body_0|> def clear_table(self): """Clears the tables. Should be called at the start of every run""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MRT_W_Roas_Table: """Announcements table class""" def _create_tables(self): """Creates tables if they do not exist""" self.clear_table() self.unhinge_db() self.logger.info('Vacuum analyzing tables now that db is unhinged') self.execute('VACUUM ANALYZE;') se...
the_stack_v2_python_sparse
lib_bgp_data/forecast/tables.py
jfuruness/lib_bgp_data
train
16
5e474669e014a54dde3bd14b3005e5c8f704ac02
[ "super(DeviceDriverTest, self).setUp()\nself.build_client = mock.MagicMock()\nself.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client)\nself.storage_client = mock.MagicMock()\nself.Patch(gstorage_client, 'StorageClient', return_value=self.storage_client)\nself.compute_client = mock.Mag...
<|body_start_0|> super(DeviceDriverTest, self).setUp() self.build_client = mock.MagicMock() self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client) self.storage_client = mock.MagicMock() self.Patch(gstorage_client, 'StorageClient', return_value=self...
Test device_driver.
DeviceDriverTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceDriverTest: """Test device_driver.""" def setUp(self): """Set up the test.""" <|body_0|> def testCreateGCETypeAVD(self): """Test CreateGCETypeAVD.""" <|body_1|> def testCreateGCETypeAVDInternalIP(self): """Test CreateGCETypeAVD with int...
stack_v2_sparse_classes_36k_train_010145
6,901
permissive
[ { "docstring": "Set up the test.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test CreateGCETypeAVD.", "name": "testCreateGCETypeAVD", "signature": "def testCreateGCETypeAVD(self)" }, { "docstring": "Test CreateGCETypeAVD with internal IP.", "name": "t...
4
null
Implement the Python class `DeviceDriverTest` described below. Class description: Test device_driver. Method signatures and docstrings: - def setUp(self): Set up the test. - def testCreateGCETypeAVD(self): Test CreateGCETypeAVD. - def testCreateGCETypeAVDInternalIP(self): Test CreateGCETypeAVD with internal IP. - def...
Implement the Python class `DeviceDriverTest` described below. Class description: Test device_driver. Method signatures and docstrings: - def setUp(self): Set up the test. - def testCreateGCETypeAVD(self): Test CreateGCETypeAVD. - def testCreateGCETypeAVDInternalIP(self): Test CreateGCETypeAVD with internal IP. - def...
78a61ca023cbf1a0cecfef8b97df2b274ac3a988
<|skeleton|> class DeviceDriverTest: """Test device_driver.""" def setUp(self): """Set up the test.""" <|body_0|> def testCreateGCETypeAVD(self): """Test CreateGCETypeAVD.""" <|body_1|> def testCreateGCETypeAVDInternalIP(self): """Test CreateGCETypeAVD with int...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeviceDriverTest: """Test device_driver.""" def setUp(self): """Set up the test.""" super(DeviceDriverTest, self).setUp() self.build_client = mock.MagicMock() self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client) self.storage_client...
the_stack_v2_python_sparse
tools/acloud/public/device_driver_test.py
ZYHGOD-1/Aosp11
train
0
18374e3a0394f568e6ee8f47cc759e82eb8b5893
[ "self.input = input.clone()\noutput = input.clamp(min=0)\nreturn output", "assert self.input is not None\nassert grad_output.size() == self.input.size()\ngrad_input = grad_output.clone()\ngrad_input[self.input < 0] = 0\nreturn grad_input" ]
<|body_start_0|> self.input = input.clone() output = input.clamp(min=0) return output <|end_body_0|> <|body_start_1|> assert self.input is not None assert grad_output.size() == self.input.size() grad_input = grad_output.clone() grad_input[self.input < 0] = 0 ...
Class representing the rectified linear unit activation function.
ReLU
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReLU: """Class representing the rectified linear unit activation function.""" def forward(self, input): """Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as input""" <|body_0|> def backward(self, grad_ou...
stack_v2_sparse_classes_36k_train_010146
2,186
permissive
[ { "docstring": "Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as input", "name": "forward", "signature": "def forward(self, input)" }, { "docstring": "Given the gradient w.r.t. to the output of the activation, computes the grad...
2
stack_v2_sparse_classes_30k_val_001025
Implement the Python class `ReLU` described below. Class description: Class representing the rectified linear unit activation function. Method signatures and docstrings: - def forward(self, input): Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as in...
Implement the Python class `ReLU` described below. Class description: Class representing the rectified linear unit activation function. Method signatures and docstrings: - def forward(self, input): Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as in...
056b1be878b77c5a7dd5cff8d29ecb390be8b5de
<|skeleton|> class ReLU: """Class representing the rectified linear unit activation function.""" def forward(self, input): """Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as input""" <|body_0|> def backward(self, grad_ou...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReLU: """Class representing the rectified linear unit activation function.""" def forward(self, input): """Apllies the relu function to the input. Args: input -- tensor of size (N, *) Return: output -- tensor of same size as input""" self.input = input.clone() output = input.clamp...
the_stack_v2_python_sparse
Proj2/modules/Activations.py
jouvemax/DeepLearning
train
0
0a404c1421be4c6d39a1a7333cc6bd83b07ac0be
[ "n = self.xdim\nx = x.detach()\nx.requires_grad_(True)\nnx = self.step(t, x, u)\njac_x = torch.stack([torch.autograd.grad(nx[:, :, i].sum(), x, retain_graph=True)[0] for i in range(n)], dim=2)\nreturn jac_x", "n = self.xdim\nu = u.detach()\nu.requires_grad_(True)\nnx = self.step(t, x, u)\njac_u = torch.stack([tor...
<|body_start_0|> n = self.xdim x = x.detach() x.requires_grad_(True) nx = self.step(t, x, u) jac_x = torch.stack([torch.autograd.grad(nx[:, :, i].sum(), x, retain_graph=True)[0] for i in range(n)], dim=2) return jac_x <|end_body_0|> <|body_start_1|> n = self.xdim...
Mixin for computing jacobians of dynamics. Defaults to using autograd.
DynJacMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DynJacMixin: """Mixin for computing jacobians of dynamics. Defaults to using autograd.""" def jac_step_x(self, t, x, u=None): """Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torch.tensor): (B, T, n) shaped system states u (torch.tensor...
stack_v2_sparse_classes_36k_train_010147
11,101
permissive
[ { "docstring": "Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torch.tensor): (B, T, n) shaped system states u (torch.tensor): (B, T, m) shaped control inputs Returns jac_x_t (torch.tensor): (B, T, n, n) shaped jacobian of the next state", "name": "jac_step_x",...
3
stack_v2_sparse_classes_30k_train_019198
Implement the Python class `DynJacMixin` described below. Class description: Mixin for computing jacobians of dynamics. Defaults to using autograd. Method signatures and docstrings: - def jac_step_x(self, t, x, u=None): Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torc...
Implement the Python class `DynJacMixin` described below. Class description: Mixin for computing jacobians of dynamics. Defaults to using autograd. Method signatures and docstrings: - def jac_step_x(self, t, x, u=None): Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torc...
6154587fe3cdb92e8b7f70eedb1262caa1553cc8
<|skeleton|> class DynJacMixin: """Mixin for computing jacobians of dynamics. Defaults to using autograd.""" def jac_step_x(self, t, x, u=None): """Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torch.tensor): (B, T, n) shaped system states u (torch.tensor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DynJacMixin: """Mixin for computing jacobians of dynamics. Defaults to using autograd.""" def jac_step_x(self, t, x, u=None): """Returns the Jacobian of step at time t Args: t (torch.tensor): (B, T,) shaped time indices x (torch.tensor): (B, T, n) shaped system states u (torch.tensor): (B, T, m) ...
the_stack_v2_python_sparse
ceem/dynamics.py
sisl/CEEM
train
6
e82d1080472569ba433d54900246adfcc73093c3
[ "self.ensure_one()\nif self.country_id.code != 'CL':\n return super()._format_document_number(document_number)\nif not document_number:\n return False\nreturn document_number.zfill(6)", "self.ensure_one()\nif self.country_id.code == 'CL' and self.code in ['39', '41', '110', '111', '112', '34']:\n return ...
<|body_start_0|> self.ensure_one() if self.country_id.code != 'CL': return super()._format_document_number(document_number) if not document_number: return False return document_number.zfill(6) <|end_body_0|> <|body_start_1|> self.ensure_one() if s...
L10nLatamDocumentType
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class L10nLatamDocumentType: def _format_document_number(self, document_number): """Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it""" <|body_...
stack_v2_sparse_classes_36k_train_010148
1,398
permissive
[ { "docstring": "Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it", "name": "_format_document_number", "signature": "def _format_document_number(self, document_nu...
2
stack_v2_sparse_classes_30k_train_005509
Implement the Python class `L10nLatamDocumentType` described below. Class description: Implement the L10nLatamDocumentType class. Method signatures and docstrings: - def _format_document_number(self, document_number): Make validation of Import Dispatch Number * making validations on the document_number. If it is wron...
Implement the Python class `L10nLatamDocumentType` described below. Class description: Implement the L10nLatamDocumentType class. Method signatures and docstrings: - def _format_document_number(self, document_number): Make validation of Import Dispatch Number * making validations on the document_number. If it is wron...
310497a9872db7844b521e6dab5f7a9f61d365a4
<|skeleton|> class L10nLatamDocumentType: def _format_document_number(self, document_number): """Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class L10nLatamDocumentType: def _format_document_number(self, document_number): """Make validation of Import Dispatch Number * making validations on the document_number. If it is wrong it should raise an exception * format the document_number against a pattern and return it""" self.ensure_one() ...
the_stack_v2_python_sparse
addons/l10n_cl/models/l10n_latam_document_type.py
SHIVJITH/Odoo_Machine_Test
train
0
d441b85e15392c2057bfe64dde8c30c8d627129b
[ "subcategory = self.cleaned_data['subcategory']\nif subcategory.parent_category is None:\n raise forms.ValidationError(INVALID_SUBCATEGORY, code='invalid')\nreturn subcategory", "images = self.data.get('images', [])\ncurrent_images = Image.objects.filter(offer_id=offer.id)\nif current_images:\n excluded_ima...
<|body_start_0|> subcategory = self.cleaned_data['subcategory'] if subcategory.parent_category is None: raise forms.ValidationError(INVALID_SUBCATEGORY, code='invalid') return subcategory <|end_body_0|> <|body_start_1|> images = self.data.get('images', []) current_im...
Form to create an offer from admin
AdminCreateOfferForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdminCreateOfferForm: """Form to create an offer from admin""" def clean_subcategory(self): """Validate subcategory is actually a subcategory, not a parent category""" <|body_0|> def clean_images(self, offer): """Clean images""" <|body_1|> def clean_...
stack_v2_sparse_classes_36k_train_010149
8,911
no_license
[ { "docstring": "Validate subcategory is actually a subcategory, not a parent category", "name": "clean_subcategory", "signature": "def clean_subcategory(self)" }, { "docstring": "Clean images", "name": "clean_images", "signature": "def clean_images(self, offer)" }, { "docstring":...
4
stack_v2_sparse_classes_30k_train_001423
Implement the Python class `AdminCreateOfferForm` described below. Class description: Form to create an offer from admin Method signatures and docstrings: - def clean_subcategory(self): Validate subcategory is actually a subcategory, not a parent category - def clean_images(self, offer): Clean images - def clean_mate...
Implement the Python class `AdminCreateOfferForm` described below. Class description: Form to create an offer from admin Method signatures and docstrings: - def clean_subcategory(self): Validate subcategory is actually a subcategory, not a parent category - def clean_images(self, offer): Clean images - def clean_mate...
4dc6362ef624eb6591aad9d5c7de95eee40a01c9
<|skeleton|> class AdminCreateOfferForm: """Form to create an offer from admin""" def clean_subcategory(self): """Validate subcategory is actually a subcategory, not a parent category""" <|body_0|> def clean_images(self, offer): """Clean images""" <|body_1|> def clean_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdminCreateOfferForm: """Form to create an offer from admin""" def clean_subcategory(self): """Validate subcategory is actually a subcategory, not a parent category""" subcategory = self.cleaned_data['subcategory'] if subcategory.parent_category is None: raise forms.Va...
the_stack_v2_python_sparse
app/offers/forms.py
arielMilan1899/orbita-api
train
0
e58e6fce59535aaaeab0fd30bac2bc5fad985af1
[ "self.w = w\nself.n = len(w)\nself.s = sum(self.w)\nfor i in range(1, self.n):\n w[i] += w[i - 1]", "seed = random.randint(1, self.s)\nl, r = (0, self.n - 1)\nwhile l < r:\n mid = (l + r) // 2\n if seed <= self.w[mid]:\n r = mid\n else:\n l = mid + 1\nreturn l" ]
<|body_start_0|> self.w = w self.n = len(w) self.s = sum(self.w) for i in range(1, self.n): w[i] += w[i - 1] <|end_body_0|> <|body_start_1|> seed = random.randint(1, self.s) l, r = (0, self.n - 1) while l < r: mid = (l + r) // 2 ...
Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.""" def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): ...
stack_v2_sparse_classes_36k_train_010150
752
permissive
[ { "docstring": ":type w: List[int]", "name": "__init__", "signature": "def __init__(self, w)" }, { "docstring": ":rtype: int", "name": "pickIndex", "signature": "def pickIndex(self)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. Method signatures and docstrings: - def __init__(self, w): :type w: List[in...
Implement the Python class `Solution` described below. Class description: Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. Method signatures and docstrings: - def __init__(self, w): :type w: List[in...
e3accd22d8cf25546f33883aac634a9bfe108b34
<|skeleton|> class Solution: """Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.""" def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.""" def __init__(self, w): """:type w: List[int]""" self.w = w self.n = len(w) self.s = sum(...
the_stack_v2_python_sparse
LeetCode/random_pick_with_rate.py
milkrong/Basic-Python-DS-Algs
train
0
b7c9d0a622882f42d91684702fba4df6979b3b9e
[ "security_group = self.os_conn.create_sec_group_for_ssh()\nself.instance_keypair = self.os_conn.create_key(key_name='instancekey')\nself.os_conn.nova.security_group_rules.create(security_group.id, ip_protocol='tcp', from_port=1, to_port=65535, cidr='0.0.0.0/0')\nnet, subnet = self.create_internal_network_with_subne...
<|body_start_0|> security_group = self.os_conn.create_sec_group_for_ssh() self.instance_keypair = self.os_conn.create_key(key_name='instancekey') self.os_conn.nova.security_group_rules.create(security_group.id, ip_protocol='tcp', from_port=1, to_port=65535, cidr='0.0.0.0/0') net, subnet ...
Check association and disassociation floating ip
TestFloatingIP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFloatingIP: """Check association and disassociation floating ip""" def prepare_openstack(self): """Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new security group sec_group1 3. Add Ingress rule for TCP pr...
stack_v2_sparse_classes_36k_train_010151
5,007
no_license
[ { "docstring": "Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new security group sec_group1 3. Add Ingress rule for TCP protocol to sec_group1 4. Boot vm1 net01 with sec_group1", "name": "prepare_openstack", "signature": "def pre...
2
stack_v2_sparse_classes_30k_train_010560
Implement the Python class `TestFloatingIP` described below. Class description: Check association and disassociation floating ip Method signatures and docstrings: - def prepare_openstack(self): Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new...
Implement the Python class `TestFloatingIP` described below. Class description: Check association and disassociation floating ip Method signatures and docstrings: - def prepare_openstack(self): Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new...
8aced2855b78b5f123195d188c80e27b43888a2e
<|skeleton|> class TestFloatingIP: """Check association and disassociation floating ip""" def prepare_openstack(self): """Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new security group sec_group1 3. Add Ingress rule for TCP pr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestFloatingIP: """Check association and disassociation floating ip""" def prepare_openstack(self): """Prepare OpenStack for scenarios run Steps: 1. Create network net01, subnet net01__subnet with CIDR 10.1.1.0/24 2. Create new security group sec_group1 3. Add Ingress rule for TCP protocol to sec...
the_stack_v2_python_sparse
mos_tests/neutron/python_tests/test_floating_ip.py
Mirantis/mos-integration-tests
train
16
e020960945365660d61f3fdfca91ec5631ee0331
[ "if type(sources) == int:\n sources = list(sources)\nself.marked = [False for _ in range(G.V)]\nfor s in sources:\n if not self.marked[s]:\n self.dfs(G, s)", "self.marked[v] = True\nfor w in G.adj[v]:\n self.dfs(G, w)" ]
<|body_start_0|> if type(sources) == int: sources = list(sources) self.marked = [False for _ in range(G.V)] for s in sources: if not self.marked[s]: self.dfs(G, s) <|end_body_0|> <|body_start_1|> self.marked[v] = True for w in G.adj[v]: ...
DirectedDFS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DirectedDFS: def __init__(self, G, sources): """Args: G: Digraph sources: int or list[int]""" <|body_0|> def dfs(self, G, v): """Args: G: Digraph v: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if type(sources) == int: sources = l...
stack_v2_sparse_classes_36k_train_010152
575
no_license
[ { "docstring": "Args: G: Digraph sources: int or list[int]", "name": "__init__", "signature": "def __init__(self, G, sources)" }, { "docstring": "Args: G: Digraph v: int", "name": "dfs", "signature": "def dfs(self, G, v)" } ]
2
stack_v2_sparse_classes_30k_train_011763
Implement the Python class `DirectedDFS` described below. Class description: Implement the DirectedDFS class. Method signatures and docstrings: - def __init__(self, G, sources): Args: G: Digraph sources: int or list[int] - def dfs(self, G, v): Args: G: Digraph v: int
Implement the Python class `DirectedDFS` described below. Class description: Implement the DirectedDFS class. Method signatures and docstrings: - def __init__(self, G, sources): Args: G: Digraph sources: int or list[int] - def dfs(self, G, v): Args: G: Digraph v: int <|skeleton|> class DirectedDFS: def __init__...
c4e5cce32826ae8ead955277b85f6b3377286d51
<|skeleton|> class DirectedDFS: def __init__(self, G, sources): """Args: G: Digraph sources: int or list[int]""" <|body_0|> def dfs(self, G, v): """Args: G: Digraph v: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DirectedDFS: def __init__(self, G, sources): """Args: G: Digraph sources: int or list[int]""" if type(sources) == int: sources = list(sources) self.marked = [False for _ in range(G.V)] for s in sources: if not self.marked[s]: self.dfs(G, ...
the_stack_v2_python_sparse
code/chapter4/DirectedDFS.py
AiZhanghan/Algorithms-Fourth-Edition
train
0
c3f831e21b3afc2ba0364626e10f86eb08ea51ba
[ "super(TFC_RNN, self).__init__()\nself.skip_connection = skip_connection\nself.tfc = TFC(in_channels, num_layers_tfc, gr, kt, kf, activation)\nself.bn = nn.BatchNorm2d(gr)\nhidden_units_rnn = max(f // bn_factor_rnn, min_bn_units_rnn)\nself.rnn = nn.GRU(f, hidden_units_rnn, num_layers_rnn, bias=bias_rnn, batch_first...
<|body_start_0|> super(TFC_RNN, self).__init__() self.skip_connection = skip_connection self.tfc = TFC(in_channels, num_layers_tfc, gr, kt, kf, activation) self.bn = nn.BatchNorm2d(gr) hidden_units_rnn = max(f // bn_factor_rnn, min_bn_units_rnn) self.rnn = nn.GRU(f, hidde...
[B, in_channels, T, F] => [B, gr, T, F]
TFC_RNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TFC_RNN: """[B, in_channels, T, F] => [B, gr, T, F]""" def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU): """...
stack_v2_sparse_classes_36k_train_010153
6,895
permissive
[ { "docstring": "in_channels: number of input channels num_layers_tfc: number of densely connected conv layers gr: growth rate kt: kernel size of the temporal axis. kf: kernel size of the freq. axis f: num of frequency bins bn_factor_rnn: bottleneck factor of rnn num_layers_rnn: number of layers of rnn bidirecti...
2
stack_v2_sparse_classes_30k_val_000938
Implement the Python class `TFC_RNN` described below. Class description: [B, in_channels, T, F] => [B, gr, T, F] Method signatures and docstrings: - def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, b...
Implement the Python class `TFC_RNN` described below. Class description: [B, in_channels, T, F] => [B, gr, T, F] Method signatures and docstrings: - def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, b...
366b92b601f324a5937fb902d3cd123a0980c9b8
<|skeleton|> class TFC_RNN: """[B, in_channels, T, F] => [B, gr, T, F]""" def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TFC_RNN: """[B, in_channels, T, F] => [B, gr, T, F]""" def __init__(self, in_channels, num_layers_tfc, gr, kt, kf, f, bn_factor_rnn, num_layers_rnn, bidirectional=True, min_bn_units_rnn=16, bias_rnn=True, bn_factor_tdf=16, bias_tdf=True, skip_connection=True, activation=nn.ReLU): """in_channels: ...
the_stack_v2_python_sparse
src/lasaft/source_separation/sub_modules/building_blocks.py
loretoparisi/Conditioned-Source-Separation-LaSAFT
train
3
24f201f8fefa926be75ce2c69d19785742966365
[ "classname = self.__class__.__name__\nobj_dir = settings.CLASSNAME_TO_DIR[classname]\nobj_path = os.path.join(obj_dir, self.id)\npickle.dump(self, open(obj_path, 'wb'))", "classname = cls.__name__\nobj_dir = settings.CLASSNAME_TO_DIR[classname]\nobj_list = []\nfor obj_name in os.listdir(obj_dir):\n obj_path = ...
<|body_start_0|> classname = self.__class__.__name__ obj_dir = settings.CLASSNAME_TO_DIR[classname] obj_path = os.path.join(obj_dir, self.id) pickle.dump(self, open(obj_path, 'wb')) <|end_body_0|> <|body_start_1|> classname = cls.__name__ obj_dir = settings.CLASSNAME_TO_...
基础功能类
Base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Base: """基础功能类""" def save(self): """存储对象功能""" <|body_0|> def get_all_obj(cls): """获取所有对象功能""" <|body_1|> def enroll(self, logger): """注册功能""" <|body_2|> def login(cls, logger): """登陆功能""" <|body_3|> <|end_skelet...
stack_v2_sparse_classes_36k_train_010154
2,893
no_license
[ { "docstring": "存储对象功能", "name": "save", "signature": "def save(self)" }, { "docstring": "获取所有对象功能", "name": "get_all_obj", "signature": "def get_all_obj(cls)" }, { "docstring": "注册功能", "name": "enroll", "signature": "def enroll(self, logger)" }, { "docstring": "登...
4
stack_v2_sparse_classes_30k_train_006199
Implement the Python class `Base` described below. Class description: 基础功能类 Method signatures and docstrings: - def save(self): 存储对象功能 - def get_all_obj(cls): 获取所有对象功能 - def enroll(self, logger): 注册功能 - def login(cls, logger): 登陆功能
Implement the Python class `Base` described below. Class description: 基础功能类 Method signatures and docstrings: - def save(self): 存储对象功能 - def get_all_obj(cls): 获取所有对象功能 - def enroll(self, logger): 注册功能 - def login(cls, logger): 登陆功能 <|skeleton|> class Base: """基础功能类""" def save(self): """存储对象功能""" ...
4d497a6261de17cc2fc058cea50e127e885e5095
<|skeleton|> class Base: """基础功能类""" def save(self): """存储对象功能""" <|body_0|> def get_all_obj(cls): """获取所有对象功能""" <|body_1|> def enroll(self, logger): """注册功能""" <|body_2|> def login(cls, logger): """登陆功能""" <|body_3|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Base: """基础功能类""" def save(self): """存储对象功能""" classname = self.__class__.__name__ obj_dir = settings.CLASSNAME_TO_DIR[classname] obj_path = os.path.join(obj_dir, self.id) pickle.dump(self, open(obj_path, 'wb')) def get_all_obj(cls): """获取所有对象功能""" ...
the_stack_v2_python_sparse
day09/LikeFabric/core/base.py
phully/PythonHomeWork
train
0
e7c9fee0370d61548a563c60e0c201d38f4431c7
[ "super().__init__()\nself.decoder = Decoder(config)\nself.encoder = Encoder(config)\nhop_length = frame_length = int(config.sample_rate * config.frame_resolution)\nself.harmonic_oscillator = HarmonicOscillator(sr=config.sample_rate, frame_length=hop_length)\nself.filtered_noise = FilteredNoise(frame_length=hop_leng...
<|body_start_0|> super().__init__() self.decoder = Decoder(config) self.encoder = Encoder(config) hop_length = frame_length = int(config.sample_rate * config.frame_resolution) self.harmonic_oscillator = HarmonicOscillator(sr=config.sample_rate, frame_length=hop_length) se...
AutoEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoEncoder: def __init__(self, config): """encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_units=512, mlp_layers=3, use_z=False, z_units=16, n_harmonics=101, n_freq=65, gru_units=512, component...
stack_v2_sparse_classes_36k_train_010155
32,670
no_license
[ { "docstring": "encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_units=512, mlp_layers=3, use_z=False, z_units=16, n_harmonics=101, n_freq=65, gru_units=512, components_config sample_rate hop_length", "name": "__ini...
4
null
Implement the Python class `AutoEncoder` described below. Class description: Implement the AutoEncoder class. Method signatures and docstrings: - def __init__(self, config): encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_un...
Implement the Python class `AutoEncoder` described below. Class description: Implement the AutoEncoder class. Method signatures and docstrings: - def __init__(self, config): encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_un...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class AutoEncoder: def __init__(self, config): """encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_units=512, mlp_layers=3, use_z=False, z_units=16, n_harmonics=101, n_freq=65, gru_units=512, component...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AutoEncoder: def __init__(self, config): """encoder_config use_z=False, sample_rate=16000, z_units=16, n_fft=2048, hop_length=64, n_mels=128, n_mfcc=30, gru_units=512 decoder_config mlp_units=512, mlp_layers=3, use_z=False, z_units=16, n_harmonics=101, n_freq=65, gru_units=512, components_config sampl...
the_stack_v2_python_sparse
generated/test_sweetcocoa_ddsp_pytorch.py
jansel/pytorch-jit-paritybench
train
35
6a9013415fcd27f786424a343215399b2549464c
[ "self.need_header_flag = False\nself.header = None\nself.data = input_data(img, no_header=True)\nself.num_bins = num_bins\nself.periodic = periodic\nif lags is None:\n self.lags = [1, 2, 4, 8, 16, 32, 64]\nelse:\n self.lags = lags\nself.tsallis_arrays = np.empty((len(self.lags), self.data.shape[0], self.data....
<|body_start_0|> self.need_header_flag = False self.header = None self.data = input_data(img, no_header=True) self.num_bins = num_bins self.periodic = periodic if lags is None: self.lags = [1, 2, 4, 8, 16, 32, 64] else: self.lags = lags ...
The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional Sets whether the boundaries are periodic.
Tsallis
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tsallis: """The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional Sets whether the boundaries are period...
stack_v2_sparse_classes_36k_train_010156
8,719
permissive
[ { "docstring": "Parameters ---------- periodic : bool, optional Use for simulations with periodic boundaries.", "name": "__init__", "signature": "def __init__(self, img, lags=None, num_bins=500, periodic=False)" }, { "docstring": "Calculate the Tsallis distribution at each lag. We standardize ea...
4
stack_v2_sparse_classes_30k_train_005033
Implement the Python class `Tsallis` described below. Class description: The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional...
Implement the Python class `Tsallis` described below. Class description: The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional...
6bdcae10dd27e8e81413e422fd9dd5ade3868a33
<|skeleton|> class Tsallis: """The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional Sets whether the boundaries are period...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tsallis: """The Tsallis Distribution (see Tofflemire et al., 2011) Parameters ---------- img : %(dtypes)s 2D image. lags : numpy.ndarray or list Lags to calculate at. num_bins : int, optional Number of bins to use in the histograms. periodic : bool, optional Sets whether the boundaries are periodic.""" d...
the_stack_v2_python_sparse
TurbuStat/turbustat/statistics/tsallis/tsallis.py
jrobbfed/carma
train
0
ed01d783da097b71de112097f1bbaa9a5a37a6fe
[ "if not s:\n return ''\nif len(s) == 1:\n return s\n\ndef isPalindrome(l, r):\n while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\nindicies = []\nmax_lenght = 0\nfor i in range(0, len(s) - 1):\n for j in range(i + 1, len(s)):\n if is...
<|body_start_0|> if not s: return '' if len(s) == 1: return s def isPalindrome(l, r): while l < r: if s[l] != s[r]: return False l += 1 r -= 1 return True indicies = [] ...
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|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_2|> <|en...
stack_v2_sparse_classes_36k_train_010157
4,948
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)" }, { "docstring": ":type s: str :rtype:...
3
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 - def longestPalindrome(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 - def longestPalindrome(self, s): :type s: str :rtype: str <...
b925bb22d1daa4a56c5a238a5758a926905559b4
<|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|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_2|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestPalindrome(self, s): """:type s: str :rtype: str""" if not s: return '' if len(s) == 1: return s def isPalindrome(l, r): while l < r: if s[l] != s[r]: return False l +=...
the_stack_v2_python_sparse
String/5. Longest Palindromic Substring.py
beninghton/notGivenUpToG
train
0
75da30ac44e3af5b3c94b184ef2a07e1600a96f4
[ "dct = {}\nfor i in A:\n if i not in dct.keys():\n dct[i] = 1\n else:\n dct[i] += 1\nfor k, v in dct.items():\n if v == 1:\n return k", "for i in A:\n if A.count(i) == 1:\n return i", "lst1 = []\nlst2 = []\nfor i in A:\n if i not in lst1:\n if i not in lst2:\n ...
<|body_start_0|> dct = {} for i in A: if i not in dct.keys(): dct[i] = 1 else: dct[i] += 1 for k, v in dct.items(): if v == 1: return k <|end_body_0|> <|body_start_1|> for i in A: if A.count(...
@param: A: An integer array @return: An integer
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """@param: A: An integer array @return: An integer""" def singleNumberII_1(self, A): """字典,lintcode居然超时了, 这台垃圾电脑秒出结果""" <|body_0|> def singleNumberII_2(self, A): """逗比答案, 还是超时""" <|body_1|> def singleNumberII_3(self, A): """不用怀疑还是超时...
stack_v2_sparse_classes_36k_train_010158
2,222
no_license
[ { "docstring": "字典,lintcode居然超时了, 这台垃圾电脑秒出结果", "name": "singleNumberII_1", "signature": "def singleNumberII_1(self, A)" }, { "docstring": "逗比答案, 还是超时", "name": "singleNumberII_2", "signature": "def singleNumberII_2(self, A)" }, { "docstring": "不用怀疑还是超时...", "name": "singleNum...
4
stack_v2_sparse_classes_30k_train_005039
Implement the Python class `Solution` described below. Class description: @param: A: An integer array @return: An integer Method signatures and docstrings: - def singleNumberII_1(self, A): 字典,lintcode居然超时了, 这台垃圾电脑秒出结果 - def singleNumberII_2(self, A): 逗比答案, 还是超时 - def singleNumberII_3(self, A): 不用怀疑还是超时... - def singl...
Implement the Python class `Solution` described below. Class description: @param: A: An integer array @return: An integer Method signatures and docstrings: - def singleNumberII_1(self, A): 字典,lintcode居然超时了, 这台垃圾电脑秒出结果 - def singleNumberII_2(self, A): 逗比答案, 还是超时 - def singleNumberII_3(self, A): 不用怀疑还是超时... - def singl...
87592a39d67d8e734e693327d6b063be334b37e2
<|skeleton|> class Solution: """@param: A: An integer array @return: An integer""" def singleNumberII_1(self, A): """字典,lintcode居然超时了, 这台垃圾电脑秒出结果""" <|body_0|> def singleNumberII_2(self, A): """逗比答案, 还是超时""" <|body_1|> def singleNumberII_3(self, A): """不用怀疑还是超时...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """@param: A: An integer array @return: An integer""" def singleNumberII_1(self, A): """字典,lintcode居然超时了, 这台垃圾电脑秒出结果""" dct = {} for i in A: if i not in dct.keys(): dct[i] = 1 else: dct[i] += 1 for k, v in d...
the_stack_v2_python_sparse
LintCode/LintCode-83:落单的数 II.py
hoshizorahikari/PythonExercise
train
0
bbe0e77c4d10909107a65a10439caff196654794
[ "cart_obj = self.request.user.cart_set.order_by('-created_time')[0]\ncart_items = CartItem.objects.select_related('menu', 'menu__restaurant').prefetch_related('menu__tastes').filter(cart__id=cart_obj.id)\nif not cart_items.exists():\n return JsonResponse(data={'message': '주문표는 현재 비어있습니다.'})\nfirst_menu = cart_it...
<|body_start_0|> cart_obj = self.request.user.cart_set.order_by('-created_time')[0] cart_items = CartItem.objects.select_related('menu', 'menu__restaurant').prefetch_related('menu__tastes').filter(cart__id=cart_obj.id) if not cart_items.exists(): return JsonResponse(data={'message': ...
CartListCreateAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CartListCreateAPIView: def get(self, request, *args, **kwargs): """주문표 내 메뉴의 리스트를 보여준다.""" <|body_0|> def post(self, request, *args, **kwargs): """주문표을 생성한다.""" <|body_1|> <|end_skeleton|> <|body_start_0|> cart_obj = self.request.user.cart_set.order...
stack_v2_sparse_classes_36k_train_010159
10,133
no_license
[ { "docstring": "주문표 내 메뉴의 리스트를 보여준다.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "주문표을 생성한다.", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_003432
Implement the Python class `CartListCreateAPIView` described below. Class description: Implement the CartListCreateAPIView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 주문표 내 메뉴의 리스트를 보여준다. - def post(self, request, *args, **kwargs): 주문표을 생성한다.
Implement the Python class `CartListCreateAPIView` described below. Class description: Implement the CartListCreateAPIView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 주문표 내 메뉴의 리스트를 보여준다. - def post(self, request, *args, **kwargs): 주문표을 생성한다. <|skeleton|> class CartListCreateA...
659d9757d1f369a6713aa5a66bab2aa5d6381b8e
<|skeleton|> class CartListCreateAPIView: def get(self, request, *args, **kwargs): """주문표 내 메뉴의 리스트를 보여준다.""" <|body_0|> def post(self, request, *args, **kwargs): """주문표을 생성한다.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CartListCreateAPIView: def get(self, request, *args, **kwargs): """주문표 내 메뉴의 리스트를 보여준다.""" cart_obj = self.request.user.cart_set.order_by('-created_time')[0] cart_items = CartItem.objects.select_related('menu', 'menu__restaurant').prefetch_related('menu__tastes').filter(cart__id=cart_o...
the_stack_v2_python_sparse
project/src/cart/api/views.py
ssr03/MiniDelivery
train
0
e2f5c0369cbd798ab3e41e4207d461f0a64f3f79
[ "dummy = ListNode(0)\ncurr = dummy.next = head\nh = l = ListNode(0)\nwhile curr and curr.next:\n if curr.val != curr.next.val:\n l.next = curr\n curr = curr.next\n l = l.next\n else:\n tmp = curr.val\n while curr and curr.val == tmp:\n curr = curr.next\nl.next = c...
<|body_start_0|> dummy = ListNode(0) curr = dummy.next = head h = l = ListNode(0) while curr and curr.next: if curr.val != curr.next.val: l.next = curr curr = curr.next l = l.next else: tmp = curr.val...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def deleteDuplicates1(self, head: ListNode) -> ListNode: """额外链表 :param head: :return:""" <|body_0|> def deleteDuplicates2(self, head: ListNode) -> ListNode: """in-place :param head: :return:""" <|body_1|> def deleteDuplicates3(self, head: List...
stack_v2_sparse_classes_36k_train_010160
2,518
no_license
[ { "docstring": "额外链表 :param head: :return:", "name": "deleteDuplicates1", "signature": "def deleteDuplicates1(self, head: ListNode) -> ListNode" }, { "docstring": "in-place :param head: :return:", "name": "deleteDuplicates2", "signature": "def deleteDuplicates2(self, head: ListNode) -> L...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteDuplicates1(self, head: ListNode) -> ListNode: 额外链表 :param head: :return: - def deleteDuplicates2(self, head: ListNode) -> ListNode: in-place :param head: :return: - de...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteDuplicates1(self, head: ListNode) -> ListNode: 额外链表 :param head: :return: - def deleteDuplicates2(self, head: ListNode) -> ListNode: in-place :param head: :return: - de...
25f2795b6e7f9f68833f2fddc6cc4f4d977121a6
<|skeleton|> class Solution: def deleteDuplicates1(self, head: ListNode) -> ListNode: """额外链表 :param head: :return:""" <|body_0|> def deleteDuplicates2(self, head: ListNode) -> ListNode: """in-place :param head: :return:""" <|body_1|> def deleteDuplicates3(self, head: List...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def deleteDuplicates1(self, head: ListNode) -> ListNode: """额外链表 :param head: :return:""" dummy = ListNode(0) curr = dummy.next = head h = l = ListNode(0) while curr and curr.next: if curr.val != curr.next.val: l.next = curr ...
the_stack_v2_python_sparse
82.py
Darkxiete/leetcode_python
train
0
37e7b6c744bbb139f8eb8174d412166fdc09bd0e
[ "req = request.query_params.dict()\nif len(req) != 0:\n raise ArgumentError()\ndata = VERSION.objects.all()\nlength = data.count()\nif length > 0:\n return Response(data.values('version_number', 'update_date', 'announcement', 'download_address')[length - 1])\nreturn Response({'version_number': '', 'update_dat...
<|body_start_0|> req = request.query_params.dict() if len(req) != 0: raise ArgumentError() data = VERSION.objects.all() length = data.count() if length > 0: return Response(data.values('version_number', 'update_date', 'announcement', 'download_address')[le...
Version
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Version: def get(request): """前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址""" <|body_0|> def post(request): """pm调用在数据库中插入最新版本信息 访问方法 http://127.0.0.1:8000/version/ 参数:版本号,更新日期,更新公告,下载地址 返回结果:插入状态""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_010161
1,785
no_license
[ { "docstring": "前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址", "name": "get", "signature": "def get(request)" }, { "docstring": "pm调用在数据库中插入最新版本信息 访问方法 http://127.0.0.1:8000/version/ 参数:版本号,更新日期,更新公告,下载地址 返回结果:插入状态", "name": "post", "signature": "def post(...
2
stack_v2_sparse_classes_30k_train_017946
Implement the Python class `Version` described below. Class description: Implement the Version class. Method signatures and docstrings: - def get(request): 前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址 - def post(request): pm调用在数据库中插入最新版本信息 访问方法 http://127.0.0.1:8000/version/ 参数:版本号,更新日...
Implement the Python class `Version` described below. Class description: Implement the Version class. Method signatures and docstrings: - def get(request): 前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址 - def post(request): pm调用在数据库中插入最新版本信息 访问方法 http://127.0.0.1:8000/version/ 参数:版本号,更新日...
7dfa07283d4130b931a92c80bf4f499f97a33b62
<|skeleton|> class Version: def get(request): """前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址""" <|body_0|> def post(request): """pm调用在数据库中插入最新版本信息 访问方法 http://127.0.0.1:8000/version/ 参数:版本号,更新日期,更新公告,下载地址 返回结果:插入状态""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Version: def get(request): """前端调用得到最新版本信息 访问方法 http://127.0.0.1:8000/version/ 无参数 返回结果:版本号,更新日期,更新公告,下载地址""" req = request.query_params.dict() if len(req) != 0: raise ArgumentError() data = VERSION.objects.all() length = data.count() if length > 0: ...
the_stack_v2_python_sparse
version_information/views.py
SE2020-TopUnderstanding/BUAA-Campus-Tools-Backend
train
7
b8c07cbce56f5499ce9970ac0d9450bc4b56240d
[ "try:\n return project_context.database['project']\nexcept KeyError as e:\n raise ValueError('Cannot get project') from e", "from renku import __version__\ndatabase = project_context.database\ntry:\n if database['project']:\n database.remove_root_object('project')\nexcept KeyError:\n pass\nproj...
<|body_start_0|> try: return project_context.database['project'] except KeyError as e: raise ValueError('Cannot get project') from e <|end_body_0|> <|body_start_1|> from renku import __version__ database = project_context.database try: if data...
Gateway for project database operations.
ProjectGateway
[ "Apache-2.0", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectGateway: """Gateway for project database operations.""" def get_project(self) -> Project: """Get project metadata.""" <|body_0|> def update_project(self, project: Project): """Update project metadata.""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_010162
1,711
permissive
[ { "docstring": "Get project metadata.", "name": "get_project", "signature": "def get_project(self) -> Project" }, { "docstring": "Update project metadata.", "name": "update_project", "signature": "def update_project(self, project: Project)" } ]
2
null
Implement the Python class `ProjectGateway` described below. Class description: Gateway for project database operations. Method signatures and docstrings: - def get_project(self) -> Project: Get project metadata. - def update_project(self, project: Project): Update project metadata.
Implement the Python class `ProjectGateway` described below. Class description: Gateway for project database operations. Method signatures and docstrings: - def get_project(self) -> Project: Get project metadata. - def update_project(self, project: Project): Update project metadata. <|skeleton|> class ProjectGateway...
e0ff587f507d049eeeb873e8488ba8bb10ac1a15
<|skeleton|> class ProjectGateway: """Gateway for project database operations.""" def get_project(self) -> Project: """Get project metadata.""" <|body_0|> def update_project(self, project: Project): """Update project metadata.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectGateway: """Gateway for project database operations.""" def get_project(self) -> Project: """Get project metadata.""" try: return project_context.database['project'] except KeyError as e: raise ValueError('Cannot get project') from e def update_...
the_stack_v2_python_sparse
renku/infrastructure/gateway/project_gateway.py
SwissDataScienceCenter/renku-python
train
30
b3a8b0f807275f77fd678f130c0c9d4cb12bbfc0
[ "super().__init__(inter_class=False)\nself.num_frames = num_frames\nself.num_ctx_frames = num_ctx_frames", "def _remove_ctx_frames(frame):\n s, h, w, c = frame.shape\n seq_len = s // self.num_ctx_frames\n frame = frame.reshape(seq_len, self.num_ctx_frames, h, w, c)\n return frame[:, -1]\nframes = [o.f...
<|body_start_0|> super().__init__(inter_class=False) self.num_frames = num_frames self.num_ctx_frames = num_ctx_frames <|end_body_0|> <|body_start_1|> def _remove_ctx_frames(frame): s, h, w, c = frame.shape seq_len = s // self.num_ctx_frames frame = f...
Frame reconstruction visualizer.
ReconstructionVisualizer
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReconstructionVisualizer: """Frame reconstruction visualizer.""" def __init__(self, num_frames, num_ctx_frames): """Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The number of context frames stacked together for each indiv...
stack_v2_sparse_classes_36k_train_010163
2,727
permissive
[ { "docstring": "Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The number of context frames stacked together for each individual video frame.", "name": "__init__", "signature": "def __init__(self, num_frames, num_ctx_frames)" }, { "doc...
2
null
Implement the Python class `ReconstructionVisualizer` described below. Class description: Frame reconstruction visualizer. Method signatures and docstrings: - def __init__(self, num_frames, num_ctx_frames): Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The...
Implement the Python class `ReconstructionVisualizer` described below. Class description: Frame reconstruction visualizer. Method signatures and docstrings: - def __init__(self, num_frames, num_ctx_frames): Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ReconstructionVisualizer: """Frame reconstruction visualizer.""" def __init__(self, num_frames, num_ctx_frames): """Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The number of context frames stacked together for each indiv...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReconstructionVisualizer: """Frame reconstruction visualizer.""" def __init__(self, num_frames, num_ctx_frames): """Constructor. Args: num_frames: The number of reconstructed frames in a sequence to display. num_ctx_frames: The number of context frames stacked together for each individual video f...
the_stack_v2_python_sparse
xirl/xirl/evaluators/reconstruction_visualizer.py
Jimmy-INL/google-research
train
1
2d2e5ce95f9d0a33a80f091c0b58cfe18653b78b
[ "self.p = {}\nfor word in words:\n for i in xrange(len(word) + 1):\n if word[:i] in self.p:\n self.p[word[:i]].add(word)\n else:\n self.p[word[:i]] = set([word])\nself.s = {}\nfor word in words:\n for i in xrange(len(word) + 1):\n if word[i:] in self.s:\n ...
<|body_start_0|> self.p = {} for word in words: for i in xrange(len(word) + 1): if word[:i] in self.p: self.p[word[:i]].add(word) else: self.p[word[:i]] = set([word]) self.s = {} for word in words: ...
WordFilter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.p = {} for word in words: ...
stack_v2_sparse_classes_36k_train_010164
1,920
permissive
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type prefix: str :type suffix: str :rtype: int", "name": "f", "signature": "def f(self, prefix, suffix)" } ]
2
null
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int <|skeleton|> class WordFilter: def __in...
6facec2a54d1d9f133f420c9bce1d1043f57ebc6
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordFilter: def __init__(self, words): """:type words: List[str]""" self.p = {} for word in words: for i in xrange(len(word) + 1): if word[:i] in self.p: self.p[word[:i]].add(word) else: self.p[word[:i]...
the_stack_v2_python_sparse
Prefix and Suffix Search.py
sugia/leetcode
train
1
2dc46641f941ec4ad473e343b8d6e2e7978a0f74
[ "super().__init__()\nself._alpha = torch.tensor(alpha)\nself._noise_val = self._alpha / n_classes\nself._n_classes = n_classes\nself.gamma = gamma\nself.class_weight_tensor = torch.tensor(weights).view(-1).cuda() if weights else None", "if teacher.ndim == 1:\n teacher = torch.eye(self._n_classes)[teacher]\ntea...
<|body_start_0|> super().__init__() self._alpha = torch.tensor(alpha) self._noise_val = self._alpha / n_classes self._n_classes = n_classes self.gamma = gamma self.class_weight_tensor = torch.tensor(weights).view(-1).cuda() if weights else None <|end_body_0|> <|body_star...
ClassificationFocalLossWithLabelSmoothing
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassificationFocalLossWithLabelSmoothing: def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[float]=None): """:param alpha: parameter of Label Smoothing. :param n_classes: :param gamma: 簡単なサンプルの重み. 大きいほど簡単なサンプルを重視しない. :param weights: weights by cl...
stack_v2_sparse_classes_36k_train_010165
9,953
no_license
[ { "docstring": ":param alpha: parameter of Label Smoothing. :param n_classes: :param gamma: 簡単なサンプルの重み. 大きいほど簡単なサンプルを重視しない. :param weights: weights by classes, :param logits:", "name": "__init__", "signature": "def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[fl...
2
stack_v2_sparse_classes_30k_train_014893
Implement the Python class `ClassificationFocalLossWithLabelSmoothing` described below. Class description: Implement the ClassificationFocalLossWithLabelSmoothing class. Method signatures and docstrings: - def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[float]=None): :param ...
Implement the Python class `ClassificationFocalLossWithLabelSmoothing` described below. Class description: Implement the ClassificationFocalLossWithLabelSmoothing class. Method signatures and docstrings: - def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[float]=None): :param ...
e64deb19918c7a7462d1c2b79cb9bc41c57318d3
<|skeleton|> class ClassificationFocalLossWithLabelSmoothing: def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[float]=None): """:param alpha: parameter of Label Smoothing. :param n_classes: :param gamma: 簡単なサンプルの重み. 大きいほど簡単なサンプルを重視しない. :param weights: weights by cl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassificationFocalLossWithLabelSmoothing: def __init__(self, n_classes: int, alpha=[0.2, 0.2, 0.2, 0.2, 0.2], gamma=2, weights: List[float]=None): """:param alpha: parameter of Label Smoothing. :param n_classes: :param gamma: 簡単なサンプルの重み. 大きいほど簡単なサンプルを重視しない. :param weights: weights by classes, :param ...
the_stack_v2_python_sparse
losses/loss.py
monofo/kaggle_cassava_leaf_disease_classification
train
0
7990368a530c83377c1c11cb43a1fa37ff7ad768
[ "self.debug = False\nself.name = 'featurizer'\nself.epsilon = 1e-08\nself.max_num_inputs = max_num_inputs\nif max_num_features is None:\n self.max_num_bundles = 3 * self.max_num_inputs\n self.max_num_features = self.max_num_inputs + self.max_num_bundles\nelse:\n self.max_num_features = max_num_features\n ...
<|body_start_0|> self.debug = False self.name = 'featurizer' self.epsilon = 1e-08 self.max_num_inputs = max_num_inputs if max_num_features is None: self.max_num_bundles = 3 * self.max_num_inputs self.max_num_features = self.max_num_inputs + self.max_num_bu...
Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur.
Featurizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Featurizer: """Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur.""" def __init__(self, max_num_inputs, max_num_features=None): """Configure the featurizer. Parameters --------- max_num_inputs : int See Featuriz...
stack_v2_sparse_classes_36k_train_010166
8,848
permissive
[ { "docstring": "Configure the featurizer. Parameters --------- max_num_inputs : int See Featurizer.max_num_inputs. max_num_features : int See Featurizer.max_num_features.", "name": "__init__", "signature": "def __init__(self, max_num_inputs, max_num_features=None)" }, { "docstring": "Learn bundl...
5
stack_v2_sparse_classes_30k_train_007919
Implement the Python class `Featurizer` described below. Class description: Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur. Method signatures and docstrings: - def __init__(self, max_num_inputs, max_num_features=None): Configure the featurize...
Implement the Python class `Featurizer` described below. Class description: Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur. Method signatures and docstrings: - def __init__(self, max_num_inputs, max_num_features=None): Configure the featurize...
85ee5f530717518b1b43ba9a310e4f0d70b290a4
<|skeleton|> class Featurizer: """Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur.""" def __init__(self, max_num_inputs, max_num_features=None): """Configure the featurizer. Parameters --------- max_num_inputs : int See Featuriz...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Featurizer: """Convert inputs to bundles and learn new bundles. Inputs are transformed into bundles, sets of inputs that tend to co-occur.""" def __init__(self, max_num_inputs, max_num_features=None): """Configure the featurizer. Parameters --------- max_num_inputs : int See Featurizer.max_num_in...
the_stack_v2_python_sparse
becca/featurizer.py
microgold/Becca35
train
1
e5f8766a3122e2169e4a176077362189c06bd107
[ "self.data = []\nself.size = size\nself.front = 0\nself.total = 0", "self.total += val\nif len(self.data) == self.size:\n self.total -= self.data[self.front]\n self.data[self.front] = val\n self.front = (self.front + 1) % self.size\nelse:\n self.data.append(val)\nreturn self.total / len(self.data)" ]
<|body_start_0|> self.data = [] self.size = size self.front = 0 self.total = 0 <|end_body_0|> <|body_start_1|> self.total += val if len(self.data) == self.size: self.total -= self.data[self.front] self.data[self.front] = val self.front...
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.data = [] self.size = si...
stack_v2_sparse_classes_36k_train_010167
1,375
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_020898
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
9d0ff0f8705451947a6605ab5ef92bb3e27a7147
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.data = [] self.size = size self.front = 0 self.total = 0 def next(self, val): """:type val: int :rtype: float""" self.total += val if le...
the_stack_v2_python_sparse
premium/amazon/design/moving_average_from_data_stream.py
rayt579/leetcode
train
0
e79c70e3491210e29a50ac3cb8fef7c3023b80db
[ "sortable_fields = self.get_sortable_fields(request)\nordering = request.GET.get('o')\ntry:\n column = abs(int(ordering))\n current_sfield = sortable_fields[column]\nexcept (IndexError, TypeError, ValueError):\n return self.ordering\ncurrent_sfield.update(ordering)\nsort_by = current_sfield.sort_by()\nsfie...
<|body_start_0|> sortable_fields = self.get_sortable_fields(request) ordering = request.GET.get('o') try: column = abs(int(ordering)) current_sfield = sortable_fields[column] except (IndexError, TypeError, ValueError): return self.ordering curr...
Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverInline(PermissionTabularInline, SortableTabularInline): sortable_fields = {'node_link':'n...
SortableTabularInline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SortableTabularInline: """Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverInline(PermissionTabularInline, Sortable...
stack_v2_sparse_classes_36k_train_010168
7,765
no_license
[ { "docstring": "Define dynamic ordering based on request parameters", "name": "get_ordering", "signature": "def get_ordering(self, request)" }, { "docstring": "Hack for get the inline fields SHOWED at admin page NOTE: excludes primary key and hidden foreign key Returns SortableFields list", ...
2
stack_v2_sparse_classes_30k_train_017976
Implement the Python class `SortableTabularInline` described below. Class description: Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverI...
Implement the Python class `SortableTabularInline` described below. Class description: Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverI...
dd798dc9bd3321b17007ff131e7b1288a2cd3c36
<|skeleton|> class SortableTabularInline: """Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverInline(PermissionTabularInline, Sortable...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SortableTabularInline: """Inline that provides sortable functionallity Supports field override for related object attribute sort e.g. sortable_fields = {'node': 'node__name'} should replace sort by node id with sort by node name. Example usage: class SliverInline(PermissionTabularInline, SortableTabularInline...
the_stack_v2_python_sparse
controller/admin/options.py
m00dy/vct-controller
train
2
44a0a60fe395f4a1d0f6ce198eb4dfa8ca45ba7a
[ "if not file_name:\n file_name = config.getStringValue('default_statistic_file')\ntoWrite = statistic\nif append:\n toWrite = StatisticWriter.getAppendedStatistic(statistic=statistic, file_name=file_name)\nCsvWriter.writeListStatic(file_name, list(toWrite.getData().items()), lambda item: [item[0], CsvWriter.s...
<|body_start_0|> if not file_name: file_name = config.getStringValue('default_statistic_file') toWrite = statistic if append: toWrite = StatisticWriter.getAppendedStatistic(statistic=statistic, file_name=file_name) CsvWriter.writeListStatic(file_name, list(toWrite...
Class implementing a static method to write a statistic. Call writeStatistic.
StatisticWriter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatisticWriter: """Class implementing a static method to write a statistic. Call writeStatistic.""" def write(statistic: Statistic=Statistic.getDefaultStatistic(), file_name: str='', config: Config=Config.getDefaultConfig(), append: bool=True) -> None: """Write the given statistic (...
stack_v2_sparse_classes_36k_train_010169
4,209
permissive
[ { "docstring": "Write the given statistic (or the default statistic, when none is given). :param statistic: the statistic to write. Will default to the static default statistic :param file_name: the file to write to. When none is given, this will be read from the config :param config: used to read the file name...
2
null
Implement the Python class `StatisticWriter` described below. Class description: Class implementing a static method to write a statistic. Call writeStatistic. Method signatures and docstrings: - def write(statistic: Statistic=Statistic.getDefaultStatistic(), file_name: str='', config: Config=Config.getDefaultConfig()...
Implement the Python class `StatisticWriter` described below. Class description: Class implementing a static method to write a statistic. Call writeStatistic. Method signatures and docstrings: - def write(statistic: Statistic=Statistic.getDefaultStatistic(), file_name: str='', config: Config=Config.getDefaultConfig()...
27eba8b6038946ce162e9f7bbc0bd23045029d51
<|skeleton|> class StatisticWriter: """Class implementing a static method to write a statistic. Call writeStatistic.""" def write(statistic: Statistic=Statistic.getDefaultStatistic(), file_name: str='', config: Config=Config.getDefaultConfig(), append: bool=True) -> None: """Write the given statistic (...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatisticWriter: """Class implementing a static method to write a statistic. Call writeStatistic.""" def write(statistic: Statistic=Statistic.getDefaultStatistic(), file_name: str='', config: Config=Config.getDefaultConfig(), append: bool=True) -> None: """Write the given statistic (or the defaul...
the_stack_v2_python_sparse
src/core/python/core/io/statistic.py
kaat0/OpenLinTim
train
0
b24b1b037c75d47e73a927b2b4d624f695055678
[ "super(OrderMonitor, self).init_ui()\nself.setToolTip('双击单元格撤单')\nself.itemDoubleClicked.connect(self.cancel_order)", "order = cell.get_data()\nreq = order.create_cancel_request()\nself.main_engine.cancel_order(req, order.gateway_name)" ]
<|body_start_0|> super(OrderMonitor, self).init_ui() self.setToolTip('双击单元格撤单') self.itemDoubleClicked.connect(self.cancel_order) <|end_body_0|> <|body_start_1|> order = cell.get_data() req = order.create_cancel_request() self.main_engine.cancel_order(req, order.gateway_...
Monitor for order data.
OrderMonitor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderMonitor: """Monitor for order data.""" def init_ui(self): """Connect signal.""" <|body_0|> def cancel_order(self, cell: BaseCell) -> None: """Cancel order if cell double clicked.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(OrderMo...
stack_v2_sparse_classes_36k_train_010170
41,585
permissive
[ { "docstring": "Connect signal.", "name": "init_ui", "signature": "def init_ui(self)" }, { "docstring": "Cancel order if cell double clicked.", "name": "cancel_order", "signature": "def cancel_order(self, cell: BaseCell) -> None" } ]
2
null
Implement the Python class `OrderMonitor` described below. Class description: Monitor for order data. Method signatures and docstrings: - def init_ui(self): Connect signal. - def cancel_order(self, cell: BaseCell) -> None: Cancel order if cell double clicked.
Implement the Python class `OrderMonitor` described below. Class description: Monitor for order data. Method signatures and docstrings: - def init_ui(self): Connect signal. - def cancel_order(self, cell: BaseCell) -> None: Cancel order if cell double clicked. <|skeleton|> class OrderMonitor: """Monitor for order...
7f4fd3cd202712b083ed7dc2f346ba4bb1bda6d7
<|skeleton|> class OrderMonitor: """Monitor for order data.""" def init_ui(self): """Connect signal.""" <|body_0|> def cancel_order(self, cell: BaseCell) -> None: """Cancel order if cell double clicked.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderMonitor: """Monitor for order data.""" def init_ui(self): """Connect signal.""" super(OrderMonitor, self).init_ui() self.setToolTip('双击单元格撤单') self.itemDoubleClicked.connect(self.cancel_order) def cancel_order(self, cell: BaseCell) -> None: """Cancel orde...
the_stack_v2_python_sparse
vnpy/trader/ui/widget.py
msincenselee/vnpy
train
359
61d4495028e6fdadadbd108d67e4777505efd28f
[ "FAKE_DATA = False\nrule = None\nif FAKE_DATA:\n rule = {'answer': [{'content': '欢迎光临', 'type': 'text'}, {'content': '1', 'type': 'text'}, {'content': '2', 'type': 'news', 'newses': [{'id': 1, 'title': '标题一'}, {'id': 2, 'title': '标题二'}]}], 'active_type': 2, 'active_days': {'Mon': True, 'Tue': False, 'Wed': True,...
<|body_start_0|> FAKE_DATA = False rule = None if FAKE_DATA: rule = {'answer': [{'content': '欢迎光临', 'type': 'text'}, {'content': '1', 'type': 'text'}, {'content': '2', 'type': 'news', 'newses': [{'id': 1, 'title': '标题一'}, {'id': 2, 'title': '标题二'}]}], 'active_type': 2, 'active_days':...
UnmatchRules
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnmatchRules: def get(request): """未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用""" <|body_0|> def api_put(request): """创建未匹配自动回复消息""" <|body_1|> def api_post(request): """更新关键词自动回复消息""" <|body_2|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_010171
5,825
no_license
[ { "docstring": "未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用", "name": "get", "signature": "def get(request)" }, { "docstring": "创建未匹配自动回复消息", "name": "api_put", "signature": "def api_put(request)" }, { "docstring": "更新关键词自动回复消息", "name": "api_post", "signature": "d...
3
null
Implement the Python class `UnmatchRules` described below. Class description: Implement the UnmatchRules class. Method signatures and docstrings: - def get(request): 未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用 - def api_put(request): 创建未匹配自动回复消息 - def api_post(request): 更新关键词自动回复消息
Implement the Python class `UnmatchRules` described below. Class description: Implement the UnmatchRules class. Method signatures and docstrings: - def get(request): 未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用 - def api_put(request): 创建未匹配自动回复消息 - def api_post(request): 更新关键词自动回复消息 <|skeleton|> class UnmatchR...
8b2f7befe92841bcc35e0e60cac5958ef3f3af54
<|skeleton|> class UnmatchRules: def get(request): """未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用""" <|body_0|> def api_put(request): """创建未匹配自动回复消息""" <|body_1|> def api_post(request): """更新关键词自动回复消息""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UnmatchRules: def get(request): """未匹配自动回复的消息 active_type等于2表示分时段开启,等于1表示始终开启,等于0表示禁用""" FAKE_DATA = False rule = None if FAKE_DATA: rule = {'answer': [{'content': '欢迎光临', 'type': 'text'}, {'content': '1', 'type': 'text'}, {'content': '2', 'type': 'news', 'newses': ...
the_stack_v2_python_sparse
weapp/weixin2/message/unmatch_rules.py
chengdg/weizoom
train
1
0c8215b6e6d8d5bc52a543074e536e5e78292187
[ "user = get_user_model()\nemail = self.cleaned_data['inputemail'].lower()\ntry:\n user.objects.get(email=email)\n raise ValidationError('Email already exist')\nexcept ObjectDoesNotExist:\n return email", "user = get_user_model()\nusername = self.cleaned_data['inputUsername'].lower()\ntry:\n user.objec...
<|body_start_0|> user = get_user_model() email = self.cleaned_data['inputemail'].lower() try: user.objects.get(email=email) raise ValidationError('Email already exist') except ObjectDoesNotExist: return email <|end_body_0|> <|body_start_1|> us...
class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form
CustomUserCreationForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserCreationForm: """class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form""" def clean_email(self): """This m...
stack_v2_sparse_classes_36k_train_010172
3,995
no_license
[ { "docstring": "This method clean email in lower case and test if it exist Raises: ValidationError: \"Email already exist\" Returns: str: email of form in lower case", "name": "clean_email", "signature": "def clean_email(self)" }, { "docstring": "This method clean pseudo in lower case and test i...
4
stack_v2_sparse_classes_30k_train_012512
Implement the Python class `CustomUserCreationForm` described below. Class description: class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form Method s...
Implement the Python class `CustomUserCreationForm` described below. Class description: class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form Method s...
2f183c3a87a3e34e3edba207b65d86066d06b603
<|skeleton|> class CustomUserCreationForm: """class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form""" def clean_email(self): """This m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomUserCreationForm: """class dor custom user creation form Args: forms Form: super class Form Raises: ValidationError: "Email already exist" ValidationError: "Username already exist" ValidationError: "Password doesn't match" Returns: form: form""" def clean_email(self): """This method clean e...
the_stack_v2_python_sparse
free_chess_gui/auth/forms.py
Anthony10700/P13
train
0
976ef4a4e02f900221e023f10dda42e190459cf7
[ "BaseNet.__init__(self, name=name)\nself.global_net = INetAffine(decay=decay, affine_w_initializer=affine_w_initializer, affine_b_initializer=affine_b_initializer, acti_func=acti_func, name='inet-global')\nself.local_net = INetDense(decay=decay, disp_w_initializer=disp_w_initializer, disp_b_initializer=disp_b_initi...
<|body_start_0|> BaseNet.__init__(self, name=name) self.global_net = INetAffine(decay=decay, affine_w_initializer=affine_w_initializer, affine_b_initializer=affine_b_initializer, acti_func=acti_func, name='inet-global') self.local_net = INetDense(decay=decay, disp_w_initializer=disp_w_initialize...
### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Networks for Multimodal Image Registration, Medi...
INetHybridPreWarp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class INetHybridPreWarp: """### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Net...
stack_v2_sparse_classes_36k_train_010173
7,784
permissive
[ { "docstring": ":param decay: float, regularisation decay :param affine_w_initializer: weight initialisation for affine registration network :param affine_b_initializer: bias initialisation for affine registration network :param disp_w_initializer: weight initialisation for dense registration network :param dis...
2
stack_v2_sparse_classes_30k_train_000598
Implement the Python class `INetHybridPreWarp` described below. Class description: ### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Wea...
Implement the Python class `INetHybridPreWarp` described below. Class description: ### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Wea...
67db048685705e36622bc2851b4c7794e56065ad
<|skeleton|> class INetHybridPreWarp: """### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Net...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class INetHybridPreWarp: """### Description Re-implementation of the registration network proposed in: Hu et al., Label-driven weakly-supervised learning for multimodal deformable image registration, arXiv:1711.01666 https://arxiv.org/abs/1711.01666 Hu et al., Weakly-Supervised Convolutional Neural Networks for Mul...
the_stack_v2_python_sparse
niftynet/network/interventional_hybrid_net.py
BRAINSia/NiftyNet
train
0
2fc34223ff7e19ba468a622f26857279da92dbc6
[ "super().__init__()\nself.n = n\nself.D = D\nself.W = W\nself.in_channels_xyz = in_channels_xyz\nself.in_channels_dir = in_channels_dir\nself.skips = skips\nif topk > 0:\n StackedFcLayers = StackedFcSlow\nelse:\n StackedFcLayers = StackedFcDense\nfor i in range(D):\n if i == 0:\n layer = StackedFcLa...
<|body_start_0|> super().__init__() self.n = n self.D = D self.W = W self.in_channels_xyz = in_channels_xyz self.in_channels_dir = in_channels_dir self.skips = skips if topk > 0: StackedFcLayers = StackedFcSlow else: Stacked...
Nerflets.
Nerflets
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Nerflets: """Nerflets.""" def __init__(self, n, D, W, in_channels_xyz=63, in_channels_dir=27, skips=[4], with_semantics=False, n_classes=6, topk=0): """n: number of nerflets D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: numbe...
stack_v2_sparse_classes_36k_train_010174
8,749
permissive
[ { "docstring": "n: number of nerflets D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in t...
2
null
Implement the Python class `Nerflets` described below. Class description: Nerflets. Method signatures and docstrings: - def __init__(self, n, D, W, in_channels_xyz=63, in_channels_dir=27, skips=[4], with_semantics=False, n_classes=6, topk=0): n: number of nerflets D: number of layers for density (sigma) encoder W: nu...
Implement the Python class `Nerflets` described below. Class description: Nerflets. Method signatures and docstrings: - def __init__(self, n, D, W, in_channels_xyz=63, in_channels_dir=27, skips=[4], with_semantics=False, n_classes=6, topk=0): n: number of nerflets D: number of layers for density (sigma) encoder W: nu...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class Nerflets: """Nerflets.""" def __init__(self, n, D, W, in_channels_xyz=63, in_channels_dir=27, skips=[4], with_semantics=False, n_classes=6, topk=0): """n: number of nerflets D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: numbe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Nerflets: """Nerflets.""" def __init__(self, n, D, W, in_channels_xyz=63, in_channels_dir=27, skips=[4], with_semantics=False, n_classes=6, topk=0): """n: number of nerflets D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input ch...
the_stack_v2_python_sparse
nerflets/models/nerf.py
Jimmy-INL/google-research
train
1
2a2be11a0d0379ccdf33e5e0db3d05ff1e40b26f
[ "super(Sensor, self).__init__()\nself.link = link\nself.type = sensor_type if sensor_type is not None else sensor.type\nself.is_virtual = getattr(sensor, 'is_virtual', False)\nself.sensor = sensor\nself.part_id = part_id", "attrs = super(Sensor, self).render_attributes()\nattrs.update({'link': self.link.name, 'pa...
<|body_start_0|> super(Sensor, self).__init__() self.link = link self.type = sensor_type if sensor_type is not None else sensor.type self.is_virtual = getattr(sensor, 'is_virtual', False) self.sensor = sensor self.part_id = part_id <|end_body_0|> <|body_start_1|> ...
Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo.
Sensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sensor: """Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo.""" def __init__(self, part_id, link, sensor, sensor_type=None): """:param link: :type link: Link :param part_id: ID of the part this sensor ...
stack_v2_sparse_classes_36k_train_010175
4,432
permissive
[ { "docstring": ":param link: :type link: Link :param part_id: ID of the part this sensor belongs to, required to identify the corresponding input neuron(s). :type part_id: str :param sensor: SDF element for this sensor, or a `VirtualSensor` instance if applicable. :type sensor: SdfSensor|VirtualSensor :param se...
3
null
Implement the Python class `Sensor` described below. Class description: Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo. Method signatures and docstrings: - def __init__(self, part_id, link, sensor, sensor_type=None): :param link: :ty...
Implement the Python class `Sensor` described below. Class description: Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo. Method signatures and docstrings: - def __init__(self, part_id, link, sensor, sensor_type=None): :param link: :ty...
70e65320a28fe04e121145b2cdde289d3052728a
<|skeleton|> class Sensor: """Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo.""" def __init__(self, part_id, link, sensor, sensor_type=None): """:param link: :type link: Link :param part_id: ID of the part this sensor ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sensor: """Plugin sensor base class. This is used to communicate sensor configuration through the SDF plugin to the model controller in Gazebo.""" def __init__(self, part_id, link, sensor, sensor_type=None): """:param link: :type link: Link :param part_id: ID of the part this sensor belongs to, r...
the_stack_v2_python_sparse
revolve/build/sdf/sensor.py
ElteHupkes/revolve
train
0
4cdcd2254e219ca22f778cf162069424188aa01a
[ "super().__init__()\nself.in_dim = in_dim\nself.r_dim = r_dim\nself.attention_dims = attention_dims\nif probabilistic_dims is None:\n self.probabilistic_dims = [self.r_dim, self.r_dim]\nelse:\n self.probabilistic_dims = probabilistic_dims\nself.self_att = self_att\nself.self_attentive_network = SelfAttentiveV...
<|body_start_0|> super().__init__() self.in_dim = in_dim self.r_dim = r_dim self.attention_dims = attention_dims if probabilistic_dims is None: self.probabilistic_dims = [self.r_dim, self.r_dim] else: self.probabilistic_dims = probabilistic_dims ...
Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.
AttentiveProbabilisticEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentiveProbabilisticEncoder: """Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.""" def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001):...
stack_v2_sparse_classes_36k_train_010176
16,175
no_license
[ { "docstring": ":param in_dim: An integer describing the dimensionality of the input to the encoder; in this case the sum of x_dim and y_dim :param r_dim: An integer describing the dimensionality of the embedding, r_i :param encoder_n_hidden: An integer describing the number of hidden layers in the neural netwo...
2
stack_v2_sparse_classes_30k_train_003402
Implement the Python class `AttentiveProbabilisticEncoder` described below. Class description: Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only. Method signatures and docstrings: - def __init__(self, in_dim, r_dim, att...
Implement the Python class `AttentiveProbabilisticEncoder` described below. Class description: Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only. Method signatures and docstrings: - def __init__(self, in_dim, r_dim, att...
de60f831ee082ab2ae232c498cf2755da7c14c27
<|skeleton|> class AttentiveProbabilisticEncoder: """Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.""" def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttentiveProbabilisticEncoder: """Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.""" def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001): """:...
the_stack_v2_python_sparse
models/networks/np_networks.py
PenelopeJones/neural_processes
train
4
6f5dd294ad55df4bafaf58136d7f79820b3dca5a
[ "self.graph = graph\nself.mst = None\nself.distance = dict(((node, float('inf')) for node in self.graph.iternodes()))\nself.parent = dict(((node, None) for node in self.graph.iternodes()))\nself._in_queue = dict(((node, True) for node in self.graph.iternodes()))\nself._pq = PriorityQueue()", "if source is None:\n...
<|body_start_0|> self.graph = graph self.mst = None self.distance = dict(((node, float('inf')) for node in self.graph.iternodes())) self.parent = dict(((node, None) for node in self.graph.iternodes())) self._in_queue = dict(((node, True) for node in self.graph.iternodes())) ...
Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, private
PrimMSTWithEdges
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrimMSTWithEdges: """Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, private""" def __...
stack_v2_sparse_classes_36k_train_010177
14,685
permissive
[ { "docstring": "The algorithm initialization.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self, source=None)" }, { "docstring": "The minimum spanning tree is built.", "name": "...
3
stack_v2_sparse_classes_30k_train_000984
Implement the Python class `PrimMSTWithEdges` described below. Class description: Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq :...
Implement the Python class `PrimMSTWithEdges` described below. Class description: Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq :...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class PrimMSTWithEdges: """Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, private""" def __...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrimMSTWithEdges: """Prim's algorithm for finding a minimum spanning tree. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, private""" def __init__(self, ...
the_stack_v2_python_sparse
graphtheory/spanningtrees/prim.py
kgashok/graphs-dict
train
0
1e6c10a940ae3b54e24efb2013c27b872b606985
[ "logger.info(f'Ecommerce loader is loaded with catalog {catalog}')\nif not isinstance(catalog, list):\n catalog = [catalog]\nec_data_global: List[Any] = []\ndata_path = Path(expand_path(data_path))\nif not is_done(data_path):\n self._download_data(data_path)\nif data_path.is_dir():\n for fname in data_path...
<|body_start_0|> logger.info(f'Ecommerce loader is loaded with catalog {catalog}') if not isinstance(catalog, list): catalog = [catalog] ec_data_global: List[Any] = [] data_path = Path(expand_path(data_path)) if not is_done(data_path): self._download_data(...
Class to download and load ecommerce data catalog
AmazonEcommerceReader
[ "Python-2.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AmazonEcommerceReader: """Class to download and load ecommerce data catalog""" def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: """Load data from specific catalog Parameters: data_path: where the dataset is located catalog: names of the spe...
stack_v2_sparse_classes_36k_train_010178
3,627
permissive
[ { "docstring": "Load data from specific catalog Parameters: data_path: where the dataset is located catalog: names of the specific subcategories Returns: dataset: loaded dataset", "name": "read", "signature": "def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]" ...
3
null
Implement the Python class `AmazonEcommerceReader` described below. Class description: Class to download and load ecommerce data catalog Method signatures and docstrings: - def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: Load data from specific catalog Parameters: data_pat...
Implement the Python class `AmazonEcommerceReader` described below. Class description: Class to download and load ecommerce data catalog Method signatures and docstrings: - def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: Load data from specific catalog Parameters: data_pat...
65f69dfb898f5444cc2c98ae03ec7b3f44266df2
<|skeleton|> class AmazonEcommerceReader: """Class to download and load ecommerce data catalog""" def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: """Load data from specific catalog Parameters: data_path: where the dataset is located catalog: names of the spe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AmazonEcommerceReader: """Class to download and load ecommerce data catalog""" def read(self, data_path: str, catalog: list, **kwargs) -> Dict[str, List[Tuple[Any, Any]]]: """Load data from specific catalog Parameters: data_path: where the dataset is located catalog: names of the specific subcate...
the_stack_v2_python_sparse
deeppavlov/dataset_readers/amazon_ecommerce_reader.py
vintagexav/DeepPavlov
train
2
3f2c58771047de95642c976bcd07dff68c672bab
[ "self.generator = dictGenerator\nself.site = pywikibot.Site('commons', 'commons')\nself.repo = pywikibot.Site().data_repository()\nself.create = create", "for metadata in self.generator:\n grave_item = None\n if metadata.get('wikidata'):\n grave_item = pywikibot.ItemPage(self.repo, title=metadata.get...
<|body_start_0|> self.generator = dictGenerator self.site = pywikibot.Site('commons', 'commons') self.repo = pywikibot.Site().data_repository() self.create = create <|end_body_0|> <|body_start_1|> for metadata in self.generator: grave_item = None if metad...
A bot to enrich and create paintings on Wikidata
GraveBot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraveBot: """A bot to enrich and create paintings on Wikidata""" def __init__(self, dictGenerator, create=False): """Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you...
stack_v2_sparse_classes_36k_train_010179
13,014
no_license
[ { "docstring": "Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you want to create new items or just update existing", "name": "__init__", "signature": "def __init__(self, dictGenerator, c...
5
null
Implement the Python class `GraveBot` described below. Class description: A bot to enrich and create paintings on Wikidata Method signatures and docstrings: - def __init__(self, dictGenerator, create=False): Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'id...
Implement the Python class `GraveBot` described below. Class description: A bot to enrich and create paintings on Wikidata Method signatures and docstrings: - def __init__(self, dictGenerator, create=False): Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'id...
99a96e49cfe6b2d3151da7ad5469792d80171be3
<|skeleton|> class GraveBot: """A bot to enrich and create paintings on Wikidata""" def __init__(self, dictGenerator, create=False): """Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraveBot: """A bot to enrich and create paintings on Wikidata""" def __init__(self, dictGenerator, create=False): """Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you want to crea...
the_stack_v2_python_sparse
bot/wikidata/pere-lachaise_import.py
multichill/toollabs
train
18
770b9820c2d24942f223a2a60425a3342850966b
[ "if resource_name is not None:\n if is_valid_ipv4(resource_name):\n resource_name = resource_name + '::inst0::INSTR'\n else:\n logger.error('Invalid IP address for BNC845: {}.'.format(resource_name))\nsuper(BNC845, self).__init__(resource_name, *args, **kwargs)", "if resource_name is not None:...
<|body_start_0|> if resource_name is not None: if is_valid_ipv4(resource_name): resource_name = resource_name + '::inst0::INSTR' else: logger.error('Invalid IP address for BNC845: {}.'.format(resource_name)) super(BNC845, self).__init__(resource_na...
SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. output: Toggle RF signal output on/off. pulse: Toggle RF pulsed mode on/off...
BNC845
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BNC845: """SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. output: Toggle RF signal output on/off. p...
stack_v2_sparse_classes_36k_train_010180
4,136
permissive
[ { "docstring": "Berkely Nucleonics BNC845-M RF Signal Generator Args: resource_name: The IP address of the source to conenct to, as string.", "name": "__init__", "signature": "def __init__(self, resource_name=None, *args, **kwargs)" }, { "docstring": "Connect to the RF source via a specified phy...
2
stack_v2_sparse_classes_30k_train_017225
Implement the Python class `BNC845` described below. Class description: SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. ou...
Implement the Python class `BNC845` described below. Class description: SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. ou...
7f68f19dcda4a8937a10bd52270c883f2cf63fcb
<|skeleton|> class BNC845: """SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. output: Toggle RF signal output on/off. p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BNC845: """SCPI instrument driver for Berkely Nucleonics BNC845-M RF Signal Generator. Properties: frequency: Set the RF generator frequency, in Hz. 0.01-20 GHz. power: Set the RF generator output power, in dBm. No effect, BNC845M output is always +16dBm. output: Toggle RF signal output on/off. pulse: Toggle ...
the_stack_v2_python_sparse
src/auspex/instruments/bnc.py
BBN-Q/Auspex
train
35
b73c9813a5eeeefc76d8a3e11dbda6456ee83c45
[ "if not coins:\n return -1\nif amount == 0:\n return 0\nMAX = 2147483647\ndp = [0] + [MAX] * amount\nfor i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1\nreturn dp[amount] if dp[amount] < MAX else -1", "if not coins:\n return -1\nif amount == 0:\n ret...
<|body_start_0|> if not coins: return -1 if amount == 0: return 0 MAX = 2147483647 dp = [0] + [MAX] * amount for i in range(1, amount + 1): dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1 return dp[amount] if dp[amoun...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def coinChange(self, coins, amount): """:type coins: List[int] :type amount: int :rtype: int""" <|body_0|> def coinChange(self, coins, amount): """:type coins: List[int] :type amount: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_010181
2,201
no_license
[ { "docstring": ":type coins: List[int] :type amount: int :rtype: int", "name": "coinChange", "signature": "def coinChange(self, coins, amount)" }, { "docstring": ":type coins: List[int] :type amount: int :rtype: int", "name": "coinChange", "signature": "def coinChange(self, coins, amount...
2
stack_v2_sparse_classes_30k_train_011723
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int - def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int - def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ...
88da6b274e49ce97d432e1f4d4de8efa55593836
<|skeleton|> class Solution: def coinChange(self, coins, amount): """:type coins: List[int] :type amount: int :rtype: int""" <|body_0|> def coinChange(self, coins, amount): """:type coins: List[int] :type amount: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def coinChange(self, coins, amount): """:type coins: List[int] :type amount: int :rtype: int""" if not coins: return -1 if amount == 0: return 0 MAX = 2147483647 dp = [0] + [MAX] * amount for i in range(1, amount + 1): ...
the_stack_v2_python_sparse
4th/homework_9/id_69/322-CoinChange.py
StuQAlgorithm/AlgorithmHomework
train
6
aaca2af582c834401ab3bf841da77663d419e736
[ "def build(left, right):\n if left > right:\n return None\n mid = nums.index(max(nums[left:right + 1]))\n root = TreeNode(nums[mid])\n root.left = build(left, mid - 1)\n root.right = build(mid + 1, right)\n return root\nreturn build(0, len(nums) - 1)", "stack = []\nfor n in nums:\n nod...
<|body_start_0|> def build(left, right): if left > right: return None mid = nums.index(max(nums[left:right + 1])) root = TreeNode(nums[mid]) root.left = build(left, mid - 1) root.right = build(mid + 1, right) return root ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def constructMaximumBinaryTree(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_0|> def constructMaximumBinaryTree(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> def b...
stack_v2_sparse_classes_36k_train_010182
2,219
no_license
[ { "docstring": ":type nums: List[int] :rtype: TreeNode", "name": "constructMaximumBinaryTree", "signature": "def constructMaximumBinaryTree(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: TreeNode", "name": "constructMaximumBinaryTree", "signature": "def constructMaximumBin...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructMaximumBinaryTree(self, nums): :type nums: List[int] :rtype: TreeNode - def constructMaximumBinaryTree(self, nums): :type nums: List[int] :rtype: TreeNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructMaximumBinaryTree(self, nums): :type nums: List[int] :rtype: TreeNode - def constructMaximumBinaryTree(self, nums): :type nums: List[int] :rtype: TreeNode <|skeleto...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def constructMaximumBinaryTree(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_0|> def constructMaximumBinaryTree(self, nums): """:type nums: List[int] :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def constructMaximumBinaryTree(self, nums): """:type nums: List[int] :rtype: TreeNode""" def build(left, right): if left > right: return None mid = nums.index(max(nums[left:right + 1])) root = TreeNode(nums[mid]) root.le...
the_stack_v2_python_sparse
src/lt_654.py
oxhead/CodingYourWay
train
0
b7099be81f1b1317a457e9f947bf6c8ecc0e46c7
[ "categories = Category.objects.eligible_for_demos()\ncategories = categories.order_by('?')[:10]\nfor n, cat in enumerate(categories):\n yield models.CategoryUsage(demonstration=self.object, category=cat, position=n)", "usages = self.object.categoryusage_set.all()\npending = usages.exclude(chance__finished_at__...
<|body_start_0|> categories = Category.objects.eligible_for_demos() categories = categories.order_by('?')[:10] for n, cat in enumerate(categories): yield models.CategoryUsage(demonstration=self.object, category=cat, position=n) <|end_body_0|> <|body_start_1|> usages = self.o...
Offers the time for user read the terms of usage.
DemonstrationStartView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DemonstrationStartView: """Offers the time for user read the terms of usage.""" def get_new_usages(self): """Chooses 10 random categories to be used for demonstration.""" <|body_0|> def get_success_url(self): """Clears any previous attempt and start/restart the d...
stack_v2_sparse_classes_36k_train_010183
10,067
no_license
[ { "docstring": "Chooses 10 random categories to be used for demonstration.", "name": "get_new_usages", "signature": "def get_new_usages(self)" }, { "docstring": "Clears any previous attempt and start/restart the demonstration for the user.", "name": "get_success_url", "signature": "def g...
2
null
Implement the Python class `DemonstrationStartView` described below. Class description: Offers the time for user read the terms of usage. Method signatures and docstrings: - def get_new_usages(self): Chooses 10 random categories to be used for demonstration. - def get_success_url(self): Clears any previous attempt an...
Implement the Python class `DemonstrationStartView` described below. Class description: Offers the time for user read the terms of usage. Method signatures and docstrings: - def get_new_usages(self): Chooses 10 random categories to be used for demonstration. - def get_success_url(self): Clears any previous attempt an...
e2d24a82462a735fc722f0b228be04a4495185c1
<|skeleton|> class DemonstrationStartView: """Offers the time for user read the terms of usage.""" def get_new_usages(self): """Chooses 10 random categories to be used for demonstration.""" <|body_0|> def get_success_url(self): """Clears any previous attempt and start/restart the d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DemonstrationStartView: """Offers the time for user read the terms of usage.""" def get_new_usages(self): """Chooses 10 random categories to be used for demonstration.""" categories = Category.objects.eligible_for_demos() categories = categories.order_by('?')[:10] for n, c...
the_stack_v2_python_sparse
demonstrations/views/main.py
fredericosachweh/amostra2
train
0
f3853432fb03d2156f017c26e3788b82d4517541
[ "self.res = 0\nvisited = [[False for _ in range(n)] for _ in range(m)]\nself.dfs(m, n, k, 0, 0, visited)\nreturn self.res", "if row < 0 or row >= m or col < 0 or (col >= n) or visited[row][col] or (not self.valid(row, col, k)):\n return\nvisited[row][col] = True\nself.res += 1\nself.dfs(m, n, k, row + 1, col, ...
<|body_start_0|> self.res = 0 visited = [[False for _ in range(n)] for _ in range(m)] self.dfs(m, n, k, 0, 0, visited) return self.res <|end_body_0|> <|body_start_1|> if row < 0 or row >= m or col < 0 or (col >= n) or visited[row][col] or (not self.valid(row, col, k)): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def movingCount(self, m, n, k): """Args: m: int n: int k: int Return: int""" <|body_0|> def dfs(self, m, n, k, row, col, visited): """Args: m: int n: int k: int row: int col: int visited: list[bool]""" <|body_1|> def valid(self, row, col, k): ...
stack_v2_sparse_classes_36k_train_010184
1,346
no_license
[ { "docstring": "Args: m: int n: int k: int Return: int", "name": "movingCount", "signature": "def movingCount(self, m, n, k)" }, { "docstring": "Args: m: int n: int k: int row: int col: int visited: list[bool]", "name": "dfs", "signature": "def dfs(self, m, n, k, row, col, visited)" },...
3
stack_v2_sparse_classes_30k_train_015786
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def movingCount(self, m, n, k): Args: m: int n: int k: int Return: int - def dfs(self, m, n, k, row, col, visited): Args: m: int n: int k: int row: int col: int visited: list[boo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def movingCount(self, m, n, k): Args: m: int n: int k: int Return: int - def dfs(self, m, n, k, row, col, visited): Args: m: int n: int k: int row: int col: int visited: list[boo...
101bce2fac8b188a4eb2f5e017293d21ad0ecb21
<|skeleton|> class Solution: def movingCount(self, m, n, k): """Args: m: int n: int k: int Return: int""" <|body_0|> def dfs(self, m, n, k, row, col, visited): """Args: m: int n: int k: int row: int col: int visited: list[bool]""" <|body_1|> def valid(self, row, col, k): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def movingCount(self, m, n, k): """Args: m: int n: int k: int Return: int""" self.res = 0 visited = [[False for _ in range(n)] for _ in range(m)] self.dfs(m, n, k, 0, 0, visited) return self.res def dfs(self, m, n, k, row, col, visited): """Args: ...
the_stack_v2_python_sparse
剑指offer/剑指 Offer 13. 机器人的运动范围.py
AiZhanghan/Leetcode
train
0
bf591b69389a0101c355a618358a9bd142eabafc
[ "slow = head\ncurr = head\nwhile curr and curr.next:\n slow = slow.next\n curr = curr.next.next\nnew_head = self.reverse(slow)\nwhile new_head:\n if head.val != new_head.val:\n return False\n head = head.next\n new_head = new_head.next\nreturn True", "new_head = None\nc = head\nwhile c:\n ...
<|body_start_0|> slow = head curr = head while curr and curr.next: slow = slow.next curr = curr.next.next new_head = self.reverse(slow) while new_head: if head.val != new_head.val: return False head = head.next ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def reverse(self, head): """Reverse second half of linked list""" <|body_1|> <|end_skeleton|> <|body_start_0|> slow = head curr = head while c...
stack_v2_sparse_classes_36k_train_010185
1,580
no_license
[ { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, head)" }, { "docstring": "Reverse second half of linked list", "name": "reverse", "signature": "def reverse(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_008366
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head): :type head: ListNode :rtype: bool - def reverse(self, head): Reverse second half of linked list
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head): :type head: ListNode :rtype: bool - def reverse(self, head): Reverse second half of linked list <|skeleton|> class Solution: def isPalindrome(...
1639a4b13c692d87c658a7e0a11212bf0e98d443
<|skeleton|> class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def reverse(self, head): """Reverse second half of linked list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" slow = head curr = head while curr and curr.next: slow = slow.next curr = curr.next.next new_head = self.reverse(slow) while new_head: if head.val...
the_stack_v2_python_sparse
easy/isPalindrome.py
Hashah1/Leetcode-Practice
train
0
7a70f4187813414faae3b899984e6b612d518e8a
[ "if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n tango.Except.throw_exception(f'Abort() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Abort command on CspSubarrayLeafNode.', 'cspsubarrayleafnode.Abort()', tango.ErrSeverity.ERR)\nthis_serve...
<|body_start_0|> if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]: tango.Except.throw_exception(f'Abort() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Abort command on CspSubarrayLeafNode.', 'cspsubarrayleafnode.Abort()', tango.E...
A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray.
AbortCommand
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbortCommand: """A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command is allowed ...
stack_v2_sparse_classes_36k_train_010186
4,767
permissive
[ { "docstring": "Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state", "name": "check_allowed", "signature": ...
3
stack_v2_sparse_classes_30k_train_007241
Implement the Python class `AbortCommand` described below. Class description: A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray. Method signatures and docstrings: - def check_allowed(self): Checks whether this command is allowed to be run in curre...
Implement the Python class `AbortCommand` described below. Class description: A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray. Method signatures and docstrings: - def check_allowed(self): Checks whether this command is allowed to be run in curre...
7ee65a9c8dada9b28893144b372a398bd0646195
<|skeleton|> class AbortCommand: """A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command is allowed ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AbortCommand: """A class for CSPSubarrayLeafNode's Abort() command. Command to abort the current operation being done on the CSP Subarray.""" def check_allowed(self): """Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in ...
the_stack_v2_python_sparse
temp_src/ska_tmc_cspsubarrayleafnode_mid/abort_command.py
ska-telescope/tmc-prototype
train
4
f54606f8d5746eecda25cec1c99b1ab0058a9ce7
[ "layout = self.layout\nfor i in range(len(self.phobos_data)):\n name = self.phobos_data[i].name[2:].replace('_', ' ')\n self.phobos_data[i].draw(layout, name)\nif self.annotation_checks:\n box = layout.box()\n box.label(text='Include annotations:')\n for i in range(len(self.annotation_checks)):\n ...
<|body_start_0|> layout = self.layout for i in range(len(self.phobos_data)): name = self.phobos_data[i].name[2:].replace('_', ' ') self.phobos_data[i].draw(layout, name) if self.annotation_checks: box = layout.box() box.label(text='Include annotati...
Temporary operator to add a generic object.
TempObjAddOperator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TempObjAddOperator: """Temporary operator to add a generic object.""" def draw(self, context): """Args: context: Returns:""" <|body_0|> def invoke(self, context, event): """Args: context: event: Returns:""" <|body_1|> def execute(self, context): ...
stack_v2_sparse_classes_36k_train_010187
17,163
permissive
[ { "docstring": "Args: context: Returns:", "name": "draw", "signature": "def draw(self, context)" }, { "docstring": "Args: context: event: Returns:", "name": "invoke", "signature": "def invoke(self, context, event)" }, { "docstring": "Args: context: Returns:", "name": "execute...
3
null
Implement the Python class `TempObjAddOperator` described below. Class description: Temporary operator to add a generic object. Method signatures and docstrings: - def draw(self, context): Args: context: Returns: - def invoke(self, context, event): Args: context: event: Returns: - def execute(self, context): Args: co...
Implement the Python class `TempObjAddOperator` described below. Class description: Temporary operator to add a generic object. Method signatures and docstrings: - def draw(self, context): Args: context: Returns: - def invoke(self, context, event): Args: context: event: Returns: - def execute(self, context): Args: co...
543d220c65bbee0e23e810d89307e23aa79eb0cd
<|skeleton|> class TempObjAddOperator: """Temporary operator to add a generic object.""" def draw(self, context): """Args: context: Returns:""" <|body_0|> def invoke(self, context, event): """Args: context: event: Returns:""" <|body_1|> def execute(self, context): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TempObjAddOperator: """Temporary operator to add a generic object.""" def draw(self, context): """Args: context: Returns:""" layout = self.layout for i in range(len(self.phobos_data)): name = self.phobos_data[i].name[2:].replace('_', ' ') self.phobos_data[i...
the_stack_v2_python_sparse
phobos/blender/operators/generic.py
dfki-ric/phobos
train
483
9a111069bb59de3a04178f934f5b3cf61d0887ef
[ "sim_id = CommonSimUtils.get_sim_id(sim_info)\nrabbit_hole_service = CommonRabbitHoleUtils.get_rabbit_hole_service()\nrabbit_hole_id = rabbit_hole_service.get_head_rabbit_hole_id(sim_id)\nif rabbit_hole_id is None or rabbit_hole_id < 0:\n return None\nreturn rabbit_hole_id", "if sim_info is None:\n raise As...
<|body_start_0|> sim_id = CommonSimUtils.get_sim_id(sim_info) rabbit_hole_service = CommonRabbitHoleUtils.get_rabbit_hole_service() rabbit_hole_id = rabbit_hole_service.get_head_rabbit_hole_id(sim_id) if rabbit_hole_id is None or rabbit_hole_id < 0: return None return...
Utilities for manipulating Rabbit Holes for Sims.
CommonSimRabbitHoleUtils
[ "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommonSimRabbitHoleUtils: """Utilities for manipulating Rabbit Holes for Sims.""" def get_first_rabbit_hole_id_for_sim(cls, sim_info: SimInfo) -> Union[int, None]: """get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit hole a Sim is in. :param sim_info: An instance of a Sim. :...
stack_v2_sparse_classes_36k_train_010188
5,289
permissive
[ { "docstring": "get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit hole a Sim is in. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The id of the first rabbit hole the Sim is in or None if not found. :rtype: Union[int, None]", "name": "get_first_rabbit_hole_id_for_sim", ...
3
null
Implement the Python class `CommonSimRabbitHoleUtils` described below. Class description: Utilities for manipulating Rabbit Holes for Sims. Method signatures and docstrings: - def get_first_rabbit_hole_id_for_sim(cls, sim_info: SimInfo) -> Union[int, None]: get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit h...
Implement the Python class `CommonSimRabbitHoleUtils` described below. Class description: Utilities for manipulating Rabbit Holes for Sims. Method signatures and docstrings: - def get_first_rabbit_hole_id_for_sim(cls, sim_info: SimInfo) -> Union[int, None]: get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit h...
58e7beb30b9c818b294d35abd2436a0192cd3e82
<|skeleton|> class CommonSimRabbitHoleUtils: """Utilities for manipulating Rabbit Holes for Sims.""" def get_first_rabbit_hole_id_for_sim(cls, sim_info: SimInfo) -> Union[int, None]: """get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit hole a Sim is in. :param sim_info: An instance of a Sim. :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommonSimRabbitHoleUtils: """Utilities for manipulating Rabbit Holes for Sims.""" def get_first_rabbit_hole_id_for_sim(cls, sim_info: SimInfo) -> Union[int, None]: """get_rabbit_hole_id(sim_info) Retrieve the id of the rabbit hole a Sim is in. :param sim_info: An instance of a Sim. :type sim_info...
the_stack_v2_python_sparse
Scripts/sims4communitylib/utils/sims/common_sim_rabbit_hole_utils.py
ColonolNutty/Sims4CommunityLibrary
train
183
9242462fd3e4800f63bcc87a5500dda60145900e
[ "geo_api = GeoNamesAPI()\nextra_args = {}\nself.mode = mode\nif self.mode == 'country':\n extra_args.update({'feature_class': 'A', 'feature_code': 'PCLI'})\nresults = geo_api.search(self.q, max_rows=50, name_start=True, **extra_args)\nreturn JsonResponse({'results': [dict(id=geo_api.uri_from_id(item['geonameId']...
<|body_start_0|> geo_api = GeoNamesAPI() extra_args = {} self.mode = mode if self.mode == 'country': extra_args.update({'feature_class': 'A', 'feature_code': 'PCLI'}) results = geo_api.search(self.q, max_rows=50, name_start=True, **extra_args) return JsonRespo...
GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only.
GeoNamesLookup
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeoNamesLookup: """GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only.""" def get(self, request, mode=None, *args, **kwargs): """"Return option list json response.""" <|body_0|> def get_label(self, item): """displa...
stack_v2_sparse_classes_36k_train_010189
39,534
permissive
[ { "docstring": "\"Return option list json response.", "name": "get", "signature": "def get(self, request, mode=None, *args, **kwargs)" }, { "docstring": "display country for context, if available", "name": "get_label", "signature": "def get_label(self, item)" } ]
2
null
Implement the Python class `GeoNamesLookup` described below. Class description: GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only. Method signatures and docstrings: - def get(self, request, mode=None, *args, **kwargs): "Return option list json response. - def get_labe...
Implement the Python class `GeoNamesLookup` described below. Class description: GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only. Method signatures and docstrings: - def get(self, request, mode=None, *args, **kwargs): "Return option list json response. - def get_labe...
6103855f07c2c0123ab21b93b794ea5d5ca39aa2
<|skeleton|> class GeoNamesLookup: """GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only.""" def get(self, request, mode=None, *args, **kwargs): """"Return option list json response.""" <|body_0|> def get_label(self, item): """displa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GeoNamesLookup: """GeoNames ajax lookup for use as autocomplete. Optional mode parameter to restrict to countries only.""" def get(self, request, mode=None, *args, **kwargs): """"Return option list json response.""" geo_api = GeoNamesAPI() extra_args = {} self.mode = mode ...
the_stack_v2_python_sparse
mep/people/views.py
Princeton-CDH/mep-django
train
6
008acc477c6de384db81166439581d21a3140acd
[ "def rserialize(root, string):\n \"\"\" a recursive helper function for the serialize() function.\"\"\"\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return s...
<|body_start_0|> def rserialize(root, string): """ a recursive helper function for the serialize() function.""" if root is None: string += 'None,' else: string += str(root.val) + ',' string = rserialize(root.left, string) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_010190
17,936
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_010181
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
035ef08434fa1ca781a6fb2f9eed3538b7d20c02
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def rserialize(root, string): """ a recursive helper function for the serialize() function.""" if root is None: string += 'None,' else...
the_stack_v2_python_sparse
leetcode_python/Tree/serialize-and-deserialize-binary-tree.py
yennanliu/CS_basics
train
64
f5629e682fd4bc02a02a90ffed28960461a4f6c6
[ "event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason)\nflow.Events.PublishEvent('Audit', event, token=self.token)\nreturn self.ApprovalUrnBuilder(self.client_id.Path(), self.token.username, self.args.reason)", "cli...
<|body_start_0|> event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason) flow.Events.PublishEvent('Audit', event, token=self.token) return self.ApprovalUrnBuilder(self.client_id.Path(), self.token.us...
Grant an approval in an emergency.
BreakGlassGrantClientApprovalFlow
[ "Apache-2.0", "DOC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BreakGlassGrantClientApprovalFlow: """Grant an approval in an emergency.""" def BuildApprovalUrn(self): """Builds approval object urn.""" <|body_0|> def BuildSubjectTitle(self): """Returns the string with subject's title.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_010191
28,119
permissive
[ { "docstring": "Builds approval object urn.", "name": "BuildApprovalUrn", "signature": "def BuildApprovalUrn(self)" }, { "docstring": "Returns the string with subject's title.", "name": "BuildSubjectTitle", "signature": "def BuildSubjectTitle(self)" } ]
2
stack_v2_sparse_classes_30k_train_010932
Implement the Python class `BreakGlassGrantClientApprovalFlow` described below. Class description: Grant an approval in an emergency. Method signatures and docstrings: - def BuildApprovalUrn(self): Builds approval object urn. - def BuildSubjectTitle(self): Returns the string with subject's title.
Implement the Python class `BreakGlassGrantClientApprovalFlow` described below. Class description: Grant an approval in an emergency. Method signatures and docstrings: - def BuildApprovalUrn(self): Builds approval object urn. - def BuildSubjectTitle(self): Returns the string with subject's title. <|skeleton|> class ...
ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e
<|skeleton|> class BreakGlassGrantClientApprovalFlow: """Grant an approval in an emergency.""" def BuildApprovalUrn(self): """Builds approval object urn.""" <|body_0|> def BuildSubjectTitle(self): """Returns the string with subject's title.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BreakGlassGrantClientApprovalFlow: """Grant an approval in an emergency.""" def BuildApprovalUrn(self): """Builds approval object urn.""" event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason...
the_stack_v2_python_sparse
lib/aff4_objects/security.py
defaultnamehere/grr
train
3
ea8e48ee03ef06a913aa6b02068065f5808793cf
[ "spark.sparkContext.setLogLevel('INFO')\nlog4jLogger = spark.sparkContext._jvm.org.apache.log4j\nlogger = log4jLogger.LogManager.getLogger(__name__)\nindex_mapper_handle = globals()['XML2kvpMapper']\n\ndef es_mapper_pt_udf(pt):\n mapper = index_mapper_handle(field_mapper_config=field_mapper_config)\n for row ...
<|body_start_0|> spark.sparkContext.setLogLevel('INFO') log4jLogger = spark.sparkContext._jvm.org.apache.log4j logger = log4jLogger.LogManager.getLogger(__name__) index_mapper_handle = globals()['XML2kvpMapper'] def es_mapper_pt_udf(pt): mapper = index_mapper_handle(...
Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)
ESIndex
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ESIndex: """Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)""" def index_job_to_es_spark(spark, job, records_df, field_mapper_config): """Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance ...
stack_v2_sparse_classes_36k_train_010192
11,830
permissive
[ { "docstring": "Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance from static job methods job (core.models.Job): Job for records records_df (pyspark.sql.DataFrame): records as pyspark DataFrame field_mapper_config (dict): XML2kvp field mapper configurations...
2
stack_v2_sparse_classes_30k_train_004522
Implement the Python class `ESIndex` described below. Class description: Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES) Method signatures and docstrings: - def index_job_to_es_spark(spark, job, records_df, field_mapper_config): Method to index records dataframe into ES Args: ...
Implement the Python class `ESIndex` described below. Class description: Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES) Method signatures and docstrings: - def index_job_to_es_spark(spark, job, records_df, field_mapper_config): Method to index records dataframe into ES Args: ...
eb100ea17193d65485aa6c4a7f05a41b4cab7515
<|skeleton|> class ESIndex: """Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)""" def index_job_to_es_spark(spark, job, records_df, field_mapper_config): """Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ESIndex: """Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)""" def index_job_to_es_spark(spark, job, records_df, field_mapper_config): """Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance from static j...
the_stack_v2_python_sparse
core/spark/es.py
tulibraries/combine
train
1
641545540bcfb7496d5a8ce06bae2ef61738eee0
[ "tp = type(e)\ntb = e.__traceback__\ntraceback_str = 'Traceback (most recent call last):\\n' + ''.join(traceback.format_tb(tb))\ntry:\n attributes = e.get_attributes()\nexcept AttributeError:\n attributes = {}\nreturn (sy.serde.msgpack.serde._simplify(worker, tp.__name__), sy.serde.msgpack.serde._simplify(wor...
<|body_start_0|> tp = type(e) tb = e.__traceback__ traceback_str = 'Traceback (most recent call last):\n' + ''.join(traceback.format_tb(tb)) try: attributes = e.get_attributes() except AttributeError: attributes = {} return (sy.serde.msgpack.serde....
Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high
GetNotPermittedError
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetNotPermittedError: """Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raise...
stack_v2_sparse_classes_36k_train_010193
15,166
permissive
[ { "docstring": "Serialize information about an Exception which was raised to forward it", "name": "simplify", "signature": "def simplify(worker: 'sy.workers.AbstractWorker', e)" }, { "docstring": "Detail and re-raise an Exception forwarded by another worker", "name": "detail", "signature...
2
stack_v2_sparse_classes_30k_train_013977
Implement the Python class `GetNotPermittedError` described below. Class description: Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high Method signatures and docstrings: - def simplify(worker: 'sy.workers.AbstractWorker', e):...
Implement the Python class `GetNotPermittedError` described below. Class description: Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high Method signatures and docstrings: - def simplify(worker: 'sy.workers.AbstractWorker', e):...
cc4765bed880ad38a02505834f63df39e0815328
<|skeleton|> class GetNotPermittedError: """Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raise...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetNotPermittedError: """Raised when calling get on a pointer to a tensor which does not allow get to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raised to forward ...
the_stack_v2_python_sparse
syft/exceptions.py
tudorcebere/PySyft
train
2
c120acd5af964ec3df331bad4fdbd6ba6a8889a2
[ "super(BertAttention, self).__init__()\nself.self1 = BertSelfAttention(config)\nself.output = BertSelfOutput(config)\nself.pruned_heads = set()\nself.view = P.Reshape()\nself.eq = ops.Equal()", "self_outputs = self.self1(hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask)\natt...
<|body_start_0|> super(BertAttention, self).__init__() self.self1 = BertSelfAttention(config) self.output = BertSelfOutput(config) self.pruned_heads = set() self.view = P.Reshape() self.eq = ops.Equal() <|end_body_0|> <|body_start_1|> self_outputs = self.self1(hi...
bert attention
BertAttention
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertAttention: """bert attention""" def __init__(self, config): """init fun""" <|body_0|> def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): """construct fun""" <|body_1|> <|e...
stack_v2_sparse_classes_36k_train_010194
16,172
permissive
[ { "docstring": "init fun", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "construct fun", "name": "construct", "signature": "def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None)"...
2
null
Implement the Python class `BertAttention` described below. Class description: bert attention Method signatures and docstrings: - def __init__(self, config): init fun - def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun
Implement the Python class `BertAttention` described below. Class description: bert attention Method signatures and docstrings: - def __init__(self, config): init fun - def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun <|sk...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class BertAttention: """bert attention""" def __init__(self, config): """init fun""" <|body_0|> def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): """construct fun""" <|body_1|> <|e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BertAttention: """bert attention""" def __init__(self, config): """init fun""" super(BertAttention, self).__init__() self.self1 = BertSelfAttention(config) self.output = BertSelfOutput(config) self.pruned_heads = set() self.view = P.Reshape() self.e...
the_stack_v2_python_sparse
research/nlp/luke/src/luke/robert.py
mindspore-ai/models
train
301
311058ba9aa7fb7985af4c25b0aaeb5b8e92d78d
[ "interpol = pero.LogInterpol()\nself.assertEqual(interpol.normalize(10, 1, 100), 0.5)\nself.assertEqual(interpol.denormalize(0.5, 1, 100), 10)\nself.assertAlmostEqual(interpol.normalize(0.1, 1, 100), -0.5, 10)\nself.assertAlmostEqual(interpol.denormalize(-0.5, 1, 100), 0.1, 10)\nself.assertAlmostEqual(interpol.norm...
<|body_start_0|> interpol = pero.LogInterpol() self.assertEqual(interpol.normalize(10, 1, 100), 0.5) self.assertEqual(interpol.denormalize(0.5, 1, 100), 10) self.assertAlmostEqual(interpol.normalize(0.1, 1, 100), -0.5, 10) self.assertAlmostEqual(interpol.denormalize(-0.5, 1, 100)...
Test case for linear interpolator.
TestCase
[ "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-commercial-license", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCase: """Test case for linear interpolator.""" def test_log10(self): """Tests whether interpolator works for log10 range.""" <|body_0|> def test_log2(self): """Tests whether interpolator works for log2 range.""" <|body_1|> def test_arrays(self): ...
stack_v2_sparse_classes_36k_train_010195
2,040
permissive
[ { "docstring": "Tests whether interpolator works for log10 range.", "name": "test_log10", "signature": "def test_log10(self)" }, { "docstring": "Tests whether interpolator works for log2 range.", "name": "test_log2", "signature": "def test_log2(self)" }, { "docstring": "Tests whe...
3
null
Implement the Python class `TestCase` described below. Class description: Test case for linear interpolator. Method signatures and docstrings: - def test_log10(self): Tests whether interpolator works for log10 range. - def test_log2(self): Tests whether interpolator works for log2 range. - def test_arrays(self): Test...
Implement the Python class `TestCase` described below. Class description: Test case for linear interpolator. Method signatures and docstrings: - def test_log10(self): Tests whether interpolator works for log10 range. - def test_log2(self): Tests whether interpolator works for log2 range. - def test_arrays(self): Test...
d59b1bc056f3037b7b7ab635b6deb41120612965
<|skeleton|> class TestCase: """Test case for linear interpolator.""" def test_log10(self): """Tests whether interpolator works for log10 range.""" <|body_0|> def test_log2(self): """Tests whether interpolator works for log2 range.""" <|body_1|> def test_arrays(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCase: """Test case for linear interpolator.""" def test_log10(self): """Tests whether interpolator works for log10 range.""" interpol = pero.LogInterpol() self.assertEqual(interpol.normalize(10, 1, 100), 0.5) self.assertEqual(interpol.denormalize(0.5, 1, 100), 10) ...
the_stack_v2_python_sparse
unittests/scales/test_log.py
xxao/pero
train
31
d5ed7c2006d589b4d866b7c55e5b49cd11e0caf7
[ "elements = set(arr)\nsorted_ranks = sorted(list(elements))\nres = []\nfor x in arr:\n res.append(sorted_ranks.index(x) + 1)\nreturn res", "elements = list(set(arr))\nsorted_ranks = sorted(elements)\nd = {}\nfor i, x in enumerate(sorted_ranks):\n d[x] = i + 1\nres = []\nfor x in arr:\n res.append(d[x])\n...
<|body_start_0|> elements = set(arr) sorted_ranks = sorted(list(elements)) res = [] for x in arr: res.append(sorted_ranks.index(x) + 1) return res <|end_body_0|> <|body_start_1|> elements = list(set(arr)) sorted_ranks = sorted(elements) d = {}...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def arrayRankTransform0(self, arr: List[int]) -> List[int]: """Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The larger the element, the larger the rank; - If two elements are equal, their rank must be the same; - R...
stack_v2_sparse_classes_36k_train_010196
1,061
no_license
[ { "docstring": "Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The larger the element, the larger the rank; - If two elements are equal, their rank must be the same; - Rank should be as small as possible.", "name": "arrayRankTransform0", "sig...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def arrayRankTransform0(self, arr: List[int]) -> List[int]: Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The large...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def arrayRankTransform0(self, arr: List[int]) -> List[int]: Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The large...
95a86cbbca28d0c0f6d72d28a2f1cb5a86327934
<|skeleton|> class Solution: def arrayRankTransform0(self, arr: List[int]) -> List[int]: """Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The larger the element, the larger the rank; - If two elements are equal, their rank must be the same; - R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def arrayRankTransform0(self, arr: List[int]) -> List[int]: """Purpose: Replaces each element in integer array with its rank. Note: - Rank is an integer starting from 1; - The larger the element, the larger the rank; - If two elements are equal, their rank must be the same; - Rank should be ...
the_stack_v2_python_sparse
rankTransformArr.py
tashakim/puzzles_python
train
8
1285e3ae0f167499f21506afefb5a0da279b101e
[ "main = MainPage()\nmain.goto_register().register()\nsleep(3)", "main = MainPage()\nmain.goto_login().goto_register().register()\nsleep(3)" ]
<|body_start_0|> main = MainPage() main.goto_register().register() sleep(3) <|end_body_0|> <|body_start_1|> main = MainPage() main.goto_login().goto_register().register() sleep(3) <|end_body_1|>
TestRegister
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRegister: def test_register(self): """从首页-注册页 :return:""" <|body_0|> def test_login_register(self): """从首页-登录页-注册页 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> main = MainPage() main.goto_register().register() sleep(3...
stack_v2_sparse_classes_36k_train_010197
673
no_license
[ { "docstring": "从首页-注册页 :return:", "name": "test_register", "signature": "def test_register(self)" }, { "docstring": "从首页-登录页-注册页 :return:", "name": "test_login_register", "signature": "def test_login_register(self)" } ]
2
null
Implement the Python class `TestRegister` described below. Class description: Implement the TestRegister class. Method signatures and docstrings: - def test_register(self): 从首页-注册页 :return: - def test_login_register(self): 从首页-登录页-注册页 :return:
Implement the Python class `TestRegister` described below. Class description: Implement the TestRegister class. Method signatures and docstrings: - def test_register(self): 从首页-注册页 :return: - def test_login_register(self): 从首页-登录页-注册页 :return: <|skeleton|> class TestRegister: def test_register(self): ""...
6648dbfb640b065ff2c76cb6889a8f9e4f124b91
<|skeleton|> class TestRegister: def test_register(self): """从首页-注册页 :return:""" <|body_0|> def test_login_register(self): """从首页-登录页-注册页 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestRegister: def test_register(self): """从首页-注册页 :return:""" main = MainPage() main.goto_register().register() sleep(3) def test_login_register(self): """从首页-登录页-注册页 :return:""" main = MainPage() main.goto_login().goto_register().register() ...
the_stack_v2_python_sparse
test_ProjectPractice/test_selenium/testcase/test_register.py
Veraun/HogwartsSDET17-1
train
0
420ff28a65c5b7c760df03e57724a4d6e949cfc2
[ "super(FeatureExtractor, self).__init__(model_path, profiling_file=profiling_file, decode=False)\nassert output_feature in self._outputs_map, 'invalid output_name %s, not in model signature' % output_feature\nself._outputs = [output_feature]", "output_list = super(FeatureExtractor, self).predict(images, self._out...
<|body_start_0|> super(FeatureExtractor, self).__init__(model_path, profiling_file=profiling_file, decode=False) assert output_feature in self._outputs_map, 'invalid output_name %s, not in model signature' % output_feature self._outputs = [output_feature] <|end_body_0|> <|body_start_1|> ...
FeatureExtractor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureExtractor: def __init__(self, model_path, output_feature, profiling_file=None): """Args: model_path: saved model path or frozenpb path output_feature: output node name""" <|body_0|> def predict(self, images, batch_size=1): """Args: images: a list of numpy uint...
stack_v2_sparse_classes_36k_train_010198
18,831
permissive
[ { "docstring": "Args: model_path: saved model path or frozenpb path output_feature: output node name", "name": "__init__", "signature": "def __init__(self, model_path, output_feature, profiling_file=None)" }, { "docstring": "Args: images: a list of numpy uint8 array batch_size: batch_size used t...
2
stack_v2_sparse_classes_30k_train_019406
Implement the Python class `FeatureExtractor` described below. Class description: Implement the FeatureExtractor class. Method signatures and docstrings: - def __init__(self, model_path, output_feature, profiling_file=None): Args: model_path: saved model path or frozenpb path output_feature: output node name - def pr...
Implement the Python class `FeatureExtractor` described below. Class description: Implement the FeatureExtractor class. Method signatures and docstrings: - def __init__(self, model_path, output_feature, profiling_file=None): Args: model_path: saved model path or frozenpb path output_feature: output node name - def pr...
d6912e2da3061935bf82bd429bc7a16a7a06e3a3
<|skeleton|> class FeatureExtractor: def __init__(self, model_path, output_feature, profiling_file=None): """Args: model_path: saved model path or frozenpb path output_feature: output node name""" <|body_0|> def predict(self, images, batch_size=1): """Args: images: a list of numpy uint...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatureExtractor: def __init__(self, model_path, output_feature, profiling_file=None): """Args: model_path: saved model path or frozenpb path output_feature: output node name""" super(FeatureExtractor, self).__init__(model_path, profiling_file=profiling_file, decode=False) assert outpu...
the_stack_v2_python_sparse
scripts/fashion_bert/image_feature_extract.py
alibaba/EasyTransfer
train
900
9634dfb3d421affdce4416511aa6888e9f65533d
[ "super(SearchRequestHandler, self).__init__(application, request, **kwargs)\nself.status = None\nself.timestamp = None\nself.issues = []\nself.total = 0", "def _decode_request():\n \"\"\"Decodes request.\n\n \"\"\"\n if self.get_argument(_PARAM_STATUS) != '*':\n self.status = self.get_argu...
<|body_start_0|> super(SearchRequestHandler, self).__init__(application, request, **kwargs) self.status = None self.timestamp = None self.issues = [] self.total = 0 <|end_body_0|> <|body_start_1|> def _decode_request(): """Decodes request. ...
Search issue request handler.
SearchRequestHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchRequestHandler: """Search issue request handler.""" def __init__(self, application, request, **kwargs): """Instance constructor.""" <|body_0|> def get(self): """HTTP GET handler.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(Search...
stack_v2_sparse_classes_36k_train_010199
1,876
no_license
[ { "docstring": "Instance constructor.", "name": "__init__", "signature": "def __init__(self, application, request, **kwargs)" }, { "docstring": "HTTP GET handler.", "name": "get", "signature": "def get(self)" } ]
2
stack_v2_sparse_classes_30k_test_000483
Implement the Python class `SearchRequestHandler` described below. Class description: Search issue request handler. Method signatures and docstrings: - def __init__(self, application, request, **kwargs): Instance constructor. - def get(self): HTTP GET handler.
Implement the Python class `SearchRequestHandler` described below. Class description: Search issue request handler. Method signatures and docstrings: - def __init__(self, application, request, **kwargs): Instance constructor. - def get(self): HTTP GET handler. <|skeleton|> class SearchRequestHandler: """Search i...
3058848dcb263aa1214166252e528850e73cb006
<|skeleton|> class SearchRequestHandler: """Search issue request handler.""" def __init__(self, application, request, **kwargs): """Instance constructor.""" <|body_0|> def get(self): """HTTP GET handler.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SearchRequestHandler: """Search issue request handler.""" def __init__(self, application, request, **kwargs): """Instance constructor.""" super(SearchRequestHandler, self).__init__(application, request, **kwargs) self.status = None self.timestamp = None self.issues...
the_stack_v2_python_sparse
ws/errata/handlers/search.py
AtefBN/esdoc-errata
train
0