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
b3b4446140f490e733ab9273e5bb7bb8974feb54
[ "n = len(nums)\nif n < 2:\n return False\ntotal = sum(nums)\nif total % 2 == 1:\n return False\nm = total / 2\nmaxNumber = max(nums)\nif maxNumber > m and maxNumber + m > total:\n return False\ndp = [[0] * (m + 1) for _ in range(n)]\nif nums[0] <= m:\n dp[0][nums[0]] = 1\nfor i in range(1, n):\n for ...
<|body_start_0|> n = len(nums) if n < 2: return False total = sum(nums) if total % 2 == 1: return False m = total / 2 maxNumber = max(nums) if maxNumber > m and maxNumber + m > total: return False dp = [[0] * (m + 1) for...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_031400
3,218
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition", "signature": "def canPartition(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition", "signature": "def canPartition(self, nums)" }, { "docstring": ":type nums: List...
3
stack_v2_sparse_classes_30k_train_008336
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: Li...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" n = len(nums) if n < 2: return False total = sum(nums) if total % 2 == 1: return False m = total / 2 maxNumber = max(nums) if maxNumber > m a...
the_stack_v2_python_sparse
0416_Partition_Equal_Subset_Sum.py
bingli8802/leetcode
train
0
31924789b918677b7ba7cef968a892ad6d3d28d7
[ "assert len(raw_shape) == 3\nself.batch_size = batch_size\nself.num_threads = num_threads\nself.min_after_dequeue = min_after_dequeue\nself.raw_shape = raw_shape\nif target_height is None:\n self.target_height = raw_shape[0]\nelse:\n self.target_height = target_height\nif target_width is None:\n self.targe...
<|body_start_0|> assert len(raw_shape) == 3 self.batch_size = batch_size self.num_threads = num_threads self.min_after_dequeue = min_after_dequeue self.raw_shape = raw_shape if target_height is None: self.target_height = raw_shape[0] else: ...
DataReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataReader: def __init__(self, batch_size, num_threads, min_after_dequeue, raw_shape, target_height=None, target_width=None, label_offset=0): """Args: batch_size: number of samples per batch num_threads: number of reading threads min_after_dequeue: minimum samples after dequeuing raw_sha...
stack_v2_sparse_classes_36k_train_031401
3,281
permissive
[ { "docstring": "Args: batch_size: number of samples per batch num_threads: number of reading threads min_after_dequeue: minimum samples after dequeuing raw_shape: raw image shape target_height: new image height after resizing, None mean no resizing target_width: new image width after resizing, None mean no resi...
3
stack_v2_sparse_classes_30k_train_009228
Implement the Python class `DataReader` described below. Class description: Implement the DataReader class. Method signatures and docstrings: - def __init__(self, batch_size, num_threads, min_after_dequeue, raw_shape, target_height=None, target_width=None, label_offset=0): Args: batch_size: number of samples per batc...
Implement the Python class `DataReader` described below. Class description: Implement the DataReader class. Method signatures and docstrings: - def __init__(self, batch_size, num_threads, min_after_dequeue, raw_shape, target_height=None, target_width=None, label_offset=0): Args: batch_size: number of samples per batc...
f977ca1cda972983cac7e33b324f07f2e1463a19
<|skeleton|> class DataReader: def __init__(self, batch_size, num_threads, min_after_dequeue, raw_shape, target_height=None, target_width=None, label_offset=0): """Args: batch_size: number of samples per batch num_threads: number of reading threads min_after_dequeue: minimum samples after dequeuing raw_sha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataReader: def __init__(self, batch_size, num_threads, min_after_dequeue, raw_shape, target_height=None, target_width=None, label_offset=0): """Args: batch_size: number of samples per batch num_threads: number of reading threads min_after_dequeue: minimum samples after dequeuing raw_shape: raw image ...
the_stack_v2_python_sparse
src/data_utils/data_reader.py
knmac/LCDC_release
train
25
9846cefd3d202e9b1555d5a69f33d57d4e9552be
[ "super().__init__()\nself.t = []\nself.q = []\nself.dq = []\nself.ddq = []\nself.stress = []\nself.strain = []", "self.t.append(t)\nself.q.append(q)\nself.dq.append(dq)\nself.ddq.append(ddq)\nself.stress.append(stress)\nself.strain.append(strain)" ]
<|body_start_0|> super().__init__() self.t = [] self.q = [] self.dq = [] self.ddq = [] self.stress = [] self.strain = [] <|end_body_0|> <|body_start_1|> self.t.append(t) self.q.append(q) self.dq.append(dq) self.ddq.append(ddq) ...
Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timestep dq: list list of ndarrays containing the first time derivative of the soluti...
AmfeSolution
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AmfeSolution: """Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timestep dq: list list of ndarrays containing...
stack_v2_sparse_classes_36k_train_031402
16,882
permissive
[ { "docstring": "Constructor of AmfeSolution", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function is called to write a timestep into the solution container Parameters ---------- t : float time q : numpy.array solution vector at time t dq : numpy.array (optional...
2
stack_v2_sparse_classes_30k_val_000921
Implement the Python class `AmfeSolution` described below. Class description: Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timest...
Implement the Python class `AmfeSolution` described below. Class description: Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timest...
61658db4f00858da4b4c6ba295ce66fd3ca9d324
<|skeleton|> class AmfeSolution: """Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timestep dq: list list of ndarrays containing...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AmfeSolution: """Simple Container for solutions of AMfe simulations It is based on lists of numpy.arrays Attributes ---------- t : list list of timesteps the solution has been computed q : list list of ndarrays containing the solution vectors for each timestep dq: list list of ndarrays containing the first ti...
the_stack_v2_python_sparse
src/amfe/solver/solution.py
c-meyer/AMfe
train
0
28d655366485d6e2d1d8f692c60424739e41b81e
[ "ctx.__dict__.update(ctx_dict)\nctx.kwargs = kwargs\nctx.param_shape = alpha.shape\ncandidates = ctx.candidates\ns_path_f = ctx.s_path_f\nwith torch.enable_grad():\n if len(s_path_f) == 1:\n m_out = candidates[s_path_f[0]](*args, **kwargs)\n else:\n m_out = sum((candidates[i](*args, **kwargs) fo...
<|body_start_0|> ctx.__dict__.update(ctx_dict) ctx.kwargs = kwargs ctx.param_shape = alpha.shape candidates = ctx.candidates s_path_f = ctx.s_path_f with torch.enable_grad(): if len(s_path_f) == 1: m_out = candidates[s_path_f[0]](*args, **kwarg...
BinaryGate gradient approximation function.
BinaryGateFunction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryGateFunction: """BinaryGate gradient approximation function.""" def forward(ctx, kwargs, alpha, ctx_dict, *args): """Return forward outputs.""" <|body_0|> def backward(ctx, m_grad): """Return backward outputs.""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_031403
12,569
permissive
[ { "docstring": "Return forward outputs.", "name": "forward", "signature": "def forward(ctx, kwargs, alpha, ctx_dict, *args)" }, { "docstring": "Return backward outputs.", "name": "backward", "signature": "def backward(ctx, m_grad)" } ]
2
stack_v2_sparse_classes_30k_train_006592
Implement the Python class `BinaryGateFunction` described below. Class description: BinaryGate gradient approximation function. Method signatures and docstrings: - def forward(ctx, kwargs, alpha, ctx_dict, *args): Return forward outputs. - def backward(ctx, m_grad): Return backward outputs.
Implement the Python class `BinaryGateFunction` described below. Class description: BinaryGate gradient approximation function. Method signatures and docstrings: - def forward(ctx, kwargs, alpha, ctx_dict, *args): Return forward outputs. - def backward(ctx, m_grad): Return backward outputs. <|skeleton|> class Binary...
52b53582fe7df95d7aacc8425013fd18645d079f
<|skeleton|> class BinaryGateFunction: """BinaryGate gradient approximation function.""" def forward(ctx, kwargs, alpha, ctx_dict, *args): """Return forward outputs.""" <|body_0|> def backward(ctx, m_grad): """Return backward outputs.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryGateFunction: """BinaryGate gradient approximation function.""" def forward(ctx, kwargs, alpha, ctx_dict, *args): """Return forward outputs.""" ctx.__dict__.update(ctx_dict) ctx.kwargs = kwargs ctx.param_shape = alpha.shape candidates = ctx.candidates ...
the_stack_v2_python_sparse
vega/networks/pytorch/customs/modnas/arch_space/mixed_ops.py
yiziqi/vega
train
0
2b359d6db42ad1456a284127373bd437ce5f25cb
[ "with self._lock:\n if not self._done:\n self._Print('.')\nreturn self._done", "if self._spinner_only or not self._output_enabled:\n return\ndisplay_message = self._GetPrefix()\nself._stream.write(message or display_message + '\\n')\nreturn" ]
<|body_start_0|> with self._lock: if not self._done: self._Print('.') return self._done <|end_body_0|> <|body_start_1|> if self._spinner_only or not self._output_enabled: return display_message = self._GetPrefix() self._stream.write(messag...
A context manager for telling the user about long-running progress.
_NonInteractiveProgressTracker
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _NonInteractiveProgressTracker: """A context manager for telling the user about long-running progress.""" def Tick(self): """Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether ...
stack_v2_sparse_classes_36k_train_031404
47,411
permissive
[ { "docstring": "Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether progress has completed.", "name": "Tick", "signature": "def Tick(self)" }, { "docstring": "Reprints the prefix followed b...
2
stack_v2_sparse_classes_30k_train_020991
Implement the Python class `_NonInteractiveProgressTracker` described below. Class description: A context manager for telling the user about long-running progress. Method signatures and docstrings: - def Tick(self): Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. N...
Implement the Python class `_NonInteractiveProgressTracker` described below. Class description: A context manager for telling the user about long-running progress. Method signatures and docstrings: - def Tick(self): Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. N...
85bb264e273568b5a0408f733b403c56373e2508
<|skeleton|> class _NonInteractiveProgressTracker: """A context manager for telling the user about long-running progress.""" def Tick(self): """Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _NonInteractiveProgressTracker: """A context manager for telling the user about long-running progress.""" def Tick(self): """Give a visual indication to the user that some progress has been made. Output is sent to sys.stderr. Nothing is shown if output is not a TTY. Returns: Whether progress has ...
the_stack_v2_python_sparse
google-cloud-sdk/lib/googlecloudsdk/core/console/progress_tracker.py
bopopescu/socialliteapp
train
0
0d5c616df16683eb0cf1c6cdfd1569980a81ae8f
[ "try:\n return self._list(self._PROJECTS_URL, 'projects', obj_class=Project)\nexcept exceptions.EndpointNotFound:\n endpoint_filter = {'interface': plugin.AUTH_INTERFACE}\n return self._list(self._PROJECTS_URL, 'projects', obj_class=Project, endpoint_filter=endpoint_filter)", "try:\n return self._list...
<|body_start_0|> try: return self._list(self._PROJECTS_URL, 'projects', obj_class=Project) except exceptions.EndpointNotFound: endpoint_filter = {'interface': plugin.AUTH_INTERFACE} return self._list(self._PROJECTS_URL, 'projects', obj_class=Project, endpoint_filter=e...
Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.
AuthManager
[ "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthManager: """Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.""" def projects(self): """List projects that the specified token can be rescoped to. :returns: a list ...
stack_v2_sparse_classes_36k_train_031405
3,252
permissive
[ { "docstring": "List projects that the specified token can be rescoped to. :returns: a list of projects. :rtype: list of :class:`keystoneclient.v3.projects.Project`", "name": "projects", "signature": "def projects(self)" }, { "docstring": "List Domains that the specified token can be rescoped to...
3
stack_v2_sparse_classes_30k_train_000370
Implement the Python class `AuthManager` described below. Class description: Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user. Method signatures and docstrings: - def projects(self): List projects that ...
Implement the Python class `AuthManager` described below. Class description: Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user. Method signatures and docstrings: - def projects(self): List projects that ...
141787ae8b0db7ac4dffce915e033a78d145d54e
<|skeleton|> class AuthManager: """Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.""" def projects(self): """List projects that the specified token can be rescoped to. :returns: a list ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthManager: """Retrieve auth context specific information. The information returned by the auth routes is entirely dependent on the authentication information provided by the user.""" def projects(self): """List projects that the specified token can be rescoped to. :returns: a list of projects. ...
the_stack_v2_python_sparse
keystoneclient/v3/auth.py
openstack/python-keystoneclient
train
118
312f87f2fde251181b6f6e7c0f3fb42655c6f018
[ "def backtrack(i, tmp_num, tmp):\n if tmp_num == target:\n tmp = sorted(tmp)\n if tmp not in res:\n res.append(tmp)\n return\n return\n if i == n or tmp_num > target:\n return\n backtrack(i + 1, tmp_num + candidates[i], tmp + [candidates[i]])\n backtrack...
<|body_start_0|> def backtrack(i, tmp_num, tmp): if tmp_num == target: tmp = sorted(tmp) if tmp not in res: res.append(tmp) return return if i == n or tmp_num > target: return ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combinationSum21(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum2(self, candidates, target): """:param candidates: :param target: :return:""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_031406
1,580
no_license
[ { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum21", "signature": "def combinationSum21(self, candidates, target)" }, { "docstring": ":param candidates: :param target: :return:", "name": "combinationSum2", "signature": "def c...
2
stack_v2_sparse_classes_30k_train_006957
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum21(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum2(self, candidates, target): :param cand...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum21(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum2(self, candidates, target): :param cand...
a91a758ab52d8615366a46b168181c04a92a793b
<|skeleton|> class Solution: def combinationSum21(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum2(self, candidates, target): """:param candidates: :param target: :return:""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def combinationSum21(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" def backtrack(i, tmp_num, tmp): if tmp_num == target: tmp = sorted(tmp) if tmp not in res: res.a...
the_stack_v2_python_sparse
算法/40. 组合总和 II.py
Confucius-hui/LeetCode
train
0
62316a86190dd5c044b15576f410aeab4c6db677
[ "super().on_episode_step(worker=worker, base_env=base_env, policies=policies, episode=episode, env_index=env_index, **kwargs)\nif isinstance(episode, Episode):\n info = episode.last_info_for()\nelse:\n info = episode._last_infos.get(_DUMMY_AGENT_ID)\nif info is not None:\n for key, value in info.items():\n...
<|body_start_0|> super().on_episode_step(worker=worker, base_env=base_env, policies=policies, episode=episode, env_index=env_index, **kwargs) if isinstance(episode, Episode): info = episode.last_info_for() else: info = episode._last_infos.get(_DUMMY_AGENT_ID) if i...
TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example.
MonitorInfoCallback
[ "MIT", "BSL-1.0", "MPL-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MonitorInfoCallback: """TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example.""" def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyID, Policy]]=None, episode: Union[Episode, EpisodeV2], env_index: Opt...
stack_v2_sparse_classes_36k_train_031407
3,161
permissive
[ { "docstring": "TODO: Write documentation.", "name": "on_episode_step", "signature": "def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyID, Policy]]=None, episode: Union[Episode, EpisodeV2], env_index: Optional[int]=None, **kwargs: Any) -> None" }, ...
2
stack_v2_sparse_classes_30k_train_020889
Implement the Python class `MonitorInfoCallback` described below. Class description: TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example. Method signatures and docstrings: - def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyI...
Implement the Python class `MonitorInfoCallback` described below. Class description: TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example. Method signatures and docstrings: - def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyI...
a3b244f0bcb21abe605544d1f5c4a31419946efd
<|skeleton|> class MonitorInfoCallback: """TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example.""" def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyID, Policy]]=None, episode: Union[Episode, EpisodeV2], env_index: Opt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MonitorInfoCallback: """TODO: Write documentation. Base on `rllib/examples/custom_metrics_and_callbacks.py` example.""" def on_episode_step(self, *, worker: 'RolloutWorker', base_env: BaseEnv, policies: Optional[Dict[PolicyID, Policy]]=None, episode: Union[Episode, EpisodeV2], env_index: Optional[int]=No...
the_stack_v2_python_sparse
python/gym_jiminy/rllib/gym_jiminy/rllib/callbacks.py
duburcqa/jiminy
train
108
2e7a342fcb90a9e5e051a080660506da27f62019
[ "self.logger(logging.DEBUG, 'rsync.stat: path: {}'.format(path))\nret = {}\nchsum = None\npath = self.pfn2path(path)\ntry:\n cmd = \"rsync -an --size-only -e 'ssh -p {0}' --remove-source-files {1}{2}:{3}\".format(self.port, self.sshuser, self.hostname, path)\n self.logger(logging.DEBUG, 'rsync.stat: filesize...
<|body_start_0|> self.logger(logging.DEBUG, 'rsync.stat: path: {}'.format(path)) ret = {} chsum = None path = self.pfn2path(path) try: cmd = "rsync -an --size-only -e 'ssh -p {0}' --remove-source-files {1}{2}:{3}".format(self.port, self.sshuser, self.hostname, path) ...
Implementing access to RSEs using the ssh.Rsync implementation.
Rsync
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rsync: """Implementing access to RSEs using the ssh.Rsync implementation.""" def stat(self, path): """Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the library. :returns: a dict with two keys, filesize and an eleme...
stack_v2_sparse_classes_36k_train_031408
17,487
permissive
[ { "docstring": "Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the library. :returns: a dict with two keys, filesize and an element of GLOBALLY_SUPPORTED_CHECKSUMS.", "name": "stat", "signature": "def stat(self, path)" }, { "do...
4
null
Implement the Python class `Rsync` described below. Class description: Implementing access to RSEs using the ssh.Rsync implementation. Method signatures and docstrings: - def stat(self, path): Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the libra...
Implement the Python class `Rsync` described below. Class description: Implementing access to RSEs using the ssh.Rsync implementation. Method signatures and docstrings: - def stat(self, path): Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the libra...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class Rsync: """Implementing access to RSEs using the ssh.Rsync implementation.""" def stat(self, path): """Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the library. :returns: a dict with two keys, filesize and an eleme...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rsync: """Implementing access to RSEs using the ssh.Rsync implementation.""" def stat(self, path): """Returns the stats of a file. :param path: path to file :raises ServiceUnavailable: if some generic error occured in the library. :returns: a dict with two keys, filesize and an element of GLOBALL...
the_stack_v2_python_sparse
lib/rucio/rse/protocols/ssh.py
rucio/rucio
train
232
a336ef000ab596e522c1b2ebb922b1fc3207b773
[ "super().__init__(source_image_path, source_image_size, output_image_path, output_image_size)\nself.__levels = len(neighbourhood_padding)\nself.__neighbourhood_padding = neighbourhood_padding\nself.__tsvq_branching_factor = tsvq_branching_factor\nassert self.__levels > 0, 'At least one neighbourhood padding size mu...
<|body_start_0|> super().__init__(source_image_path, source_image_size, output_image_path, output_image_size) self.__levels = len(neighbourhood_padding) self.__neighbourhood_padding = neighbourhood_padding self.__tsvq_branching_factor = tsvq_branching_factor assert self.__levels ...
A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve the pixels one-by-one in scanline order by finding the best ne...
RasterPixelNeighbourhoodSynthesizer
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RasterPixelNeighbourhoodSynthesizer: """A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve...
stack_v2_sparse_classes_36k_train_031409
6,847
permissive
[ { "docstring": "Constructs a new RasterPixelNeighbourhoodSynthesizer object with the given TextureSynthesizer parameters and neighbourhood padding. Args: source_image_path: See TextureSynthesizer.__init__(). source_image_size: See TextureSynthesizer.__init__(). output_image_path: See TextureSynthesizer.__init__...
5
stack_v2_sparse_classes_30k_train_018363
Implement the Python class `RasterPixelNeighbourhoodSynthesizer` described below. Class description: A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise...
Implement the Python class `RasterPixelNeighbourhoodSynthesizer` described below. Class description: A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise...
7e7282698befd53383cbd6566039340babb0a289
<|skeleton|> class RasterPixelNeighbourhoodSynthesizer: """A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RasterPixelNeighbourhoodSynthesizer: """A RasterPixelNeighbourhoodSynthesizer object synthesizes textures using the algorithm from https://graphics.stanford.edu/papers/texture-synthesis-sig00/texture.pdf. The basic idea is to seed the output Image with noise from the source Image and then resolve the pixels o...
the_stack_v2_python_sparse
sandbox/synthesizers/raster_pixel_neighbourhood_synthesizer.py
Mandrenkov/SVBRDF-Texture-Synthesis
train
3
f1477ea164b86833503dea253bee3313020ad4a9
[ "res = 0\ncount = 0\nfor ch in s:\n if ch == 'R':\n count += 1\n else:\n count -= 1\n if count == 0:\n res += 1\nreturn res", "if not s:\n return 0\nres = 0\nstackL = stackR = []\nnumL = numR = 0\nfor ch in s:\n if numL and numR and (numL == numR):\n res += 1\n st...
<|body_start_0|> res = 0 count = 0 for ch in s: if ch == 'R': count += 1 else: count -= 1 if count == 0: res += 1 return res <|end_body_0|> <|body_start_1|> if not s: return 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def balancedStringSplit(self, s): """:type s: str :rtype: int""" <|body_0|> def balancedStringSplit2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = 0 count = 0 for ch in s: ...
stack_v2_sparse_classes_36k_train_031410
1,699
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "balancedStringSplit", "signature": "def balancedStringSplit(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "balancedStringSplit2", "signature": "def balancedStringSplit2(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_011457
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def balancedStringSplit(self, s): :type s: str :rtype: int - def balancedStringSplit2(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def balancedStringSplit(self, s): :type s: str :rtype: int - def balancedStringSplit2(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def balancedStringSpli...
690b685048c8e89d26047b6bc48b5f9af7d59cbb
<|skeleton|> class Solution: def balancedStringSplit(self, s): """:type s: str :rtype: int""" <|body_0|> def balancedStringSplit2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def balancedStringSplit(self, s): """:type s: str :rtype: int""" res = 0 count = 0 for ch in s: if ch == 'R': count += 1 else: count -= 1 if count == 0: res += 1 return res ...
the_stack_v2_python_sparse
贪心/1221. 分割平衡字符串.py
SimmonsChen/LeetCode
train
0
47b9e80cb6cef92825df538168afaa1559370789
[ "super(GaussianConvShiftAttention, self).__init__()\nself.center = center\nself.r = r\nself.beta = beta", "conv = kwargs['__layer']\nif not isinstance(conv, nn.Conv2d):\n raise NotImplementedError('GaussianConvShiftAttention only' + ' implemented for wapping torch 2d convolutions. Was asked' + ' to wrap {}'.fo...
<|body_start_0|> super(GaussianConvShiftAttention, self).__init__() self.center = center self.r = r self.beta = beta <|end_body_0|> <|body_start_1|> conv = kwargs['__layer'] if not isinstance(conv, nn.Conv2d): raise NotImplementedError('GaussianConvShiftAtten...
GaussianConvShiftAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianConvShiftAttention: def __init__(self, center, r, beta): """### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row_center, col_center) - `r` --- Approximate radius of influence of the gaussian field, a tuple of the form (row_r, c...
stack_v2_sparse_classes_36k_train_031411
13,939
no_license
[ { "docstring": "### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row_center, col_center) - `r` --- Approximate radius of influence of the gaussian field, a tuple of the form (row_r, col_r) - `beta` --- Multiplicative strength factor", "name": "__init__", ...
3
stack_v2_sparse_classes_30k_train_010937
Implement the Python class `GaussianConvShiftAttention` described below. Class description: Implement the GaussianConvShiftAttention class. Method signatures and docstrings: - def __init__(self, center, r, beta): ### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row...
Implement the Python class `GaussianConvShiftAttention` described below. Class description: Implement the GaussianConvShiftAttention class. Method signatures and docstrings: - def __init__(self, center, r, beta): ### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row...
2f1c8dda61d3641da30c1e21a5ec4abdb26c03ad
<|skeleton|> class GaussianConvShiftAttention: def __init__(self, center, r, beta): """### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row_center, col_center) - `r` --- Approximate radius of influence of the gaussian field, a tuple of the form (row_r, c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GaussianConvShiftAttention: def __init__(self, center, r, beta): """### Arguments - `center` --- Center location of the gaussian field in the input, a tuple of the form (row_center, col_center) - `r` --- Approximate radius of influence of the gaussian field, a tuple of the form (row_r, col_r) - `beta`...
the_stack_v2_python_sparse
code/proc/attention_models.py
dbirman/attfield2
train
0
31c7d54cb2ebf974366c31050cedde8cf2113d27
[ "super(SoftExponential, self).__init__()\nif alpha is None:\n self.alpha = nn.Parameter(torch.tensor(0.0))\nelse:\n self.alpha = nn.Parameter(torch.tensor(alpha))\nself.alpha.requiresGrad = True", "if self.alpha == 0.0:\n return x\nif self.alpha < 0.0:\n return -torch.log(1 - self.alpha * (x + self.al...
<|body_start_0|> super(SoftExponential, self).__init__() if alpha is None: self.alpha = nn.Parameter(torch.tensor(0.0)) else: self.alpha = nn.Parameter(torch.tensor(alpha)) self.alpha.requiresGrad = True <|end_body_0|> <|body_start_1|> if self.alpha == 0....
SoftExponential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SoftExponential: def __init__(self, alpha=None): """Init method.""" <|body_0|> def forward(self, x): """Forward pass of the function""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(SoftExponential, self).__init__() if alpha is None: ...
stack_v2_sparse_classes_36k_train_031412
32,265
no_license
[ { "docstring": "Init method.", "name": "__init__", "signature": "def __init__(self, alpha=None)" }, { "docstring": "Forward pass of the function", "name": "forward", "signature": "def forward(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_001490
Implement the Python class `SoftExponential` described below. Class description: Implement the SoftExponential class. Method signatures and docstrings: - def __init__(self, alpha=None): Init method. - def forward(self, x): Forward pass of the function
Implement the Python class `SoftExponential` described below. Class description: Implement the SoftExponential class. Method signatures and docstrings: - def __init__(self, alpha=None): Init method. - def forward(self, x): Forward pass of the function <|skeleton|> class SoftExponential: def __init__(self, alpha...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class SoftExponential: def __init__(self, alpha=None): """Init method.""" <|body_0|> def forward(self, x): """Forward pass of the function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SoftExponential: def __init__(self, alpha=None): """Init method.""" super(SoftExponential, self).__init__() if alpha is None: self.alpha = nn.Parameter(torch.tensor(0.0)) else: self.alpha = nn.Parameter(torch.tensor(alpha)) self.alpha.requiresGra...
the_stack_v2_python_sparse
generated/test_digantamisra98_Echo.py
jansel/pytorch-jit-paritybench
train
35
bffd5dd0e85b9ac62352514b792cb874190ce438
[ "try:\n import onnxruntime\n import skl2onnx\n return True\nexcept ImportError:\n return False", "if input_types is None or not isinstance(input_types[0], tuple):\n raise RuntimeError('input_types argument should contain at least one tuple, e.g. [((1, 14), np.float32)]')\nif isinstance(model, RFOnn...
<|body_start_0|> try: import onnxruntime import skl2onnx return True except ImportError: return False <|end_body_0|> <|body_start_1|> if input_types is None or not isinstance(input_types[0], tuple): raise RuntimeError('input_types argu...
RFOnnxCompiler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" <|body_0|> def compile(model, path: str, input_types=None): """Compile the trained model for faster inference. Parameters ---------- model The native model that is expect...
stack_v2_sparse_classes_36k_train_031413
4,283
permissive
[ { "docstring": "Verify whether the required package has been installed.", "name": "can_compile", "signature": "def can_compile()" }, { "docstring": "Compile the trained model for faster inference. Parameters ---------- model The native model that is expected to be compiled. path : str The path f...
4
null
Implement the Python class `RFOnnxCompiler` described below. Class description: Implement the RFOnnxCompiler class. Method signatures and docstrings: - def can_compile(): Verify whether the required package has been installed. - def compile(model, path: str, input_types=None): Compile the trained model for faster inf...
Implement the Python class `RFOnnxCompiler` described below. Class description: Implement the RFOnnxCompiler class. Method signatures and docstrings: - def can_compile(): Verify whether the required package has been installed. - def compile(model, path: str, input_types=None): Compile the trained model for faster inf...
6af92e149491f6e5062495d87306b3625d12d992
<|skeleton|> class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" <|body_0|> def compile(model, path: str, input_types=None): """Compile the trained model for faster inference. Parameters ---------- model The native model that is expect...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RFOnnxCompiler: def can_compile(): """Verify whether the required package has been installed.""" try: import onnxruntime import skl2onnx return True except ImportError: return False def compile(model, path: str, input_types=None): ...
the_stack_v2_python_sparse
tabular/src/autogluon/tabular/models/rf/compilers/onnx.py
stjordanis/autogluon
train
0
594e0ad88b5b0e6d15c52f330ecbf32b44909ee7
[ "if num_workers is None and ess_init_args is None or (num_workers is not None and ess_init_args is not None):\n raise ValueError('Exactly one of `num_workers` or `ess_init_args` has to be provided.')\nself.num_workers = num_workers or len(ess_init_args)\nif self.num_workers < 2:\n raise ValueError(f'{self.__c...
<|body_start_0|> if num_workers is None and ess_init_args is None or (num_workers is not None and ess_init_args is not None): raise ValueError('Exactly one of `num_workers` or `ess_init_args` has to be provided.') self.num_workers = num_workers or len(ess_init_args) if self.num_worke...
SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance of exchanging good parameters, and changing ESS hyperparameters to those of the mo...
SacessOptimizer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SacessOptimizer: """SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance of exchanging good parameters, and chan...
stack_v2_sparse_classes_36k_train_031414
23,958
permissive
[ { "docstring": "Construct. Parameters ---------- ess_init_args: List of argument dictionaries passed to :func:`ESSOptimizer.__init__`. Each entry corresponds to one worker process. I.e., the length of this list is the number of ESSs. Ideally, this list contains some more conservative and some more aggressive co...
3
stack_v2_sparse_classes_30k_train_013586
Implement the Python class `SacessOptimizer` described below. Class description: SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance ...
Implement the Python class `SacessOptimizer` described below. Class description: SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance ...
9a754573a7b77d30d5dc1f67a8dc1be6c29f1640
<|skeleton|> class SacessOptimizer: """SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance of exchanging good parameters, and chan...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SacessOptimizer: """SACESS optimizer. A shared-memory-based implementation of the SaCeSS algorithm presented in [PenasGon2017]_. Multiple processes (`workers`) run consecutive ESSs in parallel. After each ESS run, depending on the outcome, there is a chance of exchanging good parameters, and changing ESS hype...
the_stack_v2_python_sparse
pypesto/optimize/ess/sacess.py
ICB-DCM/pyPESTO
train
174
6cc913c2036a6ad009bdbbca42785a749a1696f4
[ "import psycopg\ncstring = f'dbname={dbname} user={dbuser}'\nif dbpass:\n cstring += f' password={dbpass}'\nwith psycopg.connect(cstring) as conn:\n with conn.cursor() as cur:\n cur.execute(open(script, 'r').read())", "print('CFG', cfg)\nif os.path.splitext(file)[1] not in ('.sql', '.py'):\n raise...
<|body_start_0|> import psycopg cstring = f'dbname={dbname} user={dbuser}' if dbpass: cstring += f' password={dbpass}' with psycopg.connect(cstring) as conn: with conn.cursor() as cur: cur.execute(open(script, 'r').read()) <|end_body_0|> <|body_st...
pgSQLScript
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class pgSQLScript: def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None): """Indent authentication does not use a password.""" <|body_0|> def execute(file: str, cfg: dict): """Executes .sql or .py file.""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_031415
7,254
permissive
[ { "docstring": "Indent authentication does not use a password.", "name": "_exec_sql", "signature": "def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None)" }, { "docstring": "Executes .sql or .py file.", "name": "execute", "signature": "def execute(file: str, cfg: dict)" ...
2
stack_v2_sparse_classes_30k_train_020162
Implement the Python class `pgSQLScript` described below. Class description: Implement the pgSQLScript class. Method signatures and docstrings: - def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None): Indent authentication does not use a password. - def execute(file: str, cfg: dict): Executes .sql or...
Implement the Python class `pgSQLScript` described below. Class description: Implement the pgSQLScript class. Method signatures and docstrings: - def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None): Indent authentication does not use a password. - def execute(file: str, cfg: dict): Executes .sql or...
fc6f23c843160dcc2549762580fb31d6388cd042
<|skeleton|> class pgSQLScript: def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None): """Indent authentication does not use a password.""" <|body_0|> def execute(file: str, cfg: dict): """Executes .sql or .py file.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class pgSQLScript: def _exec_sql(script: str, dbname: str, dbuser: str, dbpass: str=None): """Indent authentication does not use a password.""" import psycopg cstring = f'dbname={dbname} user={dbuser}' if dbpass: cstring += f' password={dbpass}' with psycopg.conne...
the_stack_v2_python_sparse
test.py
Jasata/utu-schooner
train
0
6f6197f70875f1c6dea4c151e608c9c01c1965a5
[ "config_dict = self.config_dict\nif len(config_dict['c']) > 1:\n config_dict['c'] = config_dict['c'][0]\ntry:\n plt.scatter(y=grid[:, 0], x=grid[:, 1], **config_dict)\nexcept (IndexError, TypeError):\n return self.scatter_grid_list(grid_list=grid)", "if len(grid_list) == 0:\n return\ncolor = itertools...
<|body_start_0|> config_dict = self.config_dict if len(config_dict['c']) > 1: config_dict['c'] = config_dict['c'][0] try: plt.scatter(y=grid[:, 0], x=grid[:, 1], **config_dict) except (IndexError, TypeError): return self.scatter_grid_list(grid_list=gri...
Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatter: https://matplotlib.org/3.1.1/api/_a...
GridScatter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GridScatter: """Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatt...
stack_v2_sparse_classes_36k_train_031416
6,735
permissive
[ { "docstring": "Plot an input grid of (y,x) coordinates using the matplotlib method `plt.scatter`. Parameters ---------- grid : Grid2D The grid of (y,x) coordinates that is plotted. errors The error on every point of the grid that is plotted.", "name": "scatter_grid", "signature": "def scatter_grid(self...
4
null
Implement the Python class `GridScatter` described below. Class description: Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the fo...
Implement the Python class `GridScatter` described below. Class description: Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the fo...
6639dd86d21ea28e942155753ec556752735b4e4
<|skeleton|> class GridScatter: """Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatt...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GridScatter: """Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatter: https://m...
the_stack_v2_python_sparse
autoarray/plot/wrap/two_d/grid_scatter.py
Jammy2211/PyAutoArray
train
6
3526a519f2d906d116fbecdd4930a0d76e93586f
[ "errors = []\nfor c in range(-5, 16):\n classifier = LinearSVC(C=2.0 ** c)\n errs = 1 - cross_val_score(classifier, traindata, trainlabels, cv=10)\n err = np.sum(errs) / 10\n errors.append(err)\nidx_min = np.argmin(errors)\nC_min = 2.0 ** (idx_min - 5.0)\nmin_err = errors[idx_min]\nreturn (C_min, min_er...
<|body_start_0|> errors = [] for c in range(-5, 16): classifier = LinearSVC(C=2.0 ** c) errs = 1 - cross_val_score(classifier, traindata, trainlabels, cv=10) err = np.sum(errs) / 10 errors.append(err) idx_min = np.argmin(errors) C_min = 2.0...
Question3
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Question3: def LinearSVC_crossValidation(self, traindata, trainlabels): """Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerch by hand. Parameters: 1. traindata (Nt, d) numpy ndarray. The features in the training set. 2. tr...
stack_v2_sparse_classes_36k_train_031417
21,354
no_license
[ { "docstring": "Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerch by hand. Parameters: 1. traindata (Nt, d) numpy ndarray. The features in the training set. 2. trainlabels (Nt, ) numpy ndarray. The labels in the training set. Outputs: 1. C_min F...
4
null
Implement the Python class `Question3` described below. Class description: Implement the Question3 class. Method signatures and docstrings: - def LinearSVC_crossValidation(self, traindata, trainlabels): Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerc...
Implement the Python class `Question3` described below. Class description: Implement the Question3 class. Method signatures and docstrings: - def LinearSVC_crossValidation(self, traindata, trainlabels): Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerc...
adcb6b47164a909fe8b3cd3969c8bc3f3696893a
<|skeleton|> class Question3: def LinearSVC_crossValidation(self, traindata, trainlabels): """Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerch by hand. Parameters: 1. traindata (Nt, d) numpy ndarray. The features in the training set. 2. tr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Question3: def LinearSVC_crossValidation(self, traindata, trainlabels): """Use cross-validation to select a value of C for a linear SVM by varying C from 2^{-5},...,2^{15}. You should seaerch by hand. Parameters: 1. traindata (Nt, d) numpy ndarray. The features in the training set. 2. trainlabels (Nt,...
the_stack_v2_python_sparse
ECE365/ML/lab3/main.py
RickyL-2000/ZJUI-lib
train
1
7b9b802e055e68ea0051f191fbd2929a260be32d
[ "n = len(nums)\nans = []\nfor i in range(n):\n if nums[i] == target:\n ans.append(i)\n break\nfor i in range(n - 1, -1, -1):\n if nums[i] == target:\n ans.append(i)\n break\nif not ans:\n ans.extend([-1, -1])\nreturn ans", "size = len(nums)\nif size == 0:\n return [-1, -1]\...
<|body_start_0|> n = len(nums) ans = [] for i in range(n): if nums[i] == target: ans.append(i) break for i in range(n - 1, -1, -1): if nums[i] == target: ans.append(i) break if not ans: ...
OfficialSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OfficialSolution: def search_range(self, nums: List[int], target: int) -> List[int]: """线性扫描。""" <|body_0|> def search_range_2(self, nums: List[int], target: int) -> List[int]: """二分查找。""" <|body_1|> def __find_first_position(self, nums: List[int], size,...
stack_v2_sparse_classes_36k_train_031418
4,200
no_license
[ { "docstring": "线性扫描。", "name": "search_range", "signature": "def search_range(self, nums: List[int], target: int) -> List[int]" }, { "docstring": "二分查找。", "name": "search_range_2", "signature": "def search_range_2(self, nums: List[int], target: int) -> List[int]" }, { "docstring...
4
null
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def search_range(self, nums: List[int], target: int) -> List[int]: 线性扫描。 - def search_range_2(self, nums: List[int], target: int) -> List[int]: 二分查找。 - def __find...
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def search_range(self, nums: List[int], target: int) -> List[int]: 线性扫描。 - def search_range_2(self, nums: List[int], target: int) -> List[int]: 二分查找。 - def __find...
6932d69353b94ec824dd0ddc86a92453f6673232
<|skeleton|> class OfficialSolution: def search_range(self, nums: List[int], target: int) -> List[int]: """线性扫描。""" <|body_0|> def search_range_2(self, nums: List[int], target: int) -> List[int]: """二分查找。""" <|body_1|> def __find_first_position(self, nums: List[int], size,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OfficialSolution: def search_range(self, nums: List[int], target: int) -> List[int]: """线性扫描。""" n = len(nums) ans = [] for i in range(n): if nums[i] == target: ans.append(i) break for i in range(n - 1, -1, -1): if...
the_stack_v2_python_sparse
0034_find-first-and-last-position-of-element-in-sorted-array.py
Nigirimeshi/leetcode
train
0
87c7d0c06340205282988aa7ee56fb7ee3fa1fcf
[ "InstallableFunc = ROOT.InstallableFunc\nFuncLess = ROOT.FuncLess\nFuncLess.InstallableFunc = InstallableFunc\na = FuncLess(1234)\nself.assertEqual(a.m_int, a.InstallableFunc().m_int)", "FuncLess = ROOT.FuncLess\nFunctionNS = ROOT.FunctionNS\nFuncLess.InstallableFunc2 = FunctionNS.InstallableFunc\na = FuncLess(12...
<|body_start_0|> InstallableFunc = ROOT.InstallableFunc FuncLess = ROOT.FuncLess FuncLess.InstallableFunc = InstallableFunc a = FuncLess(1234) self.assertEqual(a.m_int, a.InstallableFunc().m_int) <|end_body_0|> <|body_start_1|> FuncLess = ROOT.FuncLess FunctionNS...
Func4GlobalCppFunctionAsMethodTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Func4GlobalCppFunctionAsMethodTestCase: def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self): """Test installing and calling global C++ function as python method""" <|body_0|> def test2InstallAndCallGlobalCppFunctionAsPythonMethod(self): """Test installing an...
stack_v2_sparse_classes_36k_train_031419
10,433
no_license
[ { "docstring": "Test installing and calling global C++ function as python method", "name": "test1InstallAndCallGlobalCppFunctionAsPythonMethod", "signature": "def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self)" }, { "docstring": "Test installing and calling namespaced C++ function as p...
2
null
Implement the Python class `Func4GlobalCppFunctionAsMethodTestCase` described below. Class description: Implement the Func4GlobalCppFunctionAsMethodTestCase class. Method signatures and docstrings: - def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self): Test installing and calling global C++ function as pytho...
Implement the Python class `Func4GlobalCppFunctionAsMethodTestCase` described below. Class description: Implement the Func4GlobalCppFunctionAsMethodTestCase class. Method signatures and docstrings: - def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self): Test installing and calling global C++ function as pytho...
134508460915282a5d82d6cbbb6e6afa14653413
<|skeleton|> class Func4GlobalCppFunctionAsMethodTestCase: def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self): """Test installing and calling global C++ function as python method""" <|body_0|> def test2InstallAndCallGlobalCppFunctionAsPythonMethod(self): """Test installing an...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Func4GlobalCppFunctionAsMethodTestCase: def test1InstallAndCallGlobalCppFunctionAsPythonMethod(self): """Test installing and calling global C++ function as python method""" InstallableFunc = ROOT.InstallableFunc FuncLess = ROOT.FuncLess FuncLess.InstallableFunc = InstallableFun...
the_stack_v2_python_sparse
python/function/PyROOT_functiontests.py
root-project/roottest
train
41
1194cbacff2ec16f28e22bd11a84bc3584d9c12d
[ "curframe = inspect.currentframe()\ncalframe = inspect.getouterframes(curframe, 2)\ncalname = calframe[1][3]\nif calname in ('strategy', 'simulate_match'):\n return 'D'\nbest_strategy = self.look_ahead(opponent)\nreturn best_strategy", "for match in range(rounds):\n play_1, play_2 = (strategy, opponent.stra...
<|body_start_0|> curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) calname = calframe[1][3] if calname in ('strategy', 'simulate_match'): return 'D' best_strategy = self.look_ahead(opponent) return best_strategy <|end_body_0|> <...
A player that looks ahead at what the opponent will do and decides what to do.
MindReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MindReader: """A player that looks ahead at what the opponent will do and decides what to do.""" def strategy(self, opponent): """Pretends to play the opponent 50 times before each match. The primary purpose is to look far enough ahead to see if a defect will be punished by the oppon...
stack_v2_sparse_classes_36k_train_031420
2,435
permissive
[ { "docstring": "Pretends to play the opponent 50 times before each match. The primary purpose is to look far enough ahead to see if a defect will be punished by the opponent. If the MindReader attempts to play itself (or another similar strategy), then it will cause a recursion loop, so this is also handeled in...
3
stack_v2_sparse_classes_30k_train_003864
Implement the Python class `MindReader` described below. Class description: A player that looks ahead at what the opponent will do and decides what to do. Method signatures and docstrings: - def strategy(self, opponent): Pretends to play the opponent 50 times before each match. The primary purpose is to look far enou...
Implement the Python class `MindReader` described below. Class description: A player that looks ahead at what the opponent will do and decides what to do. Method signatures and docstrings: - def strategy(self, opponent): Pretends to play the opponent 50 times before each match. The primary purpose is to look far enou...
e59fc40ebb705afe05cea6f30e282d1e9c621259
<|skeleton|> class MindReader: """A player that looks ahead at what the opponent will do and decides what to do.""" def strategy(self, opponent): """Pretends to play the opponent 50 times before each match. The primary purpose is to look far enough ahead to see if a defect will be punished by the oppon...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MindReader: """A player that looks ahead at what the opponent will do and decides what to do.""" def strategy(self, opponent): """Pretends to play the opponent 50 times before each match. The primary purpose is to look far enough ahead to see if a defect will be punished by the opponent. If the M...
the_stack_v2_python_sparse
axelrod/strategies/mindreader.py
DEFALT303/Axelrod
train
0
10d1527b44efd6afbdade683ae0079d72bfd081f
[ "if isinstance(looker, self.__class__):\n return 'The image of yourself stretches into infinity.'\nreturn f'{self.key} shows your reflection:\\n{looker.db.desc}'", "if not text:\n text = '<silence>'\ntext = text[0] if is_iter(text) else text\nif from_obj:\n for obj in make_iter(from_obj):\n obj.ms...
<|body_start_0|> if isinstance(looker, self.__class__): return 'The image of yourself stretches into infinity.' return f'{self.key} shows your reflection:\n{looker.db.desc}' <|end_body_0|> <|body_start_1|> if not text: text = '<silence>' text = text[0] if is_iter...
A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror.
TutorialMirror
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TutorialMirror: """A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror.""" def return_appearance(self, looker, **kwargs): """This form...
stack_v2_sparse_classes_36k_train_031421
2,235
permissive
[ { "docstring": "This formats the description of this object. Called by the 'look' command. Args: looker (Object): Object doing the looking. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default).", "name": "return_appearance", "signature": "def return_appearance...
2
null
Implement the Python class `TutorialMirror` described below. Class description: A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror. Method signatures and docstrings: -...
Implement the Python class `TutorialMirror` described below. Class description: A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror. Method signatures and docstrings: -...
b3ca58b5c1325a3bf57051dfe23560a08d2947b7
<|skeleton|> class TutorialMirror: """A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror.""" def return_appearance(self, looker, **kwargs): """This form...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TutorialMirror: """A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror.""" def return_appearance(self, looker, **kwargs): """This formats the descr...
the_stack_v2_python_sparse
evennia/contrib/tutorials/mirror/mirror.py
evennia/evennia
train
1,781
701e519a250a167b32499c5aec38aa10e39b6fc6
[ "if self.action == 'list':\n return ViewFeatureListSerializer\nelif self.include_child_pages:\n return ViewFeatureSerializer\nelse:\n return ViewFeatureRowChildrenSerializer", "context = super(ViewFeaturesBaseViewSet, self).get_serializer_context()\ncontext['include_child_pages'] = self.include_child_pag...
<|body_start_0|> if self.action == 'list': return ViewFeatureListSerializer elif self.include_child_pages: return ViewFeatureSerializer else: return ViewFeatureRowChildrenSerializer <|end_body_0|> <|body_start_1|> context = super(ViewFeaturesBaseViewS...
ViewFeaturesBaseViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewFeaturesBaseViewSet: def get_serializer_class(self): """Return the serializer to use based on action and query.""" <|body_0|> def get_serializer_context(self): """Add include_child_pages to context.""" <|body_1|> def include_child_pages(self): ...
stack_v2_sparse_classes_36k_train_031422
9,430
no_license
[ { "docstring": "Return the serializer to use based on action and query.", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "Add include_child_pages to context.", "name": "get_serializer_context", "signature": "def get_serializer_context(self...
4
stack_v2_sparse_classes_30k_train_020495
Implement the Python class `ViewFeaturesBaseViewSet` described below. Class description: Implement the ViewFeaturesBaseViewSet class. Method signatures and docstrings: - def get_serializer_class(self): Return the serializer to use based on action and query. - def get_serializer_context(self): Add include_child_pages ...
Implement the Python class `ViewFeaturesBaseViewSet` described below. Class description: Implement the ViewFeaturesBaseViewSet class. Method signatures and docstrings: - def get_serializer_class(self): Return the serializer to use based on action and query. - def get_serializer_context(self): Add include_child_pages ...
bc092964153b03381aaff74a4d80f43a2b2dec19
<|skeleton|> class ViewFeaturesBaseViewSet: def get_serializer_class(self): """Return the serializer to use based on action and query.""" <|body_0|> def get_serializer_context(self): """Add include_child_pages to context.""" <|body_1|> def include_child_pages(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewFeaturesBaseViewSet: def get_serializer_class(self): """Return the serializer to use based on action and query.""" if self.action == 'list': return ViewFeatureListSerializer elif self.include_child_pages: return ViewFeatureSerializer else: ...
the_stack_v2_python_sparse
browsercompat/webplatformcompat/viewsets.py
WeilerWebServices/MDN-Web-Docs
train
1
4c867d70f9cc1eb07747dcdf312dd1fa995895af
[ "file = open(archivo, 'r')\nlineas = []\nlineas_archivo = []\nfor linea in file.readlines():\n lineas.append(linea.replace('\\n', '').split(','))\nfile.close()\nfor f in range(0, len(lineas)):\n try:\n lineas_archivo.append([float(lineas[f][0]), float(lineas[f][1]), float(lineas[f][2]), float(lineas[f]...
<|body_start_0|> file = open(archivo, 'r') lineas = [] lineas_archivo = [] for linea in file.readlines(): lineas.append(linea.replace('\n', '').split(',')) file.close() for f in range(0, len(lineas)): try: lineas_archivo.append([flo...
Esta clase nos permite abrir un archivo de texto
Archivos
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Archivos: """Esta clase nos permite abrir un archivo de texto""" def leerArchivo(self, archivo): """Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir""" <|body_0|> def realizarOperaciones(self, lista): """Realiza lo...
stack_v2_sparse_classes_36k_train_031423
2,674
no_license
[ { "docstring": "Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir", "name": "leerArchivo", "signature": "def leerArchivo(self, archivo)" }, { "docstring": "Realiza los cálculos de la distancia manhattan y devuelve una lista con los resultados. Pará...
3
stack_v2_sparse_classes_30k_train_015233
Implement the Python class `Archivos` described below. Class description: Esta clase nos permite abrir un archivo de texto Method signatures and docstrings: - def leerArchivo(self, archivo): Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir - def realizarOperaciones(sel...
Implement the Python class `Archivos` described below. Class description: Esta clase nos permite abrir un archivo de texto Method signatures and docstrings: - def leerArchivo(self, archivo): Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir - def realizarOperaciones(sel...
b3693641f2a7c8fb45fa8a4f239667cf5d44a68a
<|skeleton|> class Archivos: """Esta clase nos permite abrir un archivo de texto""" def leerArchivo(self, archivo): """Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir""" <|body_0|> def realizarOperaciones(self, lista): """Realiza lo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Archivos: """Esta clase nos permite abrir un archivo de texto""" def leerArchivo(self, archivo): """Este método abre un archivo de texto. Parámetros: archivo: nombre del archivo que se quiere abrir""" file = open(archivo, 'r') lineas = [] lineas_archivo = [] for li...
the_stack_v2_python_sparse
5.archivos/archivos.py
L3onet/curso-python
train
0
59285e5510e2cefdddc5a6a1d28d19b35b5559c6
[ "self.entity_description = description\nself._tc_object = tc_object\nself._update_devices = update_devices\nself._attr_name = f'{tc_object.name} {description.name}'", "self._update_devices()\nsensor_type = self.entity_description.key\nif sensor_type == 'battery':\n self._attr_native_value = self._tc_object.bat...
<|body_start_0|> self.entity_description = description self._tc_object = tc_object self._update_devices = update_devices self._attr_name = f'{tc_object.name} {description.name}' <|end_body_0|> <|body_start_1|> self._update_devices() sensor_type = self.entity_description....
Representation of a ThinkingCleaner Sensor.
ThinkingCleanerSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" <|body_0|> def update(self) -> None: """Update the sensor."...
stack_v2_sparse_classes_36k_train_031424
3,910
permissive
[ { "docstring": "Initialize the ThinkingCleaner.", "name": "__init__", "signature": "def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None" }, { "docstring": "Update the sensor.", "name": "update", "signature": "def update(self) -> None" } ]
2
stack_v2_sparse_classes_30k_train_000785
Implement the Python class `ThinkingCleanerSensor` described below. Class description: Representation of a ThinkingCleaner Sensor. Method signatures and docstrings: - def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner. - def update(self) -> None...
Implement the Python class `ThinkingCleanerSensor` described below. Class description: Representation of a ThinkingCleaner Sensor. Method signatures and docstrings: - def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner. - def update(self) -> None...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" <|body_0|> def update(self) -> None: """Update the sensor."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" self.entity_description = description self._tc_object = tc_object sel...
the_stack_v2_python_sparse
homeassistant/components/thinkingcleaner/sensor.py
home-assistant/core
train
35,501
f7c0618e8b1af213f6594ad1a6496f5de699e589
[ "height_points = np.array([5.0, 10.0, 20.0])\ncube = _set_up_height_cube(height_points)\nself.plugin_positive = Integration('height', positive_integration=True)\nself.plugin_positive.input_cube = cube.copy()\nself.plugin_negative = Integration('height')\nself.plugin_negative.input_cube = cube.copy()", "result = s...
<|body_start_0|> height_points = np.array([5.0, 10.0, 20.0]) cube = _set_up_height_cube(height_points) self.plugin_positive = Integration('height', positive_integration=True) self.plugin_positive.input_cube = cube.copy() self.plugin_negative = Integration('height') self.p...
Test the prepare_for_integration method.
Test_prepare_for_integration
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" <|body_0|> def test_basic(self): """Test that the type of the returned value is as expected and the expected number of items are returned.""" ...
stack_v2_sparse_classes_36k_train_031425
25,011
permissive
[ { "docstring": "Set up the cube.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that the type of the returned value is as expected and the expected number of items are returned.", "name": "test_basic", "signature": "def test_basic(self)" }, { "docstring...
4
stack_v2_sparse_classes_30k_train_003873
Implement the Python class `Test_prepare_for_integration` described below. Class description: Test the prepare_for_integration method. Method signatures and docstrings: - def setUp(self): Set up the cube. - def test_basic(self): Test that the type of the returned value is as expected and the expected number of items ...
Implement the Python class `Test_prepare_for_integration` described below. Class description: Test the prepare_for_integration method. Method signatures and docstrings: - def setUp(self): Set up the cube. - def test_basic(self): Test that the type of the returned value is as expected and the expected number of items ...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" <|body_0|> def test_basic(self): """Test that the type of the returned value is as expected and the expected number of items are returned.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_prepare_for_integration: """Test the prepare_for_integration method.""" def setUp(self): """Set up the cube.""" height_points = np.array([5.0, 10.0, 20.0]) cube = _set_up_height_cube(height_points) self.plugin_positive = Integration('height', positive_integration=True...
the_stack_v2_python_sparse
improver_tests/utilities/test_mathematical_operations.py
metoppv/improver
train
101
8ca6e663ddd9614fbbcf333440ee9fd946ec65eb
[ "if width % 2 == 0:\n print('Width needs to be odd!')\n pass\nif height % 2 == 0:\n print('Height needs to be odd!')\n pass\nlowerW = (width - 1) / 2\nlowerH = (height - 1) / 2\nmat = numx.zeros((width, height))\nfor x in range(0, width):\n for y in range(0, height):\n mat[x, y] = numx.exp(-0....
<|body_start_0|> if width % 2 == 0: print('Width needs to be odd!') pass if height % 2 == 0: print('Height needs to be odd!') pass lowerW = (width - 1) / 2 lowerH = (height - 1) / 2 mat = numx.zeros((width, height)) for x in...
This class implements a weight layer that connects one unit layer to another with convolutional weights.
Convolving_weight_layer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Convolving_weight_layer: """This class implements a weight layer that connects one unit layer to another with convolutional weights.""" def construct_gauss_filter(cls, width, height, variance=1.0): """This function constructs a 2D-Gauss filter. :Parameters: width: Filter width. -type...
stack_v2_sparse_classes_36k_train_031426
19,732
no_license
[ { "docstring": "This function constructs a 2D-Gauss filter. :Parameters: width: Filter width. -type: int height Filter Height. -type: int variance Variance of the Gaussian -type: scalar :Returns: Convolved matrix with the same shape as matrix. -type: 2D numpy arrays", "name": "construct_gauss_filter", "...
5
stack_v2_sparse_classes_30k_train_000051
Implement the Python class `Convolving_weight_layer` described below. Class description: This class implements a weight layer that connects one unit layer to another with convolutional weights. Method signatures and docstrings: - def construct_gauss_filter(cls, width, height, variance=1.0): This function constructs a...
Implement the Python class `Convolving_weight_layer` described below. Class description: This class implements a weight layer that connects one unit layer to another with convolutional weights. Method signatures and docstrings: - def construct_gauss_filter(cls, width, height, variance=1.0): This function constructs a...
997879373110b2ee69fba921d46a309443c8e374
<|skeleton|> class Convolving_weight_layer: """This class implements a weight layer that connects one unit layer to another with convolutional weights.""" def construct_gauss_filter(cls, width, height, variance=1.0): """This function constructs a 2D-Gauss filter. :Parameters: width: Filter width. -type...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Convolving_weight_layer: """This class implements a weight layer that connects one unit layer to another with convolutional weights.""" def construct_gauss_filter(cls, width, height, variance=1.0): """This function constructs a 2D-Gauss filter. :Parameters: width: Filter width. -type: int height ...
the_stack_v2_python_sparse
pydeep/dbm/weight_layer.py
MelJan/PyDeep
train
50
902352904dfc1bc1db35dff9a1bd414387868c9a
[ "self.path = Path(path)\nself.validate()\nsuper(Processing, self).__init__(path, parent=parent, recursive=recursive, dataset_index=dataset_index, dataset_state=dataset_state)", "if not self.path.is_dir():\n raise NotProcessingFolder\nif not self.contains(self.path, ['visu_pars']):\n raise NotProcessingFolde...
<|body_start_0|> self.path = Path(path) self.validate() super(Processing, self).__init__(path, parent=parent, recursive=recursive, dataset_index=dataset_index, dataset_state=dataset_state) <|end_body_0|> <|body_start_1|> if not self.path.is_dir(): raise NotProcessingFolder ...
Processing
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Processing: def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1r', '1i'], dataset_state: dict=DEFAULT_DATASET_STATE): """The constructor for Processing class. :param path: path to a folder :param parent: parent :class:`.Folder` object :param recursive: recurs...
stack_v2_sparse_classes_36k_train_031427
17,605
permissive
[ { "docstring": "The constructor for Processing class. :param path: path to a folder :param parent: parent :class:`.Folder` object :param recursive: recursively create sub-folders :return:", "name": "__init__", "signature": "def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1...
2
stack_v2_sparse_classes_30k_train_006342
Implement the Python class `Processing` described below. Class description: Implement the Processing class. Method signatures and docstrings: - def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1r', '1i'], dataset_state: dict=DEFAULT_DATASET_STATE): The constructor for Processing class. :...
Implement the Python class `Processing` described below. Class description: Implement the Processing class. Method signatures and docstrings: - def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1r', '1i'], dataset_state: dict=DEFAULT_DATASET_STATE): The constructor for Processing class. :...
772d1b541fb998293a51c28f883e64fa74afa4c6
<|skeleton|> class Processing: def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1r', '1i'], dataset_state: dict=DEFAULT_DATASET_STATE): """The constructor for Processing class. :param path: path to a folder :param parent: parent :class:`.Folder` object :param recursive: recurs...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Processing: def __init__(self, path, parent=None, recursive=True, dataset_index=['2dseq', '1r', '1i'], dataset_state: dict=DEFAULT_DATASET_STATE): """The constructor for Processing class. :param path: path to a folder :param parent: parent :class:`.Folder` object :param recursive: recursively create s...
the_stack_v2_python_sparse
brukerapi/folders.py
isi-nmr/brukerapi-python
train
18
65532ebeb459863d2e74e325a18907c3ed0c4cb6
[ "super(EncoderCNN_VGG16, self).__init__()\nvgg16 = models.vgg16(pretrained=True)\nmodules = list(vgg16.children())[:-1]\nself.resnet = nn.Sequential(*modules)\nself.linear = nn.Linear(resnet.fc.in_features, embed_size)\nfor param in self.resnet.parameters():\n param.requires_grad = False", "features = self.res...
<|body_start_0|> super(EncoderCNN_VGG16, self).__init__() vgg16 = models.vgg16(pretrained=True) modules = list(vgg16.children())[:-1] self.resnet = nn.Sequential(*modules) self.linear = nn.Linear(resnet.fc.in_features, embed_size) for param in self.resnet.parameters(): ...
EncoderCNN_VGG16
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderCNN_VGG16: def __init__(self, embed_size): """Load the pretrained ResNet-152 and replace top fc layer.""" <|body_0|> def forward(self, images): """Extract feature vectors from input images.""" <|body_1|> <|end_skeleton|> <|body_start_0|> supe...
stack_v2_sparse_classes_36k_train_031428
7,785
no_license
[ { "docstring": "Load the pretrained ResNet-152 and replace top fc layer.", "name": "__init__", "signature": "def __init__(self, embed_size)" }, { "docstring": "Extract feature vectors from input images.", "name": "forward", "signature": "def forward(self, images)" } ]
2
stack_v2_sparse_classes_30k_train_009518
Implement the Python class `EncoderCNN_VGG16` described below. Class description: Implement the EncoderCNN_VGG16 class. Method signatures and docstrings: - def __init__(self, embed_size): Load the pretrained ResNet-152 and replace top fc layer. - def forward(self, images): Extract feature vectors from input images.
Implement the Python class `EncoderCNN_VGG16` described below. Class description: Implement the EncoderCNN_VGG16 class. Method signatures and docstrings: - def __init__(self, embed_size): Load the pretrained ResNet-152 and replace top fc layer. - def forward(self, images): Extract feature vectors from input images. ...
9b8a7695b8919ecf8906f38137df6d52d6985dd4
<|skeleton|> class EncoderCNN_VGG16: def __init__(self, embed_size): """Load the pretrained ResNet-152 and replace top fc layer.""" <|body_0|> def forward(self, images): """Extract feature vectors from input images.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncoderCNN_VGG16: def __init__(self, embed_size): """Load the pretrained ResNet-152 and replace top fc layer.""" super(EncoderCNN_VGG16, self).__init__() vgg16 = models.vgg16(pretrained=True) modules = list(vgg16.children())[:-1] self.resnet = nn.Sequential(*modules) ...
the_stack_v2_python_sparse
Visual_All/models.py
nitaytech/VisualQuestion_VQA
train
0
c0e4dc872893047e3048c9f15ccd8a48ef7e20a6
[ "l_node = [root]\nseq = []\nni = 0\nwhile ni < len(l_node):\n cur = l_node[ni]\n if cur:\n seq.append(str(cur.val))\n l_node.extend([cur.left, cur.right])\n else:\n seq.append('null')\n ni += 1\nreturn '[' + ','.join(seq) + ']'", "data = data[1:-1].split(',')\nroot_val = data[0]\n...
<|body_start_0|> l_node = [root] seq = [] ni = 0 while ni < len(l_node): cur = l_node[ni] if cur: seq.append(str(cur.val)) l_node.extend([cur.left, cur.right]) else: seq.append('null') ni += 1...
Codec
[ "MIT" ]
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_031429
1,477
permissive
[ { "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
null
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:...
1a73ce6e81cf8c3ebe58f736204dc686e85d44c5
<|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""" l_node = [root] seq = [] ni = 0 while ni < len(l_node): cur = l_node[ni] if cur: seq.append(str(cur.val)) ...
the_stack_v2_python_sparse
leetcode/297_serialize-and-deserialize-binary-tree.py
Run0812/Algorithm-Learning
train
0
de5a9d122fd7a93a6cd0939dee40845214f849db
[ "super(BarChart, self).__init__()\nself.test_case_name = test_case_name\nself.database_name = database_name\nself._order_by = order_by\nif test_ids is None or type(test_ids) is not list:\n raise UnableToGenerateVisualizations()\nelse:\n self.list_of_test_ids = test_ids\nself.statistics = {}\nfor tid in self.l...
<|body_start_0|> super(BarChart, self).__init__() self.test_case_name = test_case_name self.database_name = database_name self._order_by = order_by if test_ids is None or type(test_ids) is not list: raise UnableToGenerateVisualizations() else: self...
BarChart
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BarChart: def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency'): """:param test_case_name: :param database_name: :param test_ids: :param order_by:""" <|body_0|> def generate_json(self): """:r...
stack_v2_sparse_classes_36k_train_031430
17,005
permissive
[ { "docstring": ":param test_case_name: :param database_name: :param test_ids: :param order_by:", "name": "__init__", "signature": "def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency')" }, { "docstring": ":return:", ...
4
stack_v2_sparse_classes_30k_train_007625
Implement the Python class `BarChart` described below. Class description: Implement the BarChart class. Method signatures and docstrings: - def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency'): :param test_case_name: :param database_name: :p...
Implement the Python class `BarChart` described below. Class description: Implement the BarChart class. Method signatures and docstrings: - def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency'): :param test_case_name: :param database_name: :p...
5e33e64d77997b00a43f5573353138436b1f1a34
<|skeleton|> class BarChart: def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency'): """:param test_case_name: :param database_name: :param test_ids: :param order_by:""" <|body_0|> def generate_json(self): """:r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BarChart: def __init__(self, test_case_name=default_test_case_name, database_name=default_database_name, test_ids=None, order_by='latency'): """:param test_case_name: :param database_name: :param test_ids: :param order_by:""" super(BarChart, self).__init__() self.test_case_name = test_...
the_stack_v2_python_sparse
QuickPotato/statistical/visualizations.py
simrit1/QuickPotato
train
0
b806ccaf4b3f3d2c78925ea6ce5a726b199998d0
[ "ret = {'code': 1000, 'data': None}\ntry:\n queryset = models.CourseSubCategory.objects.all()\n ser = CourseSerializer(instance=queryset, many=True)\n ret['data'] = ser.data\nexcept Exception as e:\n ret['code'] = 1001\n ret['error'] = '获取课程失败'\nreturn Response(ret)", "ret = {'code': 1000, 'data': ...
<|body_start_0|> ret = {'code': 1000, 'data': None} try: queryset = models.CourseSubCategory.objects.all() ser = CourseSerializer(instance=queryset, many=True) ret['data'] = ser.data except Exception as e: ret['code'] = 1001 ret['error'...
CourseView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseView: def list(self, request, *args, **kwargs): """课程列表接口 :param request: :param args: :param kwargs: :return:""" <|body_0|> def retrieve(self, request, *args, **kwargs): """课程详细接口 :param request: :param args: :param kwargs: :return:""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_031431
1,572
no_license
[ { "docstring": "课程列表接口 :param request: :param args: :param kwargs: :return:", "name": "list", "signature": "def list(self, request, *args, **kwargs)" }, { "docstring": "课程详细接口 :param request: :param args: :param kwargs: :return:", "name": "retrieve", "signature": "def retrieve(self, requ...
2
stack_v2_sparse_classes_30k_train_019969
Implement the Python class `CourseView` described below. Class description: Implement the CourseView class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 课程列表接口 :param request: :param args: :param kwargs: :return: - def retrieve(self, request, *args, **kwargs): 课程详细接口 :param request: :...
Implement the Python class `CourseView` described below. Class description: Implement the CourseView class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 课程列表接口 :param request: :param args: :param kwargs: :return: - def retrieve(self, request, *args, **kwargs): 课程详细接口 :param request: :...
d50e4dcdc321b8c40ea1ec0cbf981a24ab70ce34
<|skeleton|> class CourseView: def list(self, request, *args, **kwargs): """课程列表接口 :param request: :param args: :param kwargs: :return:""" <|body_0|> def retrieve(self, request, *args, **kwargs): """课程详细接口 :param request: :param args: :param kwargs: :return:""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CourseView: def list(self, request, *args, **kwargs): """课程列表接口 :param request: :param args: :param kwargs: :return:""" ret = {'code': 1000, 'data': None} try: queryset = models.CourseSubCategory.objects.all() ser = CourseSerializer(instance=queryset, many=True)...
the_stack_v2_python_sparse
app01/views/course.py
ChemistryHuang/luffycity-3
train
2
b3eb44630285f3220d850c754d7de636c2e0f8cc
[ "if current_iter == 0:\n logging.debug('init a new train model')\n self.init_corpus_with_file(data_file)\n self.dir_path = dir_path\n self.model_name = model_name\n self.current_iter = current_iter\n self.iters_num = iters_num\n self.topics_num = topics_num\n self.K = topics_num\n self.tw...
<|body_start_0|> if current_iter == 0: logging.debug('init a new train model') self.init_corpus_with_file(data_file) self.dir_path = dir_path self.model_name = model_name self.current_iter = current_iter self.iters_num = iters_num ...
LDA模型定义,主要实现训练、继续训练、推断的过程
LdaModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LdaModel: """LDA模型定义,主要实现训练、继续训练、推断的过程""" def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): """:key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了pri...
stack_v2_sparse_classes_36k_train_031432
28,257
no_license
[ { "docstring": ":key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了prior_file先验文件外,其余所有的参数都需要,且current_iter等于0 :key: 当加载已有模型时,只需要dir_path, model_name, current_iter(不等于0), iters_num, twords_num即可 :param iters_num: 可以为整数值或者“auto”", "name": "init_train_model", "signature": "def init_t...
4
null
Implement the Python class `LdaModel` described below. Class description: LDA模型定义,主要实现训练、继续训练、推断的过程 Method signatures and docstrings: - def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): :key: 初始化训练模型,根据参数c...
Implement the Python class `LdaModel` described below. Class description: LDA模型定义,主要实现训练、继续训练、推断的过程 Method signatures and docstrings: - def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): :key: 初始化训练模型,根据参数c...
ed6b3190964371797c295346378f79197a9ce05e
<|skeleton|> class LdaModel: """LDA模型定义,主要实现训练、继续训练、推断的过程""" def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): """:key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了pri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LdaModel: """LDA模型定义,主要实现训练、继续训练、推断的过程""" def init_train_model(self, dir_path, model_name, current_iter, iters_num=None, topics_num=10, twords_num=200, alpha=-1.0, beta=0.01, data_file='', prior_file=''): """:key: 初始化训练模型,根据参数current_iter(是否等于0)决定是初始化新模型,还是加载已有模型 :key: 当初始化新模型时,除了prior_file先验文件外,...
the_stack_v2_python_sparse
01-programming_language/01-python/code/python_lda.py
MachineLP/CodeFun
train
44
ae646cba6ce2f88c719c62c6020ebca6ee3af95f
[ "super().__init__()\nself.resize(400, 400)\nself.setWindowTitle('Guide')\nself.createGuideWidget()\nguideDialogLayout = QVBoxLayout()\nguideDialogLayout.addWidget(self.guideWidget)\nself.setLayout(guideDialogLayout)", "self.guideWidget = QWidget()\nself.guideText = QTextBrowser()\nself.guideHtml = open(self.guide...
<|body_start_0|> super().__init__() self.resize(400, 400) self.setWindowTitle('Guide') self.createGuideWidget() guideDialogLayout = QVBoxLayout() guideDialogLayout.addWidget(self.guideWidget) self.setLayout(guideDialogLayout) <|end_body_0|> <|body_start_1|> ...
Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text.
Guide
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Guide: """Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text.""" def __init__(self): """Instantiate the dimension of the guide dialog and the widget inside it with its layout.""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_031433
49,456
no_license
[ { "docstring": "Instantiate the dimension of the guide dialog and the widget inside it with its layout.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Create the widget of the guide text and its layout.", "name": "createGuideWidget", "signature": "def createGu...
2
stack_v2_sparse_classes_30k_train_005895
Implement the Python class `Guide` described below. Class description: Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text. Method signatures and docstrings: - def __init__(self): Instantiate the dimension of the guide dialog and the widget ...
Implement the Python class `Guide` described below. Class description: Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text. Method signatures and docstrings: - def __init__(self): Instantiate the dimension of the guide dialog and the widget ...
c0549695e9ee41842e6af0d9c6b3f75b75338eb7
<|skeleton|> class Guide: """Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text.""" def __init__(self): """Instantiate the dimension of the guide dialog and the widget inside it with its layout.""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Guide: """Dialog Open an additional window with the tutorial to use the program. ... Attributes: guidePage : String Link of the guide text.""" def __init__(self): """Instantiate the dimension of the guide dialog and the widget inside it with its layout.""" super().__init__() self....
the_stack_v2_python_sparse
src/classes/GUI.py
mnarizzano/se20-project-16
train
0
893d6ef10b4d14255d8476558e092627443298cf
[ "q = deque([root])\noutput = []\nwhile q:\n node = q.popleft()\n if isinstance(node, TreeNode):\n output.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n output.append('x')\nreturn ','.join(output)", "data = data.split(',')\nq = deque([])\nif data[0...
<|body_start_0|> q = deque([root]) output = [] while q: node = q.popleft() if isinstance(node, TreeNode): output.append(str(node.val)) q.append(node.left) q.append(node.right) else: output.append(...
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_031434
1,622
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
null
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:...
97533d53c8892b6519e99f344489fa4fd4c9ab93
<|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""" q = deque([root]) output = [] while q: node = q.popleft() if isinstance(node, TreeNode): output.append(str(node.val)) ...
the_stack_v2_python_sparse
8. Tree/297.py
proTao/leetcode
train
0
fd13c3e8ec5c1d0a9671f41c60fd35fcc20f2be9
[ "node = self.generic_visit(node)\nif isinstance(node.func, ast.Name):\n fc_name = node.func.id\n new_name = fc_name\n integer = self.parse_integer.search(fc_name)\n if integer is not None:\n size = int(integer.groups()[0])\n new_name = 'ExprInt'\n node.func.id = new_name\n no...
<|body_start_0|> node = self.generic_visit(node) if isinstance(node.func, ast.Name): fc_name = node.func.id new_name = fc_name integer = self.parse_integer.search(fc_name) if integer is not None: size = int(integer.groups()[0]) ...
AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))
MiasmTransformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit...
stack_v2_sparse_classes_36k_train_031435
12,978
no_license
[ { "docstring": "iX(Y) -> ExprIntX(Y), 'X'(Y) -> ExprOp('X', Y), ('X' % Y)(Z) -> ExprOp('X' % Y, Z)", "name": "visit_Call", "signature": "def visit_Call(self, node)" }, { "docstring": "memX[Y] -> ExprMem(Y, X)", "name": "visit_Subscript", "signature": "def visit_Subscript(self, node)" }...
4
stack_v2_sparse_classes_30k_train_016138
Implement the Python class `MiasmTransformer` described below. Class description: AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.siz...
Implement the Python class `MiasmTransformer` described below. Class description: AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.siz...
b71431045339a2e031950d2f8d99bfce30a44e99
<|skeleton|> class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit_Call(self, n...
the_stack_v2_python_sparse
miasm2/core/sembuilder.py
buptsseGJ/VulSeeker
train
97
d010b5d0cdc10f9f981a362dccca23d65ce28906
[ "if cls._file_system_type:\n return cls._file_system_type\nfile_system = file_entry.GetFileSystem()\nfile_system_indicator = file_system.type_indicator\nif file_system_indicator == definitions.TYPE_INDICATOR_TSK:\n fs_info = file_system.GetFsInfo()\n if fs_info.info:\n type_string = unicode(fs_info....
<|body_start_0|> if cls._file_system_type: return cls._file_system_type file_system = file_entry.GetFileSystem() file_system_indicator = file_system.type_indicator if file_system_indicator == definitions.TYPE_INDICATOR_TSK: fs_info = file_system.GetFsInfo() ...
Class that extracts event objects from a stat object.
StatEvents
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatEvents: """Class that extracts event objects from a stat object.""" def GetFileSystemTypeFromFileEntry(cls, file_entry): """Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (instance of vfs.file_entry.FileEntry). Returns: A string in...
stack_v2_sparse_classes_36k_train_031436
5,148
permissive
[ { "docstring": "Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (instance of vfs.file_entry.FileEntry). Returns: A string indicating the file system type.", "name": "GetFileSystemTypeFromFileEntry", "signature": "def GetFileSystemTypeFromFileEntry(cls, fil...
2
stack_v2_sparse_classes_30k_train_016309
Implement the Python class `StatEvents` described below. Class description: Class that extracts event objects from a stat object. Method signatures and docstrings: - def GetFileSystemTypeFromFileEntry(cls, file_entry): Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (in...
Implement the Python class `StatEvents` described below. Class description: Class that extracts event objects from a stat object. Method signatures and docstrings: - def GetFileSystemTypeFromFileEntry(cls, file_entry): Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (in...
b4dc64b3a2d2906e8947824c493a2bc311d765c1
<|skeleton|> class StatEvents: """Class that extracts event objects from a stat object.""" def GetFileSystemTypeFromFileEntry(cls, file_entry): """Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (instance of vfs.file_entry.FileEntry). Returns: A string in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatEvents: """Class that extracts event objects from a stat object.""" def GetFileSystemTypeFromFileEntry(cls, file_entry): """Return a filesystem type string from a file entry object. Args: file_entry: A file entry object (instance of vfs.file_entry.FileEntry). Returns: A string indicating the ...
the_stack_v2_python_sparse
plaso/parsers/filestat.py
iwm911/plaso
train
0
a34831456df7220cf831a8265786bce62d6e91d0
[ "default_attr = {}\ndefault_attr.update(kwargs)\nsuper().__init__(default_attr=default_attr)\nself.gc = gc\nself.slide_id = slide_id\nself.callback = callback\nself.callback_kwargs = callback_kwargs\nself.slide_annotations = self.gc.get('/annotation/item/' + self.slide_id)\nself.n_annotations = len(self.slide_annot...
<|body_start_0|> default_attr = {} default_attr.update(kwargs) super().__init__(default_attr=default_attr) self.gc = gc self.slide_id = slide_id self.callback = callback self.callback_kwargs = callback_kwargs self.slide_annotations = self.gc.get('/annotati...
Iterate through annotations in a girder item (slide).
Annotation_iterator
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Annotation_iterator: """Iterate through annotations in a girder item (slide).""" def __init__(self, gc, slide_id, callback=None, callback_kwargs=None, **kwargs): """Init Annotation_iterator object. Arguments ----------- gc : object girder client object slide_id : str girder ID of sli...
stack_v2_sparse_classes_36k_train_031437
8,437
permissive
[ { "docstring": "Init Annotation_iterator object. Arguments ----------- gc : object girder client object slide_id : str girder ID of slide (item) callback : function function to apply to each annotation. Must accept at least the parameters \"gc\" and \"annotation\" and these will be passed internally to it. call...
3
stack_v2_sparse_classes_30k_train_020704
Implement the Python class `Annotation_iterator` described below. Class description: Iterate through annotations in a girder item (slide). Method signatures and docstrings: - def __init__(self, gc, slide_id, callback=None, callback_kwargs=None, **kwargs): Init Annotation_iterator object. Arguments ----------- gc : ob...
Implement the Python class `Annotation_iterator` described below. Class description: Iterate through annotations in a girder item (slide). Method signatures and docstrings: - def __init__(self, gc, slide_id, callback=None, callback_kwargs=None, **kwargs): Init Annotation_iterator object. Arguments ----------- gc : ob...
c03c852e72f1497d22535c6b7d5aba25c74e620d
<|skeleton|> class Annotation_iterator: """Iterate through annotations in a girder item (slide).""" def __init__(self, gc, slide_id, callback=None, callback_kwargs=None, **kwargs): """Init Annotation_iterator object. Arguments ----------- gc : object girder client object slide_id : str girder ID of sli...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Annotation_iterator: """Iterate through annotations in a girder item (slide).""" def __init__(self, gc, slide_id, callback=None, callback_kwargs=None, **kwargs): """Init Annotation_iterator object. Arguments ----------- gc : object girder client object slide_id : str girder ID of slide (item) cal...
the_stack_v2_python_sparse
histomicstk/workflows/workflow_runner.py
DigitalSlideArchive/HistomicsTK
train
351
06932b1c78bdca0143b981b0951fa1b3bf8d98e1
[ "self.prefix = prefix\nself.suffix = suffix\nself.decimals = decimals\nself.length = length\nself.fill = fill\nself.start = datetime.now()", "progress = float(step) / float(total)\nremain = 1 - progress\nelapsed = datetime.now() - self.start\neta = round(elapsed.total_seconds() * remain / progress)\npercent = ('{...
<|body_start_0|> self.prefix = prefix self.suffix = suffix self.decimals = decimals self.length = length self.fill = fill self.start = datetime.now() <|end_body_0|> <|body_start_1|> progress = float(step) / float(total) remain = 1 - progress elaps...
ProgressBar
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProgressBar: def __init__(self, prefix='', suffix='', decimals=1, length=100, fill='#'): """Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffix: Optional - suffix string (Str) :param decimals: Optional - positive number of decimals in percent...
stack_v2_sparse_classes_36k_train_031438
6,978
no_license
[ { "docstring": "Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffix: Optional - suffix string (Str) :param decimals: Optional - positive number of decimals in percent complete (Int) :param length: Optional - character length of bar (Int) :param fill: Optional - bar ...
2
stack_v2_sparse_classes_30k_test_000999
Implement the Python class `ProgressBar` described below. Class description: Implement the ProgressBar class. Method signatures and docstrings: - def __init__(self, prefix='', suffix='', decimals=1, length=100, fill='#'): Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffi...
Implement the Python class `ProgressBar` described below. Class description: Implement the ProgressBar class. Method signatures and docstrings: - def __init__(self, prefix='', suffix='', decimals=1, length=100, fill='#'): Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffi...
2fa45b38851391a41ca34aaf42b90af399c959df
<|skeleton|> class ProgressBar: def __init__(self, prefix='', suffix='', decimals=1, length=100, fill='#'): """Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffix: Optional - suffix string (Str) :param decimals: Optional - positive number of decimals in percent...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProgressBar: def __init__(self, prefix='', suffix='', decimals=1, length=100, fill='#'): """Create terminal progress bar @params: :param prefix: Optional - prefix string (Str) :param suffix: Optional - suffix string (Str) :param decimals: Optional - positive number of decimals in percent complete (Int...
the_stack_v2_python_sparse
spark-simulation/main.py
AdamDlubak/GRAVIsim
train
0
eaefc59547875edc50de0780177ebe8d994e58e8
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
ACLServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ACLServiceServicer: """Missing associated documentation comment in .proto file.""" def Read(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def Write(self, request, context): """Missing associated documentation c...
stack_v2_sparse_classes_36k_train_031439
11,076
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "Read", "signature": "def Read(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "Write", "signature": "def Write(self, request, context)" }, ...
6
stack_v2_sparse_classes_30k_train_017029
Implement the Python class `ACLServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def Read(self, request, context): Missing associated documentation comment in .proto file. - def Write(self, request, context): Missing assoc...
Implement the Python class `ACLServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def Read(self, request, context): Missing associated documentation comment in .proto file. - def Write(self, request, context): Missing assoc...
b94598eca5db7dd1746cc6f49c5cd0c76961b9c2
<|skeleton|> class ACLServiceServicer: """Missing associated documentation comment in .proto file.""" def Read(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def Write(self, request, context): """Missing associated documentation c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ACLServiceServicer: """Missing associated documentation comment in .proto file.""" def Read(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
authzed/api/v0/acl_service_pb2_grpc.py
hercules261188/authzed-py
train
0
855ce65cee85b4f3ebbacee370fa50276fe03de4
[ "self.logging_prefix = logging_prefix\nself.cross_validation_split_index = cross_validation_split_index\nself.log_to_parent_run = log_to_parent_run", "if not is_offline_run_context(RUN_CONTEXT):\n metric_name = self.logging_prefix + label\n RUN_CONTEXT.log(metric_name, metric)\n if self.log_to_parent_run...
<|body_start_0|> self.logging_prefix = logging_prefix self.cross_validation_split_index = cross_validation_split_index self.log_to_parent_run = log_to_parent_run <|end_body_0|> <|body_start_1|> if not is_offline_run_context(RUN_CONTEXT): metric_name = self.logging_prefix + l...
Stores the information that is required to log metrics to AzureML.
AzureMLLogger
[ "MIT", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AzureMLLogger: """Stores the information that is required to log metrics to AzureML.""" def __init__(self, cross_validation_split_index: int, logging_prefix: str, log_to_parent_run: bool): """:param cross_validation_split_index: The cross validation split index, or its default value ...
stack_v2_sparse_classes_36k_train_031440
32,709
permissive
[ { "docstring": ":param cross_validation_split_index: The cross validation split index, or its default value if not running inside cross validation. :param logging_prefix: A prefix string that will be added to all metrics names before logging. :param log_to_parent_run: If true, all metrics will also be written t...
2
null
Implement the Python class `AzureMLLogger` described below. Class description: Stores the information that is required to log metrics to AzureML. Method signatures and docstrings: - def __init__(self, cross_validation_split_index: int, logging_prefix: str, log_to_parent_run: bool): :param cross_validation_split_index...
Implement the Python class `AzureMLLogger` described below. Class description: Stores the information that is required to log metrics to AzureML. Method signatures and docstrings: - def __init__(self, cross_validation_split_index: int, logging_prefix: str, log_to_parent_run: bool): :param cross_validation_split_index...
12b496093097ef48d5ac8880985c04918d7f76fe
<|skeleton|> class AzureMLLogger: """Stores the information that is required to log metrics to AzureML.""" def __init__(self, cross_validation_split_index: int, logging_prefix: str, log_to_parent_run: bool): """:param cross_validation_split_index: The cross validation split index, or its default value ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AzureMLLogger: """Stores the information that is required to log metrics to AzureML.""" def __init__(self, cross_validation_split_index: int, logging_prefix: str, log_to_parent_run: bool): """:param cross_validation_split_index: The cross validation split index, or its default value if not runnin...
the_stack_v2_python_sparse
InnerEye/ML/metrics.py
MaxCodeXTC/InnerEye-DeepLearning
train
1
f046e9ce51316ac0f4c31ece5574e127a5d65f33
[ "self._verbose = verbose\nvecs = T.matrix('vecs')\nri = T.ivector('ri')\nci = T.ivector('ci')\nif norm == 'l2':\n distance = T.sqrt(T.sum((vecs[ri] - vecs[ci]) ** 2, axis=1))\nelif norm == 'cos':\n r_norm = T.sqrt(T.sum(vecs[ri] ** 2, axis=1))\n c_norm = T.sqrt(T.sum(vecs[ci] ** 2, axis=1))\n dot = T.su...
<|body_start_0|> self._verbose = verbose vecs = T.matrix('vecs') ri = T.ivector('ri') ci = T.ivector('ci') if norm == 'l2': distance = T.sqrt(T.sum((vecs[ri] - vecs[ci]) ** 2, axis=1)) elif norm == 'cos': r_norm = T.sqrt(T.sum(vecs[ri] ** 2, axis=1...
Distance
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Distance: def __init__(self, norm='l2', verbose=False): """Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: String Describes which norm to use (default is l2) verbose : boolean If true progressiv information wi...
stack_v2_sparse_classes_36k_train_031441
3,048
permissive
[ { "docstring": "Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: String Describes which norm to use (default is l2) verbose : boolean If true progressiv information will be printed.", "name": "__init__", "signature": "def __in...
2
stack_v2_sparse_classes_30k_train_018436
Implement the Python class `Distance` described below. Class description: Implement the Distance class. Method signatures and docstrings: - def __init__(self, norm='l2', verbose=False): Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: Strin...
Implement the Python class `Distance` described below. Class description: Implement the Distance class. Method signatures and docstrings: - def __init__(self, norm='l2', verbose=False): Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: Strin...
115fd2b955de07f34cdec998ba2a7f103ae253e3
<|skeleton|> class Distance: def __init__(self, norm='l2', verbose=False): """Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: String Describes which norm to use (default is l2) verbose : boolean If true progressiv information wi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Distance: def __init__(self, norm='l2', verbose=False): """Construct an object, with the primary method transform, there can create a sparse distance matrix. Parameters ---------- norm: String Describes which norm to use (default is l2) verbose : boolean If true progressiv information will be printed....
the_stack_v2_python_sparse
model/distance.py
AndreasMadsen/bachelor-code
train
1
7b2c416ede5c532af15b0cd434b11930247b345b
[ "super(UniSlicer, self).__init__(verbose=verbose, badval=badval, plotFuncs=plotFuncs)\nself.nslice = 1\nself.slicePoints['sid'] = np.array([0], int)", "self._runMaps(maps)\nsimDataCol = simData.dtype.names[0]\nself.indices = np.ones(len(simData[simDataCol]), dtype='bool')\n\n@wraps(self._sliceSimData)\ndef _slice...
<|body_start_0|> super(UniSlicer, self).__init__(verbose=verbose, badval=badval, plotFuncs=plotFuncs) self.nslice = 1 self.slicePoints['sid'] = np.array([0], int) <|end_body_0|> <|body_start_1|> self._runMaps(maps) simDataCol = simData.dtype.names[0] self.indices = np.on...
UniSlicer.
UniSlicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UniSlicer: """UniSlicer.""" def __init__(self, verbose=True, badval=-666, plotFuncs=None): """Instantiate unislicer.""" <|body_0|> def setupSlicer(self, simData, maps=None): """Use simData to set indexes to return.""" <|body_1|> def __eq__(self, othe...
stack_v2_sparse_classes_36k_train_031442
1,308
no_license
[ { "docstring": "Instantiate unislicer.", "name": "__init__", "signature": "def __init__(self, verbose=True, badval=-666, plotFuncs=None)" }, { "docstring": "Use simData to set indexes to return.", "name": "setupSlicer", "signature": "def setupSlicer(self, simData, maps=None)" }, { ...
3
stack_v2_sparse_classes_30k_train_020129
Implement the Python class `UniSlicer` described below. Class description: UniSlicer. Method signatures and docstrings: - def __init__(self, verbose=True, badval=-666, plotFuncs=None): Instantiate unislicer. - def setupSlicer(self, simData, maps=None): Use simData to set indexes to return. - def __eq__(self, otherSli...
Implement the Python class `UniSlicer` described below. Class description: UniSlicer. Method signatures and docstrings: - def __init__(self, verbose=True, badval=-666, plotFuncs=None): Instantiate unislicer. - def setupSlicer(self, simData, maps=None): Use simData to set indexes to return. - def __eq__(self, otherSli...
2b0faebd60fb4387366954d3531ac4d9df8c6fc4
<|skeleton|> class UniSlicer: """UniSlicer.""" def __init__(self, verbose=True, badval=-666, plotFuncs=None): """Instantiate unislicer.""" <|body_0|> def setupSlicer(self, simData, maps=None): """Use simData to set indexes to return.""" <|body_1|> def __eq__(self, othe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UniSlicer: """UniSlicer.""" def __init__(self, verbose=True, badval=-666, plotFuncs=None): """Instantiate unislicer.""" super(UniSlicer, self).__init__(verbose=verbose, badval=badval, plotFuncs=plotFuncs) self.nslice = 1 self.slicePoints['sid'] = np.array([0], int) de...
the_stack_v2_python_sparse
python/lsst/sims/maf/slicers/uniSlicer.py
nanchenchen/sims_maf
train
0
01ef60f74008e1abb8f889800f7816c20464eeab
[ "length = len(s)\nanswer = 0\nf = [0] * (length + 1)\nfor i in range(2, length + 1):\n if s[i - 2] == '(' and s[i - 1] == ')':\n f[i] = f[i - 2] + 2\n elif s[i - 2] == ')' and s[i - 1] == ')' and (i - f[i - 1] - 2 >= 0) and (s[i - f[i - 1] - 2] == '('):\n f[i] = f[i - 1] + 2 + f[i - f[i - 1] - 2...
<|body_start_0|> length = len(s) answer = 0 f = [0] * (length + 1) for i in range(2, length + 1): if s[i - 2] == '(' and s[i - 1] == ')': f[i] = f[i - 2] + 2 elif s[i - 2] == ')' and s[i - 1] == ')' and (i - f[i - 1] - 2 >= 0) and (s[i - f[i - 1] -...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParenthesesDP(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParenthesesStack(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> length = len(s) answer = 0 ...
stack_v2_sparse_classes_36k_train_031443
1,333
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "longestValidParenthesesDP", "signature": "def longestValidParenthesesDP(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "longestValidParenthesesStack", "signature": "def longestValidParenthesesStack(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_004250
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParenthesesDP(self, s): :type s: str :rtype: int - def longestValidParenthesesStack(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParenthesesDP(self, s): :type s: str :rtype: int - def longestValidParenthesesStack(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def long...
64b9e452371d989f6061d89c6b96af2ba7fe5990
<|skeleton|> class Solution: def longestValidParenthesesDP(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParenthesesStack(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestValidParenthesesDP(self, s): """:type s: str :rtype: int""" length = len(s) answer = 0 f = [0] * (length + 1) for i in range(2, length + 1): if s[i - 2] == '(' and s[i - 1] == ')': f[i] = f[i - 2] + 2 elif s[i...
the_stack_v2_python_sparse
1-50/32.py
hurenjun/LeetCode
train
1
1e64394032698e6ddfc25913ea5923e7e8e750d0
[ "if module.type == 'Conv2D':\n strides, padding, groups = aimet_tensorflow.utils.op.conv.get_conv2d_op_params(module)\n params = aimet_common.layer_database.Conv2dTypeSpecificParams(strides, padding, groups)\n self.type_specific_params = params", "self.model = model\nweight_shape = aimet_tensorflow.utils...
<|body_start_0|> if module.type == 'Conv2D': strides, padding, groups = aimet_tensorflow.utils.op.conv.get_conv2d_op_params(module) params = aimet_common.layer_database.Conv2dTypeSpecificParams(strides, padding, groups) self.type_specific_params = params <|end_body_0|> <|bod...
Holds attributes for given Op
Layer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Layer: """Holds attributes for given Op""" def _set_type_specific_params(self, module: tf.Operation): """Using the provided module set type-specific-params. :param module: Training-extension specific module""" <|body_0|> def __init__(self, model: tf.compat.v1.Session, op...
stack_v2_sparse_classes_36k_train_031444
11,506
permissive
[ { "docstring": "Using the provided module set type-specific-params. :param module: Training-extension specific module", "name": "_set_type_specific_params", "signature": "def _set_type_specific_params(self, module: tf.Operation)" }, { "docstring": ":param model: TensorFlow Session :param op: Ten...
2
null
Implement the Python class `Layer` described below. Class description: Holds attributes for given Op Method signatures and docstrings: - def _set_type_specific_params(self, module: tf.Operation): Using the provided module set type-specific-params. :param module: Training-extension specific module - def __init__(self,...
Implement the Python class `Layer` described below. Class description: Holds attributes for given Op Method signatures and docstrings: - def _set_type_specific_params(self, module: tf.Operation): Using the provided module set type-specific-params. :param module: Training-extension specific module - def __init__(self,...
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
<|skeleton|> class Layer: """Holds attributes for given Op""" def _set_type_specific_params(self, module: tf.Operation): """Using the provided module set type-specific-params. :param module: Training-extension specific module""" <|body_0|> def __init__(self, model: tf.compat.v1.Session, op...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Layer: """Holds attributes for given Op""" def _set_type_specific_params(self, module: tf.Operation): """Using the provided module set type-specific-params. :param module: Training-extension specific module""" if module.type == 'Conv2D': strides, padding, groups = aimet_tensor...
the_stack_v2_python_sparse
TrainingExtensions/tensorflow/src/python/aimet_tensorflow/layer_database.py
quic/aimet
train
1,676
899813d6c430bada0e3e38b84264c07ff6d6cb91
[ "super(LAMBOptimizer_v1, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nself.include_in_weight_decay = include_in_weight_decay...
<|body_start_0|> super(LAMBOptimizer_v1, self).__init__(False, name) self.learning_rate = learning_rate self.weight_decay_rate = weight_decay_rate self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon self.exclude_from_weight_decay = exclude_from_weight...
LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June, 2019.). - Our implementation is based on `AdamWeightDecayOptimizer` in BERT (prov...
LAMBOptimizer_v1
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LAMBOptimizer_v1: """LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June, 2019.). - Our implementation is based...
stack_v2_sparse_classes_36k_train_031445
25,398
permissive
[ { "docstring": "Constructs a LAMBOptimizer.", "name": "__init__", "signature": "def __init__(self, learning_rate, weight_decay_rate=0.01, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], name='LAMBOptimizer')" }, {...
4
stack_v2_sparse_classes_30k_train_011595
Implement the Python class `LAMBOptimizer_v1` described below. Class description: LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June...
Implement the Python class `LAMBOptimizer_v1` described below. Class description: LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June...
480c909e0835a455606e829310ff949c9dd23549
<|skeleton|> class LAMBOptimizer_v1: """LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June, 2019.). - Our implementation is based...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LAMBOptimizer_v1: """LAMBOptimizer optimizer. https://github.com/ymcui/LAMB_Optimizer_TF # IMPORTANT NOTE - This is NOT an official implementation. - LAMB optimizer is changed from arXiv v1 ~ v3. - We implement v3 version (which is the latest version on June, 2019.). - Our implementation is based on `AdamWeig...
the_stack_v2_python_sparse
t2t_bert/optimizer/optimizer_utils.py
yyht/BERT
train
37
c886f53809179128f2c1587c8375019deaa81619
[ "local_file = f'{local_path}system_logs.txt'\ncommand = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}'\nprint(f'fetch command = {command}')\nos.system(command)\nreturn local_file", "local_file = f'{local_path}secondary_system_logs.txt'\ncommand = f'sshpass -p...
<|body_start_0|> local_file = f'{local_path}system_logs.txt' command = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}' print(f'fetch command = {command}') os.system(command) return local_file <|end_body_0|> <|body_start_1|> ...
Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, password, remote_file, local_...
LogFetcher
[ "Apache-2.0", "BSD-3-Clause", "MIT", "WTFPL", "GPL-2.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogFetcher: """Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u...
stack_v2_sparse_classes_36k_train_031446
13,309
permissive
[ { "docstring": "Fetches system logs from server and copies to local machine :param host: str, ssh host :param username: str, ssh username :param password: str, ssh password :param remote_file: str, location of system logs on server :param local_path: str, local path to copy system logs to :return: local_file: s...
3
stack_v2_sparse_classes_30k_train_020422
Implement the Python class `LogFetcher` described below. Class description: Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se...
Implement the Python class `LogFetcher` described below. Class description: Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class LogFetcher: """Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogFetcher: """Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, pass...
the_stack_v2_python_sparse
govern/data-security/ranger/ranger-tools/src/main/python/ranger_performance_tool/ranger_perf_utils/logging_utils.py
alldatacenter/alldata
train
774
494967e79f0a9fa3e6333dfe2d57f191ece3b6e5
[ "AxisFormat.__init__(self, 'clustersold')\nself._axes['energy'] = 0\nself._axes['vertexz'] = 1\nself._axes['pileup'] = 2\nself._axes['mbtrigger'] = 3", "newobj = AxisFormatClustersOld()\nnewobj._Deepcopy(other, memo)\nreturn newobj", "newobj = AxisFormatClustersOld()\nnewobj._Copy()\nreturn newobj" ]
<|body_start_0|> AxisFormat.__init__(self, 'clustersold') self._axes['energy'] = 0 self._axes['vertexz'] = 1 self._axes['pileup'] = 2 self._axes['mbtrigger'] = 3 <|end_body_0|> <|body_start_1|> newobj = AxisFormatClustersOld() newobj._Deepcopy(other, memo) ...
Axis format for old cluster THnSparse
AxisFormatClustersOld
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AxisFormatClustersOld: """Axis format for old cluster THnSparse""" def __init__(self): """Constructor""" <|body_0|> def __deepcopy__(self, other, memo): """Deep copy constructor""" <|body_1|> def __copy__(self, other): """Shallow copy constru...
stack_v2_sparse_classes_36k_train_031447
5,256
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Deep copy constructor", "name": "__deepcopy__", "signature": "def __deepcopy__(self, other, memo)" }, { "docstring": "Shallow copy constructor", "name": "__copy__", "sig...
3
stack_v2_sparse_classes_30k_train_018846
Implement the Python class `AxisFormatClustersOld` described below. Class description: Axis format for old cluster THnSparse Method signatures and docstrings: - def __init__(self): Constructor - def __deepcopy__(self, other, memo): Deep copy constructor - def __copy__(self, other): Shallow copy constructor
Implement the Python class `AxisFormatClustersOld` described below. Class description: Axis format for old cluster THnSparse Method signatures and docstrings: - def __init__(self): Constructor - def __deepcopy__(self, other, memo): Deep copy constructor - def __copy__(self, other): Shallow copy constructor <|skeleto...
5df28b2b415e78e81273b0d9bf5c1b99feda3348
<|skeleton|> class AxisFormatClustersOld: """Axis format for old cluster THnSparse""" def __init__(self): """Constructor""" <|body_0|> def __deepcopy__(self, other, memo): """Deep copy constructor""" <|body_1|> def __copy__(self, other): """Shallow copy constru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AxisFormatClustersOld: """Axis format for old cluster THnSparse""" def __init__(self): """Constructor""" AxisFormat.__init__(self, 'clustersold') self._axes['energy'] = 0 self._axes['vertexz'] = 1 self._axes['pileup'] = 2 self._axes['mbtrigger'] = 3 de...
the_stack_v2_python_sparse
PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/ClusterTHnSparse.py
alisw/AliPhysics
train
129
607a361f91295016287c81c4fb7f8165ea4c5111
[ "self.connections = []\nfor x in connections:\n if x not in self.connections:\n self.connections.append(x)", "if connection in self.connections:\n return False\nelse:\n self.connections.append(connection)\n return True", "if connection in self.connections:\n self.connections.remove(connect...
<|body_start_0|> self.connections = [] for x in connections: if x not in self.connections: self.connections.append(x) <|end_body_0|> <|body_start_1|> if connection in self.connections: return False else: self.connections.append(connect...
Friends
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Friends: def __init__(self, connections): """>>> f1 = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) >>> f2 = Friends([{"1", "2"}, {"3", "1"}])""" <|body_0|> def add(self, connection): """>>> f = Friends([{"1", "2"}, {"3", "1"}]) >>> f.add({"1", "3"}) Fals...
stack_v2_sparse_classes_36k_train_031448
2,353
no_license
[ { "docstring": ">>> f1 = Friends(({\"a\", \"b\"}, {\"b\", \"c\"}, {\"c\", \"a\"}, {\"a\", \"c\"})) >>> f2 = Friends([{\"1\", \"2\"}, {\"3\", \"1\"}])", "name": "__init__", "signature": "def __init__(self, connections)" }, { "docstring": ">>> f = Friends([{\"1\", \"2\"}, {\"3\", \"1\"}]) >>> f.ad...
5
stack_v2_sparse_classes_30k_train_017216
Implement the Python class `Friends` described below. Class description: Implement the Friends class. Method signatures and docstrings: - def __init__(self, connections): >>> f1 = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) >>> f2 = Friends([{"1", "2"}, {"3", "1"}]) - def add(self, connection): >>> f = ...
Implement the Python class `Friends` described below. Class description: Implement the Friends class. Method signatures and docstrings: - def __init__(self, connections): >>> f1 = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) >>> f2 = Friends([{"1", "2"}, {"3", "1"}]) - def add(self, connection): >>> f = ...
4bc81d977977efb04e6e19f9025d4288390d42dc
<|skeleton|> class Friends: def __init__(self, connections): """>>> f1 = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) >>> f2 = Friends([{"1", "2"}, {"3", "1"}])""" <|body_0|> def add(self, connection): """>>> f = Friends([{"1", "2"}, {"3", "1"}]) >>> f.add({"1", "3"}) Fals...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Friends: def __init__(self, connections): """>>> f1 = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) >>> f2 = Friends([{"1", "2"}, {"3", "1"}])""" self.connections = [] for x in connections: if x not in self.connections: self.connections.append(x)...
the_stack_v2_python_sparse
Elementary/Friends/Friends.py
lyyljs/CheckiO_Games
train
0
c5afd837def6a6ec93ab77a5746a49b3d3ffd86d
[ "self.name = name\nconv2d = functools.partial(LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope)\nself.blocks = []\nwith tf.variable_scope(self.name):\n with tf.variable_scope('res0'):\n if use_dropout:\n self.blocks.append(LayerPipe([conv2d('...
<|body_start_0|> self.name = name conv2d = functools.partial(LayerConv, w=3, n=[nc, nc], stride=1, padding=padding, use_scaling=use_scaling, relu_slope=relu_slope) self.blocks = [] with tf.variable_scope(self.name): with tf.variable_scope('res0'): if use_dropo...
ResBlock
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResBlock: def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.0, use_dropout=False): """Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. nc: 2-tuple of ints, input an...
stack_v2_sparse_classes_36k_train_031449
13,442
permissive
[ { "docstring": "Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. nc: 2-tuple of ints, input and output channel depths. padding: string, the padding method {SAME, VALID, REFLECT}. use_scaling: bool, whether to use weight norm and scaling. relu_slope: f...
2
stack_v2_sparse_classes_30k_train_008508
Implement the Python class `ResBlock` described below. Class description: Implement the ResBlock class. Method signatures and docstrings: - def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.0, use_dropout=False): Layer constructor. Args: name: string, lay...
Implement the Python class `ResBlock` described below. Class description: Implement the ResBlock class. Method signatures and docstrings: - def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.0, use_dropout=False): Layer constructor. Args: name: string, lay...
091d6ae9e087cf5a6e18b00bce7d8f7ede9d9d08
<|skeleton|> class ResBlock: def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.0, use_dropout=False): """Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. nc: 2-tuple of ints, input an...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResBlock: def __init__(self, name, nc, norm_layer_constructor, activation, padding='SAME', use_scaling=False, relu_slope=1.0, use_dropout=False): """Layer constructor. Args: name: string, layer name. stride: int or 2-tuple, stride for the convolution kernel. nc: 2-tuple of ints, input and output chann...
the_stack_v2_python_sparse
layers.py
MoustafaMeshry/StEP
train
6
01cda23f1541d885ff24899f2d840e19b88284b3
[ "result = []\nfor i in range(0, len(nums) + 1):\n result += self.combinationSolo(nums, i)\nreturn result", "nums = sorted(nums)\nif k == 0:\n return [[]]\nelif k == len(nums):\n return [nums]\nelif k == 1:\n result = []\n for i in nums:\n if [i] not in result:\n result.append([i])...
<|body_start_0|> result = [] for i in range(0, len(nums) + 1): result += self.combinationSolo(nums, i) return result <|end_body_0|> <|body_start_1|> nums = sorted(nums) if k == 0: return [[]] elif k == len(nums): return [nums] ...
Solution_A
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" <|body_0|> def combinationSolo(self, nums: List[int], k: int) -> List[List[i...
stack_v2_sparse_classes_36k_train_031450
4,175
permissive
[ { "docstring": "With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list", "name": "subsetsWithDup", "signature": "def subsetsWithDup(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "Helper for A1, refer to LC077, modify ...
2
stack_v2_sparse_classes_30k_train_010370
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t...
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back t...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" <|body_0|> def combinationSolo(self, nums: List[int], k: int) -> List[List[i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_A: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """With the help from the combinationSolo from Leetcode LC077 use tuple and set to remove repeat and convert back to list""" result = [] for i in range(0, len(nums) + 1): result += self.combinationSol...
the_stack_v2_python_sparse
LeetCode/LC090_subsets_ii.py
jxie0755/Learning_Python
train
0
84ff0893fd594936b30cd34a9aa58a2aa39a313e
[ "if kwargs.get('description', None):\n self.description = kwargs.pop('description')\nsuper().__init__(children, *args, **kwargs)", "kwargs = super().clone_kwargs()\nif hasattr(self, 'description'):\n kwargs['description'] = self.description\nreturn kwargs" ]
<|body_start_0|> if kwargs.get('description', None): self.description = kwargs.pop('description') super().__init__(children, *args, **kwargs) <|end_body_0|> <|body_start_1|> kwargs = super().clone_kwargs() if hasattr(self, 'description'): kwargs['description'] = ...
Replace default MultiFieldPanel with one that can display descriptions.
MultiFieldPanel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiFieldPanel: """Replace default MultiFieldPanel with one that can display descriptions.""" def __init__(self, children=(), *args, **kwargs): """Overwrite __init__ method to remove and capture description kwarg.""" <|body_0|> def clone_kwargs(self): """Overwri...
stack_v2_sparse_classes_36k_train_031451
3,353
permissive
[ { "docstring": "Overwrite __init__ method to remove and capture description kwarg.", "name": "__init__", "signature": "def __init__(self, children=(), *args, **kwargs)" }, { "docstring": "Overwrite clone_kwargs method to populate MultiFieldPanel with additional kwargs.", "name": "clone_kwarg...
2
null
Implement the Python class `MultiFieldPanel` described below. Class description: Replace default MultiFieldPanel with one that can display descriptions. Method signatures and docstrings: - def __init__(self, children=(), *args, **kwargs): Overwrite __init__ method to remove and capture description kwarg. - def clone_...
Implement the Python class `MultiFieldPanel` described below. Class description: Replace default MultiFieldPanel with one that can display descriptions. Method signatures and docstrings: - def __init__(self, children=(), *args, **kwargs): Overwrite __init__ method to remove and capture description kwarg. - def clone_...
4cf7be72b6b3d0c46dcadcc9d9904b471215ea81
<|skeleton|> class MultiFieldPanel: """Replace default MultiFieldPanel with one that can display descriptions.""" def __init__(self, children=(), *args, **kwargs): """Overwrite __init__ method to remove and capture description kwarg.""" <|body_0|> def clone_kwargs(self): """Overwri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiFieldPanel: """Replace default MultiFieldPanel with one that can display descriptions.""" def __init__(self, children=(), *args, **kwargs): """Overwrite __init__ method to remove and capture description kwarg.""" if kwargs.get('description', None): self.description = kwar...
the_stack_v2_python_sparse
iati_standard/edit_handlers.py
IATI/IATI-Standard-Website
train
4
f89c26f05369f303cc68cba485eb7d24306eaa7d
[ "func_name = 'get_svi_mac'\ntry:\n status_data = {'status': 0}\n t_info = re.sub('(\\\\\\\\r)+', '', info, re.DOTALL)\n svi_mac = 0\n for line in t_info.split('\\n'):\n nested_print(line)\n s = re.search('HWaddr (([0-9A-F][0-9A-F]:){5}[0-9A-F][0-9A-F])', line, re.U)\n if s:\n ...
<|body_start_0|> func_name = 'get_svi_mac' try: status_data = {'status': 0} t_info = re.sub('(\\\\r)+', '', info, re.DOTALL) svi_mac = 0 for line in t_info.split('\n'): nested_print(line) s = re.search('HWaddr (([0-9A-F][0-9...
fsw
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class fsw: def get_svi_mac(self, info): """This python API parses and return svi mac address""" <|body_0|> def parse_system_status(self, info): """This python API parses and return system status in a dictionary format""" <|body_1|> def get_module_name(self, mo...
stack_v2_sparse_classes_36k_train_031452
5,698
no_license
[ { "docstring": "This python API parses and return svi mac address", "name": "get_svi_mac", "signature": "def get_svi_mac(self, info)" }, { "docstring": "This python API parses and return system status in a dictionary format", "name": "parse_system_status", "signature": "def parse_system_...
5
stack_v2_sparse_classes_30k_train_019950
Implement the Python class `fsw` described below. Class description: Implement the fsw class. Method signatures and docstrings: - def get_svi_mac(self, info): This python API parses and return svi mac address - def parse_system_status(self, info): This python API parses and return system status in a dictionary format...
Implement the Python class `fsw` described below. Class description: Implement the fsw class. Method signatures and docstrings: - def get_svi_mac(self, info): This python API parses and return svi mac address - def parse_system_status(self, info): This python API parses and return system status in a dictionary format...
936d32629061c4685d8e18b5cf9f001255514ec1
<|skeleton|> class fsw: def get_svi_mac(self, info): """This python API parses and return svi mac address""" <|body_0|> def parse_system_status(self, info): """This python API parses and return system status in a dictionary format""" <|body_1|> def get_module_name(self, mo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class fsw: def get_svi_mac(self, info): """This python API parses and return svi mac address""" func_name = 'get_svi_mac' try: status_data = {'status': 0} t_info = re.sub('(\\\\r)+', '', info, re.DOTALL) svi_mac = 0 for line in t_info.split('\n...
the_stack_v2_python_sparse
lib/util/fsw.py
rayjiang2013/RF
train
1
2044a29673fe0d4bcf1ab4a40ef659a13bdffe09
[ "if self.has_next():\n return self.paginator.link_template % (self.number + 1)\nreturn None", "if self.has_previous():\n return self.paginator.link_template % (self.number - 1)\nreturn None", "offset = self.paginator.offset\nif offset is None:\n raise ValueError(\"Can't determine start index of paginat...
<|body_start_0|> if self.has_next(): return self.paginator.link_template % (self.number + 1) return None <|end_body_0|> <|body_start_1|> if self.has_previous(): return self.paginator.link_template % (self.number - 1) return None <|end_body_1|> <|body_start_2|> ...
FinitePage
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FinitePage: def next_link(self): """URL for the next page of results (or None).""" <|body_0|> def previous_link(self): """URL for the previous page of results (or None).""" <|body_1|> def start_index(self): """Returns the 1-based index of the fir...
stack_v2_sparse_classes_36k_train_031453
4,055
permissive
[ { "docstring": "URL for the next page of results (or None).", "name": "next_link", "signature": "def next_link(self)" }, { "docstring": "URL for the previous page of results (or None).", "name": "previous_link", "signature": "def previous_link(self)" }, { "docstring": "Returns th...
3
stack_v2_sparse_classes_30k_train_013993
Implement the Python class `FinitePage` described below. Class description: Implement the FinitePage class. Method signatures and docstrings: - def next_link(self): URL for the next page of results (or None). - def previous_link(self): URL for the previous page of results (or None). - def start_index(self): Returns t...
Implement the Python class `FinitePage` described below. Class description: Implement the FinitePage class. Method signatures and docstrings: - def next_link(self): URL for the next page of results (or None). - def previous_link(self): URL for the previous page of results (or None). - def start_index(self): Returns t...
e8e43df7d1930398a3af2ea8755bd7b6a44b4385
<|skeleton|> class FinitePage: def next_link(self): """URL for the next page of results (or None).""" <|body_0|> def previous_link(self): """URL for the previous page of results (or None).""" <|body_1|> def start_index(self): """Returns the 1-based index of the fir...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FinitePage: def next_link(self): """URL for the next page of results (or None).""" if self.has_next(): return self.paginator.link_template % (self.number + 1) return None def previous_link(self): """URL for the previous page of results (or None).""" if ...
the_stack_v2_python_sparse
typepadapp/utils/paginator.py
sivy/typepadapp
train
0
dfc6a42d38f5cea66c588e9bedb6a593450e3ffc
[ "with open(file_path, 'a') as file:\n for i in range(0, len(circuits)):\n file.write(circuits[i].qasm())\n if i != len(circuits) - 1:\n file.write(qasm_file_separator_token + '\\n')", "with open(file_path, 'r') as file:\n circuits_strings = file.read().split(qasm_file_separator_toke...
<|body_start_0|> with open(file_path, 'a') as file: for i in range(0, len(circuits)): file.write(circuits[i].qasm()) if i != len(circuits) - 1: file.write(qasm_file_separator_token + '\n') <|end_body_0|> <|body_start_1|> with open(file_pat...
A class for serializing Qiskit Quantum Circuits.
QiskitSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QiskitSerializer: """A class for serializing Qiskit Quantum Circuits.""" def serialize(circuits, file_path): """Serializes the given Qiskit Quantum Circuits and stores it at the given location.""" <|body_0|> def deserialize(file_path): """Deserializes the file be...
stack_v2_sparse_classes_36k_train_031454
1,158
no_license
[ { "docstring": "Serializes the given Qiskit Quantum Circuits and stores it at the given location.", "name": "serialize", "signature": "def serialize(circuits, file_path)" }, { "docstring": "Deserializes the file behind the given url to list of Qiskit Quantum Circuits.", "name": "deserialize"...
2
stack_v2_sparse_classes_30k_train_009410
Implement the Python class `QiskitSerializer` described below. Class description: A class for serializing Qiskit Quantum Circuits. Method signatures and docstrings: - def serialize(circuits, file_path): Serializes the given Qiskit Quantum Circuits and stores it at the given location. - def deserialize(file_path): Des...
Implement the Python class `QiskitSerializer` described below. Class description: A class for serializing Qiskit Quantum Circuits. Method signatures and docstrings: - def serialize(circuits, file_path): Serializes the given Qiskit Quantum Circuits and stores it at the given location. - def deserialize(file_path): Des...
ee78db14c0d5fc37d9990cf8ad634f5e264c161b
<|skeleton|> class QiskitSerializer: """A class for serializing Qiskit Quantum Circuits.""" def serialize(circuits, file_path): """Serializes the given Qiskit Quantum Circuits and stores it at the given location.""" <|body_0|> def deserialize(file_path): """Deserializes the file be...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QiskitSerializer: """A class for serializing Qiskit Quantum Circuits.""" def serialize(circuits, file_path): """Serializes the given Qiskit Quantum Circuits and stores it at the given location.""" with open(file_path, 'a') as file: for i in range(0, len(circuits)): ...
the_stack_v2_python_sparse
qhana_openapi/clustering/qiskitSerializer.py
IndikaKuma/quantum
train
0
58f65d75ad373949cf0198f5c14d8a296cf06d03
[ "super().__init__(coordinator=coordinator, kind=kind, name=name, icon=icon, item_id=item_id, state_key=state_key)\nself._max_speed = int(coordinator.data[item_id].get('Max-Pump-Speed', 100))\nself._min_speed = int(coordinator.data[item_id].get('Min-Pump-Speed', 0))\nif 'Filter-Type' in coordinator.data[item_id]:\n ...
<|body_start_0|> super().__init__(coordinator=coordinator, kind=kind, name=name, icon=icon, item_id=item_id, state_key=state_key) self._max_speed = int(coordinator.data[item_id].get('Max-Pump-Speed', 100)) self._min_speed = int(coordinator.data[item_id].get('Min-Pump-Speed', 0)) if 'Filt...
Define the OmniLogic Pump Switch Entity.
OmniLogicPumpControl
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OmniLogicPumpControl: """Define the OmniLogic Pump Switch Entity.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize entities.""" <|body_0|> async def async_turn_on(self, ...
stack_v2_sparse_classes_36k_train_031455
8,137
permissive
[ { "docstring": "Initialize entities.", "name": "__init__", "signature": "def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None" }, { "docstring": "Turn on the pump.", "name": "async_turn_on", "signature": "asy...
4
stack_v2_sparse_classes_30k_test_000266
Implement the Python class `OmniLogicPumpControl` described below. Class description: Define the OmniLogic Pump Switch Entity. Method signatures and docstrings: - def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize entities. ...
Implement the Python class `OmniLogicPumpControl` described below. Class description: Define the OmniLogic Pump Switch Entity. Method signatures and docstrings: - def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize entities. ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OmniLogicPumpControl: """Define the OmniLogic Pump Switch Entity.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize entities.""" <|body_0|> async def async_turn_on(self, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OmniLogicPumpControl: """Define the OmniLogic Pump Switch Entity.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize entities.""" super().__init__(coordinator=coordinator, kind=kind, name=n...
the_stack_v2_python_sparse
homeassistant/components/omnilogic/switch.py
home-assistant/core
train
35,501
630b315d55a7f1f9314aa6ecb758d9b5262dbf81
[ "positions, got_single_position = convert_to_list(positions, BacktestPosition)\n\ndef compute_percentage_pnl(position: BacktestPosition):\n if portfolio_values is not None:\n return position.total_pnl / portfolio_values.asof(position.start_time)\n else:\n return None\ntrades = [Trade(p.start_tim...
<|body_start_0|> positions, got_single_position = convert_to_list(positions, BacktestPosition) def compute_percentage_pnl(position: BacktestPosition): if portfolio_values is not None: return position.total_pnl / portfolio_values.asof(position.start_time) else: ...
Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions.
TradesGenerator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TradesGenerator: """Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions.""" def create_trades_from_backtest_positions(self, positions: Union[BacktestPosition, Sequence[BacktestPosition]], portfolio_values: Optional[QFSerie...
stack_v2_sparse_classes_36k_train_031456
7,535
permissive
[ { "docstring": "Generates trades from BacktestPositions. Parameters ---------- positions: BacktestPosition, Sequence[BacktestPosition] Position or positions that will be used to generated the trades portfolio_values: Optional[QFSeries] Series containing portfolio values at different point in time. It is optiona...
4
null
Implement the Python class `TradesGenerator` described below. Class description: Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions. Method signatures and docstrings: - def create_trades_from_backtest_positions(self, positions: Union[BacktestPosit...
Implement the Python class `TradesGenerator` described below. Class description: Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions. Method signatures and docstrings: - def create_trades_from_backtest_positions(self, positions: Union[BacktestPosit...
f707e51bc2ff45f6e46dcdd24d59d83ce7dc4f94
<|skeleton|> class TradesGenerator: """Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions.""" def create_trades_from_backtest_positions(self, positions: Union[BacktestPosition, Sequence[BacktestPosition]], portfolio_values: Optional[QFSerie...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TradesGenerator: """Class responsible for generating Trade objects from information provided in the form of Transactions or BacktestPositions.""" def create_trades_from_backtest_positions(self, positions: Union[BacktestPosition, Sequence[BacktestPosition]], portfolio_values: Optional[QFSeries]=None) -> U...
the_stack_v2_python_sparse
qf_lib/analysis/trade_analysis/trades_generator.py
quarkfin/qf-lib
train
379
08cfdcc97016edc56b3a099c5f01cd65edbe7b3d
[ "PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate')\ntemplate = PartParameterTemplate.objects.create(name='Template 1', description='a part parameter template')\nwith self.assertRaises(AttributeError):\n template.choices\nwith self.assertRaises(AttributeError):\n template.c...
<|body_start_0|> PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate') template = PartParameterTemplate.objects.create(name='Template 1', description='a part parameter template') with self.assertRaises(AttributeError): template.choices with se...
Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987
TestPartParameterTemplateMigration
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPartParameterTemplateMigration: """Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987""" def prepare(self): """Prepare some parts with units""" <|body_0|> def test_units_migration(self): """Test that the new...
stack_v2_sparse_classes_36k_train_031457
8,200
permissive
[ { "docstring": "Prepare some parts with units", "name": "prepare", "signature": "def prepare(self)" }, { "docstring": "Test that the new fields have been added correctly", "name": "test_units_migration", "signature": "def test_units_migration(self)" } ]
2
null
Implement the Python class `TestPartParameterTemplateMigration` described below. Class description: Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987 Method signatures and docstrings: - def prepare(self): Prepare some parts with units - def test_units_migration(sel...
Implement the Python class `TestPartParameterTemplateMigration` described below. Class description: Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987 Method signatures and docstrings: - def prepare(self): Prepare some parts with units - def test_units_migration(sel...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestPartParameterTemplateMigration: """Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987""" def prepare(self): """Prepare some parts with units""" <|body_0|> def test_units_migration(self): """Test that the new...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPartParameterTemplateMigration: """Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987""" def prepare(self): """Prepare some parts with units""" PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate') ...
the_stack_v2_python_sparse
InvenTree/part/test_migrations.py
inventree/InvenTree
train
3,077
c63ea35c319f69c8a17c262c620a9577e8fb7188
[ "wx.Dialog.__init__(self, None, title='Login')\nself.logged_in = False\nuser_sizer = wx.BoxSizer(wx.HORIZONTAL)\nuser_lbl = wx.StaticText(self, label='Username:')\nuser_sizer.Add(user_lbl, 0, wx.ALL | wx.CENTER, 5)\nself.user = wx.TextCtrl(self)\nuser_sizer.Add(self.user, 0, wx.ALL, 5)\np_sizer = wx.BoxSizer(wx.HOR...
<|body_start_0|> wx.Dialog.__init__(self, None, title='Login') self.logged_in = False user_sizer = wx.BoxSizer(wx.HORIZONTAL) user_lbl = wx.StaticText(self, label='Username:') user_sizer.Add(user_lbl, 0, wx.ALL | wx.CENTER, 5) self.user = wx.TextCtrl(self) user_si...
Class to define login dialog
LoginDialog
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoginDialog: """Class to define login dialog""" def __init__(self): """Constructor""" <|body_0|> def onLogin(self, event): """Check credentials and login""" <|body_1|> <|end_skeleton|> <|body_start_0|> wx.Dialog.__init__(self, None, title='Login...
stack_v2_sparse_classes_36k_train_031458
2,868
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Check credentials and login", "name": "onLogin", "signature": "def onLogin(self, event)" } ]
2
stack_v2_sparse_classes_30k_train_019817
Implement the Python class `LoginDialog` described below. Class description: Class to define login dialog Method signatures and docstrings: - def __init__(self): Constructor - def onLogin(self, event): Check credentials and login
Implement the Python class `LoginDialog` described below. Class description: Class to define login dialog Method signatures and docstrings: - def __init__(self): Constructor - def onLogin(self, event): Check credentials and login <|skeleton|> class LoginDialog: """Class to define login dialog""" def __init_...
b723ca7a0668bd758d629c5d19f5b1d17778088f
<|skeleton|> class LoginDialog: """Class to define login dialog""" def __init__(self): """Constructor""" <|body_0|> def onLogin(self, event): """Check credentials and login""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoginDialog: """Class to define login dialog""" def __init__(self): """Constructor""" wx.Dialog.__init__(self, None, title='Login') self.logged_in = False user_sizer = wx.BoxSizer(wx.HORIZONTAL) user_lbl = wx.StaticText(self, label='Username:') user_sizer.A...
the_stack_v2_python_sparse
Programming Foundations with Python/src/cn/careerwinner/sap/loginPY.py
BlessedAndy/Programming-Foundations-with-Python
train
1
c2c5e005b3c3de4be0b46cac6045f476cfe468f5
[ "try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('Verification link has expired')\nexcept jwt.exceptions.PyJWTError:\n raise serializers.ValidationError('Invalidad token')\nif payload['type'] != 'email_confir...
<|body_start_0|> try: payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256']) except jwt.ExpiredSignatureError: raise serializers.ValidationError('Verification link has expired') except jwt.exceptions.PyJWTError: raise serializers.ValidationError(...
Account verification serializer.
AccountVerificationSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountVerificationSerializer: """Account verification serializer.""" def validate_token(self, data): """Verify token is valid.""" <|body_0|> def save(self): """Update user's verified status.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_031459
7,359
permissive
[ { "docstring": "Verify token is valid.", "name": "validate_token", "signature": "def validate_token(self, data)" }, { "docstring": "Update user's verified status.", "name": "save", "signature": "def save(self)" } ]
2
stack_v2_sparse_classes_30k_val_000876
Implement the Python class `AccountVerificationSerializer` described below. Class description: Account verification serializer. Method signatures and docstrings: - def validate_token(self, data): Verify token is valid. - def save(self): Update user's verified status.
Implement the Python class `AccountVerificationSerializer` described below. Class description: Account verification serializer. Method signatures and docstrings: - def validate_token(self, data): Verify token is valid. - def save(self): Update user's verified status. <|skeleton|> class AccountVerificationSerializer:...
5c37c6876ca13b5794ac44e0342b810426acbc76
<|skeleton|> class AccountVerificationSerializer: """Account verification serializer.""" def validate_token(self, data): """Verify token is valid.""" <|body_0|> def save(self): """Update user's verified status.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountVerificationSerializer: """Account verification serializer.""" def validate_token(self, data): """Verify token is valid.""" try: payload = jwt.decode(data, settings.SECRET_KEY, algorithm=['HS256']) except jwt.ExpiredSignatureError: raise serializers....
the_stack_v2_python_sparse
hisitter/users/serializers/users.py
babysitter-finder/backend
train
1
ceab8c2e699a1286c6585bf758ab486ffe7c1e1e
[ "if not I.PIL_INSTALLED:\n raise Exception('PIL is not installed. Please install with: pip install pillow>=9.0.1')\nsuper().__init__(device=device, quantize=False, min_transformers_version='4.12.3')\nself.pipeline = pipeline('image-classification' if classification else 'object-detection', device=self.device_to_...
<|body_start_0|> if not I.PIL_INSTALLED: raise Exception('PIL is not installed. Please install with: pip install pillow>=9.0.1') super().__init__(device=device, quantize=False, min_transformers_version='4.12.3') self.pipeline = pipeline('image-classification' if classification else '...
interface to Image Captioner
ObjectDetector
[ "Apache-2.0", "CC-BY-NC-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectDetector: """interface to Image Captioner""" def __init__(self, device=None, classification=False, threshold=0.9): """``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float): threshold for object detection classification(bool): I...
stack_v2_sparse_classes_36k_train_031460
2,952
permissive
[ { "docstring": "``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float): threshold for object detection classification(bool): If True, simpy do image classification ```", "name": "__init__", "signature": "def __init__(self, device=None, classification=Fal...
2
null
Implement the Python class `ObjectDetector` described below. Class description: interface to Image Captioner Method signatures and docstrings: - def __init__(self, device=None, classification=False, threshold=0.9): ``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float...
Implement the Python class `ObjectDetector` described below. Class description: interface to Image Captioner Method signatures and docstrings: - def __init__(self, device=None, classification=False, threshold=0.9): ``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float...
ab03ae68053b727cb8907e08c35f265531d1cb3a
<|skeleton|> class ObjectDetector: """interface to Image Captioner""" def __init__(self, device=None, classification=False, threshold=0.9): """``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float): threshold for object detection classification(bool): I...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectDetector: """interface to Image Captioner""" def __init__(self, device=None, classification=False, threshold=0.9): """``` Object detection constructor Args: device(str): device to use (e.g., 'cuda', 'cpu') threshold(float): threshold for object detection classification(bool): If True, simpy...
the_stack_v2_python_sparse
ktrain/vision/object_detection/core.py
amaiya/ktrain
train
1,217
61ef53556a3fcabccfac5e7dc17a7ae67eba5a74
[ "self.gameobject = gameobject\nself.sprite = sprite\nself.source_rect = source_rect\nself.color = color\nself.sorting_order = sorting_order\nself.enabled = True", "renderer_copy = SpriteRenderer(gameobject, self.sprite, self.source_rect, self.color, self.sorting_order)\nrenderer_copy.enabled = self.enabled\nretur...
<|body_start_0|> self.gameobject = gameobject self.sprite = sprite self.source_rect = source_rect self.color = color self.sorting_order = sorting_order self.enabled = True <|end_body_0|> <|body_start_1|> renderer_copy = SpriteRenderer(gameobject, self.sprite, sel...
for rendering a sprite
SpriteRenderer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpriteRenderer: """for rendering a sprite""" def __init__(self, gameobject, sprite=None, source_rect=None, color=None, sorting_order=0): """:param gameobject (GameObject): the game object this SpriteRenderer is attached to :param sprite (Surface): the sprite to render :param source_r...
stack_v2_sparse_classes_36k_train_031461
1,284
no_license
[ { "docstring": ":param gameobject (GameObject): the game object this SpriteRenderer is attached to :param sprite (Surface): the sprite to render :param source_rect (Rectangle): represents a smaller portion of the sprite to draw :param color (tuple[int,int,int,int]): rendering color for the sprite (R, G, B, A), ...
2
stack_v2_sparse_classes_30k_train_015848
Implement the Python class `SpriteRenderer` described below. Class description: for rendering a sprite Method signatures and docstrings: - def __init__(self, gameobject, sprite=None, source_rect=None, color=None, sorting_order=0): :param gameobject (GameObject): the game object this SpriteRenderer is attached to :par...
Implement the Python class `SpriteRenderer` described below. Class description: for rendering a sprite Method signatures and docstrings: - def __init__(self, gameobject, sprite=None, source_rect=None, color=None, sorting_order=0): :param gameobject (GameObject): the game object this SpriteRenderer is attached to :par...
cb9965fc0706b530b6fb6b1e2d4d230afeea15eb
<|skeleton|> class SpriteRenderer: """for rendering a sprite""" def __init__(self, gameobject, sprite=None, source_rect=None, color=None, sorting_order=0): """:param gameobject (GameObject): the game object this SpriteRenderer is attached to :param sprite (Surface): the sprite to render :param source_r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpriteRenderer: """for rendering a sprite""" def __init__(self, gameobject, sprite=None, source_rect=None, color=None, sorting_order=0): """:param gameobject (GameObject): the game object this SpriteRenderer is attached to :param sprite (Surface): the sprite to render :param source_rect (Rectangl...
the_stack_v2_python_sparse
ZombieShooter3000/framework/components/sprite_renderer.py
Abooow/ZombieShooter3000
train
0
60a8bfa46dba2751843c39ddb6b0856a402f1309
[ "result = python_print(3)\nself.assertEquals(result, '123')\nreturn", "result = python_print(5)\nself.assertEquals(result, '12345')\nreturn" ]
<|body_start_0|> result = python_print(3) self.assertEquals(result, '123') return <|end_body_0|> <|body_start_1|> result = python_print(5) self.assertEquals(result, '12345') return <|end_body_1|>
Description
TestPythonPrint
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPythonPrint: """Description""" def test_hackerrank_sample1(self): """Verify provided test case.""" <|body_0|> def test_hackerrank_sample2(self): """Verify provided test case.""" <|body_1|> <|end_skeleton|> <|body_start_0|> result = python_pr...
stack_v2_sparse_classes_36k_train_031462
570
no_license
[ { "docstring": "Verify provided test case.", "name": "test_hackerrank_sample1", "signature": "def test_hackerrank_sample1(self)" }, { "docstring": "Verify provided test case.", "name": "test_hackerrank_sample2", "signature": "def test_hackerrank_sample2(self)" } ]
2
stack_v2_sparse_classes_30k_train_002872
Implement the Python class `TestPythonPrint` described below. Class description: Description Method signatures and docstrings: - def test_hackerrank_sample1(self): Verify provided test case. - def test_hackerrank_sample2(self): Verify provided test case.
Implement the Python class `TestPythonPrint` described below. Class description: Description Method signatures and docstrings: - def test_hackerrank_sample1(self): Verify provided test case. - def test_hackerrank_sample2(self): Verify provided test case. <|skeleton|> class TestPythonPrint: """Description""" ...
fcf3755b62fe0644af763875e3a00be962941a6d
<|skeleton|> class TestPythonPrint: """Description""" def test_hackerrank_sample1(self): """Verify provided test case.""" <|body_0|> def test_hackerrank_sample2(self): """Verify provided test case.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPythonPrint: """Description""" def test_hackerrank_sample1(self): """Verify provided test case.""" result = python_print(3) self.assertEquals(result, '123') return def test_hackerrank_sample2(self): """Verify provided test case.""" result = python_...
the_stack_v2_python_sparse
python3/python_print/test_python_print.py
ayazhemani/hackerrank-py
train
0
8ae9010ac3fc98367e175f54e67e78f5dfefb844
[ "cmd = 'fleetrun dist_fleet_utils_hdfs_client.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, err = pro.communicate()\nprint(out)\npro.wait()\npro.returncode == 0", "cmd = 'fleetrun dist_fleet_utils_localfs.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subp...
<|body_start_0|> cmd = 'fleetrun dist_fleet_utils_hdfs_client.py' pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = pro.communicate() print(out) pro.wait() pro.returncode == 0 <|end_body_0|> <|body_start_1|> cmd = ...
TestFleetUtilsAfsApi
TestFleetUtilsAfsApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFleetUtilsAfsApi: """TestFleetUtilsAfsApi""" def test_dist_fleet_utils_hdfs_client(self): """test_dist_fleet_worker""" <|body_0|> def test_dist_fleet_utils_local_client(self): """test_dist_fleet_utils_local_client""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_031463
1,472
no_license
[ { "docstring": "test_dist_fleet_worker", "name": "test_dist_fleet_utils_hdfs_client", "signature": "def test_dist_fleet_utils_hdfs_client(self)" }, { "docstring": "test_dist_fleet_utils_local_client", "name": "test_dist_fleet_utils_local_client", "signature": "def test_dist_fleet_utils_l...
2
null
Implement the Python class `TestFleetUtilsAfsApi` described below. Class description: TestFleetUtilsAfsApi Method signatures and docstrings: - def test_dist_fleet_utils_hdfs_client(self): test_dist_fleet_worker - def test_dist_fleet_utils_local_client(self): test_dist_fleet_utils_local_client
Implement the Python class `TestFleetUtilsAfsApi` described below. Class description: TestFleetUtilsAfsApi Method signatures and docstrings: - def test_dist_fleet_utils_hdfs_client(self): test_dist_fleet_worker - def test_dist_fleet_utils_local_client(self): test_dist_fleet_utils_local_client <|skeleton|> class Test...
e3562ab40b574f06bba68df6895a055fa31a085d
<|skeleton|> class TestFleetUtilsAfsApi: """TestFleetUtilsAfsApi""" def test_dist_fleet_utils_hdfs_client(self): """test_dist_fleet_worker""" <|body_0|> def test_dist_fleet_utils_local_client(self): """test_dist_fleet_utils_local_client""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestFleetUtilsAfsApi: """TestFleetUtilsAfsApi""" def test_dist_fleet_utils_hdfs_client(self): """test_dist_fleet_worker""" cmd = 'fleetrun dist_fleet_utils_hdfs_client.py' pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = pr...
the_stack_v2_python_sparse
dist_cts/dist_fleet_2.0/test_dist_fleet_utils_cloud_client.py
gentelyang/scripts
train
0
43d0f992408395adb93aadf0f0a5adbe7cead484
[ "if not self._sock:\n self.connect()\ntry:\n self._sock.sendall(command)\nexcept OSError as e:\n self.disconnect()\n if len(e.args) == 1:\n _errno, errmsg = ('UNKNOWN', e.args[0])\n else:\n _errno, errmsg = e.args\n raise ConnectionError(f'Error {_errno} while writing to socket. {err...
<|body_start_0|> if not self._sock: self.connect() try: self._sock.sendall(command) except OSError as e: self.disconnect() if len(e.args) == 1: _errno, errmsg = ('UNKNOWN', e.args[0]) else: _errno, errmsg...
StringJoiningConnection
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StringJoiningConnection: def send_packed_command(self, command, check_health=True): """Send an already packed command to the Redis server""" <|body_0|> def pack_command(self, *args): """Pack a series of arguments into a value Redis command""" <|body_1|> <|en...
stack_v2_sparse_classes_36k_train_031464
3,274
permissive
[ { "docstring": "Send an already packed command to the Redis server", "name": "send_packed_command", "signature": "def send_packed_command(self, command, check_health=True)" }, { "docstring": "Pack a series of arguments into a value Redis command", "name": "pack_command", "signature": "de...
2
null
Implement the Python class `StringJoiningConnection` described below. Class description: Implement the StringJoiningConnection class. Method signatures and docstrings: - def send_packed_command(self, command, check_health=True): Send an already packed command to the Redis server - def pack_command(self, *args): Pack ...
Implement the Python class `StringJoiningConnection` described below. Class description: Implement the StringJoiningConnection class. Method signatures and docstrings: - def send_packed_command(self, command, check_health=True): Send an already packed command to the Redis server - def pack_command(self, *args): Pack ...
e3de026a90ef2cc35a5b68934029a0ef2a5b2f53
<|skeleton|> class StringJoiningConnection: def send_packed_command(self, command, check_health=True): """Send an already packed command to the Redis server""" <|body_0|> def pack_command(self, *args): """Pack a series of arguments into a value Redis command""" <|body_1|> <|en...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StringJoiningConnection: def send_packed_command(self, command, check_health=True): """Send an already packed command to the Redis server""" if not self._sock: self.connect() try: self._sock.sendall(command) except OSError as e: self.disconne...
the_stack_v2_python_sparse
benchmarks/command_packer_benchmark.py
redis/redis-py
train
2,213
7469af7d48bf85b20aebec38b9b2320805635641
[ "conn, cursor = get_db_cursor()\nbuild = 'toy_build'\ndatabase = 'scratch/toy.db'\nrun_info = talon.init_run_info(database, build, tmp_dir='scratch/tmp/')\ninit_refs.make_temp_novel_gene_table(cursor, 'toy_build')\nlocation_dict = init_refs.make_location_dict(build, cursor)\nrun_info = talon.init_run_info(database,...
<|body_start_0|> conn, cursor = get_db_cursor() build = 'toy_build' database = 'scratch/toy.db' run_info = talon.init_run_info(database, build, tmp_dir='scratch/tmp/') init_refs.make_temp_novel_gene_table(cursor, 'toy_build') location_dict = init_refs.make_location_dict(b...
TestSearchForOverlapWithGene
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSearchForOverlapWithGene: def test_no_match(self): """Example where the supplied interval should not match anything""" <|body_0|> def test_single_match(self): """Example where the interval overlaps exactly one gene""" <|body_1|> def test_same_strand_...
stack_v2_sparse_classes_36k_train_031465
6,949
permissive
[ { "docstring": "Example where the supplied interval should not match anything", "name": "test_no_match", "signature": "def test_no_match(self)" }, { "docstring": "Example where the interval overlaps exactly one gene", "name": "test_single_match", "signature": "def test_single_match(self)...
6
null
Implement the Python class `TestSearchForOverlapWithGene` described below. Class description: Implement the TestSearchForOverlapWithGene class. Method signatures and docstrings: - def test_no_match(self): Example where the supplied interval should not match anything - def test_single_match(self): Example where the in...
Implement the Python class `TestSearchForOverlapWithGene` described below. Class description: Implement the TestSearchForOverlapWithGene class. Method signatures and docstrings: - def test_no_match(self): Example where the supplied interval should not match anything - def test_single_match(self): Example where the in...
8014faed5f982e5e106ec05239e47d65878e76c3
<|skeleton|> class TestSearchForOverlapWithGene: def test_no_match(self): """Example where the supplied interval should not match anything""" <|body_0|> def test_single_match(self): """Example where the interval overlaps exactly one gene""" <|body_1|> def test_same_strand_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSearchForOverlapWithGene: def test_no_match(self): """Example where the supplied interval should not match anything""" conn, cursor = get_db_cursor() build = 'toy_build' database = 'scratch/toy.db' run_info = talon.init_run_info(database, build, tmp_dir='scratch/tmp...
the_stack_v2_python_sparse
testing_suite/test_search_for_overlap_with_gene.py
kopardev/TALON
train
0
102c0c9462d00620fa1a76adfa584906e581862c
[ "self.t_value = t_value\nself.features = features\nself.attributes = attributes\nself.size = size\nself.forest = []", "counter = 1\ntoolbar_width = 100\nfactor = int(self.t_value / toolbar_width)\nfactor = max(factor, 1)\nif print_status_bar:\n print('Building Bagging Trees')\n sys.stdout.write('Progress: [...
<|body_start_0|> self.t_value = t_value self.features = features self.attributes = attributes self.size = size self.forest = [] <|end_body_0|> <|body_start_1|> counter = 1 toolbar_width = 100 factor = int(self.t_value / toolbar_width) factor = max...
RandomForests class for binary labeled features (-1, 1)
RandomForests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomForests: """RandomForests class for binary labeled features (-1, 1)""" def __init__(self, features, attributes, t_value, size): """RandomForests constructor :param features: ordered features from dataset :type features: python list containing Feature objects :param attributes: ...
stack_v2_sparse_classes_36k_train_031466
2,913
no_license
[ { "docstring": "RandomForests constructor :param features: ordered features from dataset :type features: python list containing Feature objects :param attributes: attributes for current fit iteration :type attributes: python tuple containing Attribute objects :param t_value: number of decision trees in forest :...
3
stack_v2_sparse_classes_30k_train_018722
Implement the Python class `RandomForests` described below. Class description: RandomForests class for binary labeled features (-1, 1) Method signatures and docstrings: - def __init__(self, features, attributes, t_value, size): RandomForests constructor :param features: ordered features from dataset :type features: p...
Implement the Python class `RandomForests` described below. Class description: RandomForests class for binary labeled features (-1, 1) Method signatures and docstrings: - def __init__(self, features, attributes, t_value, size): RandomForests constructor :param features: ordered features from dataset :type features: p...
782cfaaac95f666e8e3272dbcd42701a7d84200c
<|skeleton|> class RandomForests: """RandomForests class for binary labeled features (-1, 1)""" def __init__(self, features, attributes, t_value, size): """RandomForests constructor :param features: ordered features from dataset :type features: python list containing Feature objects :param attributes: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomForests: """RandomForests class for binary labeled features (-1, 1)""" def __init__(self, features, attributes, t_value, size): """RandomForests constructor :param features: ordered features from dataset :type features: python list containing Feature objects :param attributes: attributes fo...
the_stack_v2_python_sparse
EnsembleLearning/RandomForests.py
morsgiathatch/machine_learning
train
0
cb9c4fffe6471fba18c054f8043656055b34d354
[ "virtual_data_source = husky_model.data_sources[0]\nidentifiers = [remove_virtual_data_source_prefix(virtual_data_source, taxon_slug) for taxon_slug, attr in husky_model.attributes.items() if attr.identifier]\nattrs_by_key: Dict[str, List[ModelAttribute]] = defaultdict(list)\nfor attr in husky_model.attributes.valu...
<|body_start_0|> virtual_data_source = husky_model.data_sources[0] identifiers = [remove_virtual_data_source_prefix(virtual_data_source, taxon_slug) for taxon_slug, attr in husky_model.attributes.items() if attr.identifier] attrs_by_key: Dict[str, List[ModelAttribute]] = defaultdict(list) ...
Mapper helper class for FdqModel
FdqModelMapper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FdqModelMapper: """Mapper helper class for FdqModel""" def from_internal(cls, husky_model: HuskyModel) -> FdqModel: """Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel""" <|body_0|> def to_internal(cls, model: FdqModel, v...
stack_v2_sparse_classes_36k_train_031467
5,962
permissive
[ { "docstring": "Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel", "name": "from_internal", "signature": "def from_internal(cls, husky_model: HuskyModel) -> FdqModel" }, { "docstring": "Creates HuskyModel from FdqModel :return: Correct HuskyModel...
2
stack_v2_sparse_classes_30k_train_003581
Implement the Python class `FdqModelMapper` described below. Class description: Mapper helper class for FdqModel Method signatures and docstrings: - def from_internal(cls, husky_model: HuskyModel) -> FdqModel: Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel - def to_...
Implement the Python class `FdqModelMapper` described below. Class description: Mapper helper class for FdqModel Method signatures and docstrings: - def from_internal(cls, husky_model: HuskyModel) -> FdqModel: Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel - def to_...
210f037280793d5cb3b6d9d3e7ba3e22ca9b8bbc
<|skeleton|> class FdqModelMapper: """Mapper helper class for FdqModel""" def from_internal(cls, husky_model: HuskyModel) -> FdqModel: """Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel""" <|body_0|> def to_internal(cls, model: FdqModel, v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FdqModelMapper: """Mapper helper class for FdqModel""" def from_internal(cls, husky_model: HuskyModel) -> FdqModel: """Creates ApiModel from HuskyModel :param husky_model: Original HuskyModel :return: Correct FdqModel""" virtual_data_source = husky_model.data_sources[0] identifier...
the_stack_v2_python_sparse
src/panoramic/cli/husky/core/federated/model/mappers.py
panoramichq/panoramic-cli
train
5
8aefaba9b382d84fe30da2e717b8ae922bd23c4f
[ "self.promoted_at = APIHelper.UnixDateTime(promoted_at) if promoted_at else None\nself.assistant = assistant\nself.additional_properties = additional_properties\nsuper(Boss, self).__init__(address, age, birthday, birthtime, department, dependents, hired_at, joining_day, name, salary, uid, working_days, boss, person...
<|body_start_0|> self.promoted_at = APIHelper.UnixDateTime(promoted_at) if promoted_at else None self.assistant = assistant self.additional_properties = additional_properties super(Boss, self).__init__(address, age, birthday, birthtime, department, dependents, hired_at, joining_day, name...
Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here.
Boss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Boss: """Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here.""" def __init__(self, address=None, age=None, birthday=None,...
stack_v2_sparse_classes_36k_train_031468
13,843
permissive
[ { "docstring": "Constructor for the Boss class", "name": "__init__", "signature": "def __init__(self, address=None, age=None, birthday=None, birthtime=None, department=None, dependents=None, hired_at=None, joining_day='Monday', name=None, promoted_at=None, salary=None, uid=None, working_days=None, assis...
2
stack_v2_sparse_classes_30k_train_001906
Implement the Python class `Boss` described below. Class description: Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here. Method signatures and doc...
Implement the Python class `Boss` described below. Class description: Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here. Method signatures and doc...
49acc3d416a1dde7ea43b178d070484baf1b7f2b
<|skeleton|> class Boss: """Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here.""" def __init__(self, address=None, age=None, birthday=None,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Boss: """Implementation of the 'Boss' model. Testing circular reference. NOTE: This class inherits from 'Employee'. Attributes: promoted_at (datetime): TODO: type description here. assistant (Employee): TODO: type description here.""" def __init__(self, address=None, age=None, birthday=None, birthtime=No...
the_stack_v2_python_sparse
PYTHON_GENERIC_LIB/tester/models/person.py
MaryamAdnan3/Tester1
train
0
04068c2d9595b5d1c89d03ba9180d31767ccb468
[ "if CQRSSerializerMeta._register[type(obj)] == type(self):\n return super(CQRSPolymorphicSerializer, self).to_native(obj)\nreturn CQRSSerializerMeta._register.instances[type(obj)].to_native(obj)", "if polymorphism_resolved:\n out = super(CQRSPolymorphicSerializer, self).from_native(data, files)\n return ...
<|body_start_0|> if CQRSSerializerMeta._register[type(obj)] == type(self): return super(CQRSPolymorphicSerializer, self).to_native(obj) return CQRSSerializerMeta._register.instances[type(obj)].to_native(obj) <|end_body_0|> <|body_start_1|> if polymorphism_resolved: out =...
Serializer for Polymorphic Model
CQRSPolymorphicSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CQRSPolymorphicSerializer: """Serializer for Polymorphic Model""" def to_native(self, obj): """Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with""" <|body_0|> def from_native(self, data, files=None, polymorphism_re...
stack_v2_sparse_classes_36k_train_031469
13,334
no_license
[ { "docstring": "Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with", "name": "to_native", "signature": "def to_native(self, obj)" }, { "docstring": "Deserialize primitives -> polymorphic objects.", "name": "from_native", "signature"...
2
stack_v2_sparse_classes_30k_train_020055
Implement the Python class `CQRSPolymorphicSerializer` described below. Class description: Serializer for Polymorphic Model Method signatures and docstrings: - def to_native(self, obj): Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with - def from_native(self, d...
Implement the Python class `CQRSPolymorphicSerializer` described below. Class description: Serializer for Polymorphic Model Method signatures and docstrings: - def to_native(self, obj): Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with - def from_native(self, d...
72dfb45220000bed3b506885c0196bc2e4540836
<|skeleton|> class CQRSPolymorphicSerializer: """Serializer for Polymorphic Model""" def to_native(self, obj): """Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with""" <|body_0|> def from_native(self, data, files=None, polymorphism_re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CQRSPolymorphicSerializer: """Serializer for Polymorphic Model""" def to_native(self, obj): """Because OfferAspect is Polymorphic and don't know ahead of time which downcast model we'll be dealing with""" if CQRSSerializerMeta._register[type(obj)] == type(self): return super(C...
the_stack_v2_python_sparse
cqrs/serializers.py
xyicheng/cqrs
train
0
966616ede278f5c58b8ce4d04f3bb69a4863f93f
[ "super(PyramidRepresentation, self).__init__()\nself.r_dim = k = r_dim\nself.conv1 = nn.Conv2d(n_channels + v_dim, k // 8, kernel_size=2, stride=2)\nself.conv2 = nn.Conv2d(k // 8, k // 4, kernel_size=2, stride=2)\nself.conv3 = nn.Conv2d(k // 4, k // 2, kernel_size=2, stride=2)\nself.conv4 = nn.Conv2d(k // 2, k, ker...
<|body_start_0|> super(PyramidRepresentation, self).__init__() self.r_dim = k = r_dim self.conv1 = nn.Conv2d(n_channels + v_dim, k // 8, kernel_size=2, stride=2) self.conv2 = nn.Conv2d(k // 8, k // 4, kernel_size=2, stride=2) self.conv3 = nn.Conv2d(k // 4, k // 2, kernel_size=2, ...
PyramidRepresentation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyramidRepresentation: def __init__(self, n_channels, v_dim, r_dim=256): """Network that generates a condensed representation vector from a joint input of image and viewpoint. Employs the pyramid architecture described in the paper. :param n_channels: number of color channels in input im...
stack_v2_sparse_classes_36k_train_031470
3,901
permissive
[ { "docstring": "Network that generates a condensed representation vector from a joint input of image and viewpoint. Employs the pyramid architecture described in the paper. :param n_channels: number of color channels in input image :param v_dim: dimensions of the viewpoint vector :param r_dim: dimensions of rep...
2
stack_v2_sparse_classes_30k_train_006850
Implement the Python class `PyramidRepresentation` described below. Class description: Implement the PyramidRepresentation class. Method signatures and docstrings: - def __init__(self, n_channels, v_dim, r_dim=256): Network that generates a condensed representation vector from a joint input of image and viewpoint. Em...
Implement the Python class `PyramidRepresentation` described below. Class description: Implement the PyramidRepresentation class. Method signatures and docstrings: - def __init__(self, n_channels, v_dim, r_dim=256): Network that generates a condensed representation vector from a joint input of image and viewpoint. Em...
80440bee09951d24d739866b85dfa64cbdad2258
<|skeleton|> class PyramidRepresentation: def __init__(self, n_channels, v_dim, r_dim=256): """Network that generates a condensed representation vector from a joint input of image and viewpoint. Employs the pyramid architecture described in the paper. :param n_channels: number of color channels in input im...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PyramidRepresentation: def __init__(self, n_channels, v_dim, r_dim=256): """Network that generates a condensed representation vector from a joint input of image and viewpoint. Employs the pyramid architecture described in the paper. :param n_channels: number of color channels in input image :param v_d...
the_stack_v2_python_sparse
gqn-wohlert/gqn/representation.py
yueqiw/gqn-world-model
train
6
a03bdf575a73715aebd16ea6e1c5366028e38e09
[ "RelModelBase.__init__(self, classes, rel_classes, mode, num_gpus, require_overlap_det)\nassert depth_model in DEPTH_MODELS\nself.depth_model = depth_model\nself.pretrained_depth = pretrained_depth\nself.depth_pooling_dim = DEPTH_DIMS[self.depth_model]\nself.pooling_size = 7\nself.detector = nn.Module()\nself.depth...
<|body_start_0|> RelModelBase.__init__(self, classes, rel_classes, mode, num_gpus, require_overlap_det) assert depth_model in DEPTH_MODELS self.depth_model = depth_model self.pretrained_depth = pretrained_depth self.depth_pooling_dim = DEPTH_DIMS[self.depth_model] self.po...
Depth relation detection model
RelModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelModel: """Depth relation detection model""" def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): """:param classes: object classes :param rel_classes: relationship classes. None if were no...
stack_v2_sparse_classes_36k_train_031471
6,730
permissive
[ { "docstring": ":param classes: object classes :param rel_classes: relationship classes. None if were not using rel mode :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param require_overlap_det: whether two objects must intersect :param depth_model: provided architecture for depth...
3
stack_v2_sparse_classes_30k_val_001111
Implement the Python class `RelModel` described below. Class description: Depth relation detection model Method signatures and docstrings: - def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): :param classes: object classes ...
Implement the Python class `RelModel` described below. Class description: Depth relation detection model Method signatures and docstrings: - def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): :param classes: object classes ...
39fb0d493f44ac2daf4bbc8569a1c74e8828da5f
<|skeleton|> class RelModel: """Depth relation detection model""" def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): """:param classes: object classes :param rel_classes: relationship classes. None if were no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelModel: """Depth relation detection model""" def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): """:param classes: object classes :param rel_classes: relationship classes. None if were not using rel m...
the_stack_v2_python_sparse
lib/shz_models/rel_model_depth.py
sharifza/Depth-VRD
train
1
c02f37436a99f11fd5cb7ef52ce60f6d97445224
[ "if config is None:\n config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher])\nsuper().__init__(config)\nself._beam_orchestrator_args = beam_orchestrator_args", "tfx_pipeline.pipeline_info....
<|body_start_0|> if config is None: config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher]) super().__init__(config) self._beam_orchestrator_args = beam_orchestra...
Tfx runner on Beam.
BeamDagRunner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BeamDagRunner: """Tfx runner on Beam.""" def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): """Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator....
stack_v2_sparse_classes_36k_train_031472
6,857
permissive
[ { "docstring": "Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that this is different from the beam_pipeline_args within additional_pipeline_args, which is for beam pipelines in components. config: Optional pipeline config for customizing...
2
stack_v2_sparse_classes_30k_train_006876
Implement the Python class `BeamDagRunner` described below. Class description: Tfx runner on Beam. Method signatures and docstrings: - def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): Initializes BeamDagRunner as a TFX orchestrator. Args: bea...
Implement the Python class `BeamDagRunner` described below. Class description: Tfx runner on Beam. Method signatures and docstrings: - def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): Initializes BeamDagRunner as a TFX orchestrator. Args: bea...
1b328504fa08a70388691e4072df76f143631325
<|skeleton|> class BeamDagRunner: """Tfx runner on Beam.""" def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): """Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BeamDagRunner: """Tfx runner on Beam.""" def __init__(self, beam_orchestrator_args: Optional[List[str]]=None, config: Optional[pipeline_config.PipelineConfig]=None): """Initializes BeamDagRunner as a TFX orchestrator. Args: beam_orchestrator_args: beam args for the beam orchestrator. Note that th...
the_stack_v2_python_sparse
tfx/orchestration/beam/legacy/beam_dag_runner.py
tensorflow/tfx
train
2,116
43c22824a723ec4640cdfa82cb61ec9d795b9b0d
[ "self.logger = utils.get_logger()\nconstants = models.get_asset_dicts('preferences')\nfor key, value in constants.items():\n setattr(self, key, value)", "for option, option_dict in self.OPTIONS.items():\n option_dict['handle'] = option\n for key, value in self.DEFAULTS.items():\n if option_dict.ge...
<|body_start_0|> self.logger = utils.get_logger() constants = models.get_asset_dicts('preferences') for key, value in constants.items(): setattr(self, key, value) <|end_body_0|> <|body_start_1|> for option, option_dict in self.OPTIONS.items(): option_dict['handle...
Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, preferences are 'assets' similar to how we'...
Preferences
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Preferences: """Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, pref...
stack_v2_sparse_classes_36k_train_031473
9,041
permissive
[ { "docstring": "Initialize a logger and set the constants, which are just the dictionaries from the assets/preferences.py module.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Returns a representation of the prefrences object. Returns as JSON by default; set 'return_...
2
stack_v2_sparse_classes_30k_train_017191
Implement the Python class `Preferences` described below. Class description: Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefren...
Implement the Python class `Preferences` described below. Class description: Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefren...
38fb75a830b365e6e640e64c816501f79e0da8b4
<|skeleton|> class Preferences: """Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, pref...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Preferences: """Preferences for the webapp are an object: this makes them easier to work with in routes.py, etc. since we can sweep more of the business logic under the rug of methods here, etc. Below, you'll see us setting some constants from assets/prefrence.py. In this version of the app, preferences are '...
the_stack_v2_python_sparse
v4/app/models/users.py
toconnell/kdm-manager
train
27
4a353e5a895b5708df36aca291741f035b982346
[ "expected = [2.7]\nactual = helpers.convert_to_1d_tensor(2.7)\nwith self.session() as session:\n self.assertAllClose(expected, session.run(actual), rtol=0, atol=1e-06)\nexpected = [-6.3, 1.0, 5.1]\nactual = helpers.convert_to_1d_tensor(expected)\nwith self.session() as session:\n self.assertAllClose(expected,...
<|body_start_0|> expected = [2.7] actual = helpers.convert_to_1d_tensor(2.7) with self.session() as session: self.assertAllClose(expected, session.run(actual), rtol=0, atol=1e-06) expected = [-6.3, 1.0, 5.1] actual = helpers.convert_to_1d_tensor(expected) with...
Tests for helper functions in helpers.py.
HelpersTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HelpersTest: """Tests for helper functions in helpers.py.""" def test_convert_to_1d_tensor(self): """Tests the "convert_to_1d_tensor" function.""" <|body_0|> def test_get_num_columns_of_2d_tensor(self): """Tests the "get_num_columns_of_2d_tensor" function.""" ...
stack_v2_sparse_classes_36k_train_031474
4,464
permissive
[ { "docstring": "Tests the \"convert_to_1d_tensor\" function.", "name": "test_convert_to_1d_tensor", "signature": "def test_convert_to_1d_tensor(self)" }, { "docstring": "Tests the \"get_num_columns_of_2d_tensor\" function.", "name": "test_get_num_columns_of_2d_tensor", "signature": "def ...
3
stack_v2_sparse_classes_30k_train_013558
Implement the Python class `HelpersTest` described below. Class description: Tests for helper functions in helpers.py. Method signatures and docstrings: - def test_convert_to_1d_tensor(self): Tests the "convert_to_1d_tensor" function. - def test_get_num_columns_of_2d_tensor(self): Tests the "get_num_columns_of_2d_ten...
Implement the Python class `HelpersTest` described below. Class description: Tests for helper functions in helpers.py. Method signatures and docstrings: - def test_convert_to_1d_tensor(self): Tests the "convert_to_1d_tensor" function. - def test_get_num_columns_of_2d_tensor(self): Tests the "get_num_columns_of_2d_ten...
46b34d1c2d6ec05ea1e46db3bcc481a81e041637
<|skeleton|> class HelpersTest: """Tests for helper functions in helpers.py.""" def test_convert_to_1d_tensor(self): """Tests the "convert_to_1d_tensor" function.""" <|body_0|> def test_get_num_columns_of_2d_tensor(self): """Tests the "get_num_columns_of_2d_tensor" function.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HelpersTest: """Tests for helper functions in helpers.py.""" def test_convert_to_1d_tensor(self): """Tests the "convert_to_1d_tensor" function.""" expected = [2.7] actual = helpers.convert_to_1d_tensor(2.7) with self.session() as session: self.assertAllClose(ex...
the_stack_v2_python_sparse
tensorflow_constrained_optimization/python/rates/helpers_test.py
neelguha/tensorflow_constrained_optimization
train
0
925b63ecc6c5a472e38a2bba152be26ee0caedc8
[ "urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nssl._create_default_https_context = ssl._create_unverified_context\nself.GRPCport = 443\nself.SSLport = 443\nself.connect_timeout = 10\nself.headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}\nself.session = requests.Ses...
<|body_start_0|> urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ssl._create_default_https_context = ssl._create_unverified_context self.GRPCport = 443 self.SSLport = 443 self.connect_timeout = 10 self.headers = {'Accept': 'application/json', 'Content-...
CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements
grpcServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class grpcServer: """CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements""" def __init__(self, serverAddr, username, password) -> None: """Create a GRPC connection Log in to CloudVision retrieve session token and SSL certicifcate then create a GRPC se...
stack_v2_sparse_classes_36k_train_031475
5,417
permissive
[ { "docstring": "Create a GRPC connection Log in to CloudVision retrieve session token and SSL certicifcate then create a GRPC session", "name": "__init__", "signature": "def __init__(self, serverAddr, username, password) -> None" }, { "docstring": "Generic fetch for retrieving path data Requires...
4
stack_v2_sparse_classes_30k_train_017270
Implement the Python class `grpcServer` described below. Class description: CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements Method signatures and docstrings: - def __init__(self, serverAddr, username, password) -> None: Create a GRPC connection Log in to CloudVision retrieve...
Implement the Python class `grpcServer` described below. Class description: CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements Method signatures and docstrings: - def __init__(self, serverAddr, username, password) -> None: Create a GRPC connection Log in to CloudVision retrieve...
d93b5f66a00b1e3710257d607d62f9d43736304e
<|skeleton|> class grpcServer: """CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements""" def __init__(self, serverAddr, username, password) -> None: """Create a GRPC connection Log in to CloudVision retrieve session token and SSL certicifcate then create a GRPC se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class grpcServer: """CloudVision Connector Class Creates a GRPC connection to CloudVision Returns Path elements""" def __init__(self, serverAddr, username, password) -> None: """Create a GRPC connection Log in to CloudVision retrieve session token and SSL certicifcate then create a GRPC session""" ...
the_stack_v2_python_sparse
CVP_API/Metrics_Export/metrics_parser.py
Hugh-Adams/Example_Scripts
train
4
e6f8ac34325609104fbb11aaa3666340484bb487
[ "list_tags = []\nfor tag in tags:\n if TagRepository().check_tag_exist(tag.name):\n tag = TagRepository().get_tag_by_name(tag.name)\n tag = TagRepository().obj(tag)\n list_tags.append(tag)\n else:\n list_tags.append(CreateTag.run(tag))\nreturn list_tags", "list_tags = cls.generat...
<|body_start_0|> list_tags = [] for tag in tags: if TagRepository().check_tag_exist(tag.name): tag = TagRepository().get_tag_by_name(tag.name) tag = TagRepository().obj(tag) list_tags.append(tag) else: list_tags.appe...
CreateCard
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCard: def generate_list_tags(cls, tags) -> List[Tag]: """Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag.""" <|body_0|> def run(cls, data: CreateCardInterface) -> Card: """Prepara os dados par...
stack_v2_sparse_classes_36k_train_031476
1,434
no_license
[ { "docstring": "Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag.", "name": "generate_list_tags", "signature": "def generate_list_tags(cls, tags) -> List[Tag]" }, { "docstring": "Prepara os dados para o formato permitido e então...
2
stack_v2_sparse_classes_30k_train_010787
Implement the Python class `CreateCard` described below. Class description: Implement the CreateCard class. Method signatures and docstrings: - def generate_list_tags(cls, tags) -> List[Tag]: Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag. - def ru...
Implement the Python class `CreateCard` described below. Class description: Implement the CreateCard class. Method signatures and docstrings: - def generate_list_tags(cls, tags) -> List[Tag]: Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag. - def ru...
fb47a578f229f78473657342e7b49957ae5d2d0b
<|skeleton|> class CreateCard: def generate_list_tags(cls, tags) -> List[Tag]: """Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag.""" <|body_0|> def run(cls, data: CreateCardInterface) -> Card: """Prepara os dados par...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateCard: def generate_list_tags(cls, tags) -> List[Tag]: """Percorre todas a lista de tags, verifica se existe caso exista obtém essa tag do database caso não cria uma nova tag.""" list_tags = [] for tag in tags: if TagRepository().check_tag_exist(tag.name): ...
the_stack_v2_python_sparse
back_end/src/applications/card/create.py
Simeone-Holanda/Criador-de-cards
train
0
26c0e2bfc5816e8dc0bd21e658a6b0adca637d41
[ "self.acquisition_optimizer = acquisition_optimizer\nself.model = model\nself.parameter_space = parameter_space\nself.batch_size = batch_size\nself.sequential_acquisition_generator = sequential_acquisition_generator\nself.single_point_acquisition_generator = single_point_acquisition_generator", "x1, _ = self.acqu...
<|body_start_0|> self.acquisition_optimizer = acquisition_optimizer self.model = model self.parameter_space = parameter_space self.batch_size = batch_size self.sequential_acquisition_generator = sequential_acquisition_generator self.single_point_acquisition_generator = si...
Sequential point calculator. For attributes, see the ``__init__`` method.
SequentialMomentMatchingCalculator
[ "MIT", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SequentialMomentMatchingCalculator: """Sequential point calculator. For attributes, see the ``__init__`` method.""" def __init__(self, acquisition_optimizer: AcquisitionOptimizerBase, model: GPyModelWrapper, parameter_space: ParameterSpace, batch_size: int, sequential_acquisition_generator: ...
stack_v2_sparse_classes_36k_train_031477
9,291
permissive
[ { "docstring": "Args: acquisition_optimizer: AcquisitionOptimizer object to optimize the penalized acquisition model: Model object, used to compute the parameters of the local penalization parameter_space: Parameter space describing input domain batch_size: Number of points to collect in each batch sequential_a...
2
null
Implement the Python class `SequentialMomentMatchingCalculator` described below. Class description: Sequential point calculator. For attributes, see the ``__init__`` method. Method signatures and docstrings: - def __init__(self, acquisition_optimizer: AcquisitionOptimizerBase, model: GPyModelWrapper, parameter_space:...
Implement the Python class `SequentialMomentMatchingCalculator` described below. Class description: Sequential point calculator. For attributes, see the ``__init__`` method. Method signatures and docstrings: - def __init__(self, acquisition_optimizer: AcquisitionOptimizerBase, model: GPyModelWrapper, parameter_space:...
40bab526af6562653c42dbb32b174524c44ce2ba
<|skeleton|> class SequentialMomentMatchingCalculator: """Sequential point calculator. For attributes, see the ``__init__`` method.""" def __init__(self, acquisition_optimizer: AcquisitionOptimizerBase, model: GPyModelWrapper, parameter_space: ParameterSpace, batch_size: int, sequential_acquisition_generator: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SequentialMomentMatchingCalculator: """Sequential point calculator. For attributes, see the ``__init__`` method.""" def __init__(self, acquisition_optimizer: AcquisitionOptimizerBase, model: GPyModelWrapper, parameter_space: ParameterSpace, batch_size: int, sequential_acquisition_generator: Type[Sequenti...
the_stack_v2_python_sparse
PyStationB/libraries/GlobalPenalisation/gp/calculators.py
mebristo/station-b-libraries
train
0
b4355d694ceab4f5fff69081caa592522f000319
[ "self.dic = {}\nfor i in dictionary:\n num = len(i) - 2\n if num > 0:\n keyi = i[0] + str(num) + i[-1]\n else:\n keyi = i\n if keyi in self.dic:\n self.dic[keyi].append(i)\n else:\n self.dic[keyi] = [i]", "if len(word) >= 2:\n keyw = word[0] + str(len(word) - 2) + wor...
<|body_start_0|> self.dic = {} for i in dictionary: num = len(i) - 2 if num > 0: keyi = i[0] + str(num) + i[-1] else: keyi = i if keyi in self.dic: self.dic[keyi].append(i) else: s...
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """check if a word is unique. :type word: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_031478
955
no_license
[ { "docstring": "initialize your data structure here. :type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": "check if a word is unique. :type word: str :rtype: bool", "name": "isUnique", "signature": "def isUnique(self, word)" ...
2
null
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str] - def isUnique(self, word): check if a word is unique. :type word: str ...
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str] - def isUnique(self, word): check if a word is unique. :type word: str ...
853a6257e17f79a816f5e877843a9409f82a8c13
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """check if a word is unique. :type word: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" self.dic = {} for i in dictionary: num = len(i) - 2 if num > 0: keyi = i[0] + str(num) + i[-1] else: ...
the_stack_v2_python_sparse
uniquewordabbreviation.py
yibeihuang/LeetCode
train
0
aba64259c04ef9ca24ede3ffc08f3d7198447729
[ "super(CustomBatchNormAutograd, self).__init__()\nself.neurons = n_neurons\nself.eps = eps\nself.gamma = nn.Parameter(torch.ones(n_neurons))\nself.beta = nn.Parameter(torch.zeros(n_neurons))", "if input.shape[1] != self.neurons:\n print('The dimension of the input is not correct!')\nMean = torch.sum(input, dim...
<|body_start_0|> super(CustomBatchNormAutograd, self).__init__() self.neurons = n_neurons self.eps = eps self.gamma = nn.Parameter(torch.ones(n_neurons)) self.beta = nn.Parameter(torch.zeros(n_neurons)) <|end_body_0|> <|body_start_1|> if input.shape[1] != self.neurons: ...
This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automatic differentiation provided by PyTorch.
CustomBatchNormAutograd
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_36k_train_031479
9,605
no_license
[ { "docstring": "Initializes CustomBatchNormAutograd object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability TODO: Save parameters for the number of neurons and eps. Initialize parameters gamma and beta via nn.Parameter", "name": "__init__", ...
2
stack_v2_sparse_classes_30k_val_001072
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
Implement the Python class `CustomBatchNormAutograd` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need...
60834eaaa1db9f8ffb683d85f6939951992c7059
<|skeleton|> class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomBatchNormAutograd: """This nn.module implements a custom version of the batch norm operation for MLPs. The operations called in self.forward track the history if the input tensors have the flag requires_grad set to True. The backward pass does not need to be implemented, it is dealt with by the automati...
the_stack_v2_python_sparse
Deep Learning/assignment_1/code/custom_batchnorm.py
mcx2576/python_project
train
1
ebdbb32710c5c0e0c3085f464d3dca6c63f8a459
[ "sums = [0] * (len(nums) + 1)\nfor i in range(len(nums)):\n sums[i + 1] = nums[i] + sums[i]\nfor i in range(len(nums) - 1):\n for j in range(i + 1, len(nums) + 1):\n if (sums[j] - sums[i]) % k == 0:\n return True\nreturn False", "modes = set()\npresum = 0\nfor num in nums:\n last = pres...
<|body_start_0|> sums = [0] * (len(nums) + 1) for i in range(len(nums)): sums[i + 1] = nums[i] + sums[i] for i in range(len(nums) - 1): for j in range(i + 1, len(nums) + 1): if (sums[j] - sums[i]) % k == 0: return True return Fa...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: """简单前缀和,超时,O(n ** 2) :param nums: :param k: :return:""" <|body_0|> def checkSubarraySum1(self, nums: List[int], k: int) -> bool: """前缀和 + 同余定理 (sums[j] - sums[i]) % k == 0 同理有 sums[i] % k == sums...
stack_v2_sparse_classes_36k_train_031480
1,948
no_license
[ { "docstring": "简单前缀和,超时,O(n ** 2) :param nums: :param k: :return:", "name": "checkSubarraySum", "signature": "def checkSubarraySum(self, nums: List[int], k: int) -> bool" }, { "docstring": "前缀和 + 同余定理 (sums[j] - sums[i]) % k == 0 同理有 sums[i] % k == sums[i] % k :param nums: :param k: :return:", ...
2
stack_v2_sparse_classes_30k_train_003998
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkSubarraySum(self, nums: List[int], k: int) -> bool: 简单前缀和,超时,O(n ** 2) :param nums: :param k: :return: - def checkSubarraySum1(self, nums: List[int], k: int) -> bool: 前缀...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkSubarraySum(self, nums: List[int], k: int) -> bool: 简单前缀和,超时,O(n ** 2) :param nums: :param k: :return: - def checkSubarraySum1(self, nums: List[int], k: int) -> bool: 前缀...
9acba92695c06406f12f997a720bfe1deb9464a8
<|skeleton|> class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: """简单前缀和,超时,O(n ** 2) :param nums: :param k: :return:""" <|body_0|> def checkSubarraySum1(self, nums: List[int], k: int) -> bool: """前缀和 + 同余定理 (sums[j] - sums[i]) % k == 0 同理有 sums[i] % k == sums...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: """简单前缀和,超时,O(n ** 2) :param nums: :param k: :return:""" sums = [0] * (len(nums) + 1) for i in range(len(nums)): sums[i + 1] = nums[i] + sums[i] for i in range(len(nums) - 1): for j i...
the_stack_v2_python_sparse
datastructure/binary_array/CheckSubarraySum.py
yinhuax/leet_code
train
0
878a24eb27ab552a816697767efb528bebb0be53
[ "true_pred = always_true()\nself.id_pred = true_pred\nself.args_pred = true_pred\nself.severity_pred = true_pred\nself.time_pred = true_pred\nif is_predicate(id_pred):\n self.id_pred = id_pred\nif is_predicate(args_pred):\n self.args_pred = args_pred\nif is_predicate(severity_pred):\n self.severity_pred = ...
<|body_start_0|> true_pred = always_true() self.id_pred = true_pred self.args_pred = true_pred self.severity_pred = true_pred self.time_pred = true_pred if is_predicate(id_pred): self.id_pred = id_pred if is_predicate(args_pred): self.args_...
event_predicate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class event_predicate: def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): """A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasse...
stack_v2_sparse_classes_36k_train_031481
19,146
permissive
[ { "docstring": "A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasses of predicate, they will be ignored. If an argument is unspecified, the predicate will ignore that field when eva...
3
stack_v2_sparse_classes_30k_train_004408
Implement the Python class `event_predicate` described below. Class description: Implement the event_predicate class. Method signatures and docstrings: - def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): A predicate for specifying an EventData object from data_types.event_data. Thi...
Implement the Python class `event_predicate` described below. Class description: Implement the event_predicate class. Method signatures and docstrings: - def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): A predicate for specifying an EventData object from data_types.event_data. Thi...
aa663303327587146390dde67b83b9bf4e916d54
<|skeleton|> class event_predicate: def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): """A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasse...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class event_predicate: def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): """A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasses of predicate...
the_stack_v2_python_sparse
Gds/src/fprime_gds/common/testing_fw/predicates.py
suriyaa/fprime
train
1
c20c6be83f59da5e5ef9e782dbb2811071cf77e0
[ "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...
The temperature service definition.
IndoorTemperaturePredictionServicer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IndoorTemperaturePredictionServicer: """The temperature service definition.""" def GetSecondOrderPrediction(self, request, context): """A simple RPC. Predicts indoor temperatures.""" <|body_0|> def GetSecondOrderError(self, request, context): """Get errors associ...
stack_v2_sparse_classes_36k_train_031482
2,633
permissive
[ { "docstring": "A simple RPC. Predicts indoor temperatures.", "name": "GetSecondOrderPrediction", "signature": "def GetSecondOrderPrediction(self, request, context)" }, { "docstring": "Get errors associated with prediction", "name": "GetSecondOrderError", "signature": "def GetSecondOrder...
2
stack_v2_sparse_classes_30k_train_015427
Implement the Python class `IndoorTemperaturePredictionServicer` described below. Class description: The temperature service definition. Method signatures and docstrings: - def GetSecondOrderPrediction(self, request, context): A simple RPC. Predicts indoor temperatures. - def GetSecondOrderError(self, request, contex...
Implement the Python class `IndoorTemperaturePredictionServicer` described below. Class description: The temperature service definition. Method signatures and docstrings: - def GetSecondOrderPrediction(self, request, context): A simple RPC. Predicts indoor temperatures. - def GetSecondOrderError(self, request, contex...
1604ae035a3bd81e87a4037326b7935d1f268452
<|skeleton|> class IndoorTemperaturePredictionServicer: """The temperature service definition.""" def GetSecondOrderPrediction(self, request, context): """A simple RPC. Predicts indoor temperatures.""" <|body_0|> def GetSecondOrderError(self, request, context): """Get errors associ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IndoorTemperaturePredictionServicer: """The temperature service definition.""" def GetSecondOrderPrediction(self, request, context): """A simple RPC. Predicts indoor temperatures.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
services/indoor_temperature_prediction/indoor_temperature_prediction_pb2_grpc.py
vishalbelsare/XBOS
train
1
e1c00c96dad9e99e39266b4c71c290e03735ad89
[ "self.l = capacity\nself.history = []\nself.map = {}", "if key not in self.map:\n return -1\nself.history.remove(key)\nself.history.append(key)\nreturn self.map[key]", "if key in self.map:\n self.history.remove(key)\n self.history.append(key)\n self.map[key] = value\nelse:\n if len(self.history) ...
<|body_start_0|> self.l = capacity self.history = [] self.map = {} <|end_body_0|> <|body_start_1|> if key not in self.map: return -1 self.history.remove(key) self.history.append(key) return self.map[key] <|end_body_1|> <|body_start_2|> if key...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_031483
870
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_009595
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
fa1a63cb192666fc6aa5c7c72130993818ea58d0
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.l = capacity self.history = [] self.map = {} def get(self, key): """:rtype: int""" if key not in self.map: return -1 self.history.remove(key) self.history.app...
the_stack_v2_python_sparse
q146.py
gitttttt/lc
train
0
8ac8e18b2aac959f03c40eef1d50ddfb6c99e897
[ "if assessment.source_presented_left:\n if assessment.relation_type == 'P':\n preference = 'L'\n elif assessment.relation_type == 'D':\n preference = 'D'\n elif assessment.relation_type == 'B':\n preference = 'LB'\nelif assessment.relation_type == 'P':\n preference = 'R'\nelif asses...
<|body_start_0|> if assessment.source_presented_left: if assessment.relation_type == 'P': preference = 'L' elif assessment.relation_type == 'D': preference = 'D' elif assessment.relation_type == 'B': preference = 'LB' el...
PreferenceAssessmentForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreferenceAssessmentForm: def from_assessment(cls, assessment): """Creates a PreferenceAssessmentForm from an AssessedDocumentRelation""" <|body_0|> def to_assessment(self, left_doc, right_doc): """Converts this form to an UNSAVED assessment object.""" <|body...
stack_v2_sparse_classes_36k_train_031484
6,306
no_license
[ { "docstring": "Creates a PreferenceAssessmentForm from an AssessedDocumentRelation", "name": "from_assessment", "signature": "def from_assessment(cls, assessment)" }, { "docstring": "Converts this form to an UNSAVED assessment object.", "name": "to_assessment", "signature": "def to_asse...
2
stack_v2_sparse_classes_30k_train_002127
Implement the Python class `PreferenceAssessmentForm` described below. Class description: Implement the PreferenceAssessmentForm class. Method signatures and docstrings: - def from_assessment(cls, assessment): Creates a PreferenceAssessmentForm from an AssessedDocumentRelation - def to_assessment(self, left_doc, righ...
Implement the Python class `PreferenceAssessmentForm` described below. Class description: Implement the PreferenceAssessmentForm class. Method signatures and docstrings: - def from_assessment(cls, assessment): Creates a PreferenceAssessmentForm from an AssessedDocumentRelation - def to_assessment(self, left_doc, righ...
e726870180788b10b102c62161e523382f1aa697
<|skeleton|> class PreferenceAssessmentForm: def from_assessment(cls, assessment): """Creates a PreferenceAssessmentForm from an AssessedDocumentRelation""" <|body_0|> def to_assessment(self, left_doc, right_doc): """Converts this form to an UNSAVED assessment object.""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PreferenceAssessmentForm: def from_assessment(cls, assessment): """Creates a PreferenceAssessmentForm from an AssessedDocumentRelation""" if assessment.source_presented_left: if assessment.relation_type == 'P': preference = 'L' elif assessment.relation_t...
the_stack_v2_python_sparse
forms.py
fisayoadegun/django-assessment
train
0
6b1c63dcbf62cb9c56e782e98dc299aac98953b8
[ "self.set_header('content-type', 'application/json')\ntry:\n incident_list = IncidentDao().get_incident_list()\n self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident_list}))\nexcept Exception as e:\n logger.error(e)\n self.process_error(400, 'fail to get incidents from database')", "se...
<|body_start_0|> self.set_header('content-type', 'application/json') try: incident_list = IncidentDao().get_incident_list() self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident_list})) except Exception as e: logger.error(e) self.pro...
IncidentListHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IncidentListHandler: def get(self): """list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions...
stack_v2_sparse_classes_36k_train_031485
20,674
permissive
[ { "docstring": "list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions/Error'", "name": "get", "signature": "...
2
stack_v2_sparse_classes_30k_train_018037
Implement the Python class `IncidentListHandler` described below. Class description: Implement the IncidentListHandler class. Method signatures and docstrings: - def get(self): list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incident...
Implement the Python class `IncidentListHandler` described below. Class description: Implement the IncidentListHandler class. Method signatures and docstrings: - def get(self): list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incident...
2e32e6e7b225e0bd87ee8c847c22862f12c51bb1
<|skeleton|> class IncidentListHandler: def get(self): """list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IncidentListHandler: def get(self): """list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions/Error'""" ...
the_stack_v2_python_sparse
nebula/views/risk_incident.py
threathunterX/nebula_web
train
2
958aedd0caaf393fba95c3446aad03543aef6cdf
[ "self.as_super = super(CLIDriverBase, self)\nself.as_super.__init__()\nself.net_protocol = EmCLIProtocol()\nself._port_number = 22", "if service_type not in self.list_enable_service:\n return GlobalModule.COM_CONNECT_NG\nelse:\n tmp_device_info = None\n if device_info is not None:\n tmp_json = jso...
<|body_start_0|> self.as_super = super(CLIDriverBase, self) self.as_super.__init__() self.net_protocol = EmCLIProtocol() self._port_number = 22 <|end_body_0|> <|body_start_1|> if service_type not in self.list_enable_service: return GlobalModule.COM_CONNECT_NG ...
CLI driver (base) class
CLIDriverBase
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CLIDriverBase: """CLI driver (base) class""" def __init__(self): """Constructor""" <|body_0|> def connect_device(self, device_name, device_info, service_type, order_type): """Connection control of individual section on driver Get launched from driver common secti...
stack_v2_sparse_classes_36k_train_031486
4,327
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Connection control of individual section on driver Get launched from driver common section, and conduct device connection control to the protocol processing section. Parameter: device_name : De...
4
null
Implement the Python class `CLIDriverBase` described below. Class description: CLI driver (base) class Method signatures and docstrings: - def __init__(self): Constructor - def connect_device(self, device_name, device_info, service_type, order_type): Connection control of individual section on driver Get launched fro...
Implement the Python class `CLIDriverBase` described below. Class description: CLI driver (base) class Method signatures and docstrings: - def __init__(self): Constructor - def connect_device(self, device_name, device_info, service_type, order_type): Connection control of individual section on driver Get launched fro...
e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f
<|skeleton|> class CLIDriverBase: """CLI driver (base) class""" def __init__(self): """Constructor""" <|body_0|> def connect_device(self, device_name, device_info, service_type, order_type): """Connection control of individual section on driver Get launched from driver common secti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CLIDriverBase: """CLI driver (base) class""" def __init__(self): """Constructor""" self.as_super = super(CLIDriverBase, self) self.as_super.__init__() self.net_protocol = EmCLIProtocol() self._port_number = 22 def connect_device(self, device_name, device_info,...
the_stack_v2_python_sparse
lib/SeparateDriver/CLIDriver.py
lixiaochun/element-manager
train
0
eb61fcc3acc3bd9619406313a1e48c7f64e90ef5
[ "self.task_controller = task_controller\nself.clear_before = clear_before\nself.clear_after = clear_after\nself.retries = retries\nself.recovery_task = recovery_task\nself.depend = depend\nself.block = block", "max_len = max((len(s) for s in sequences))\nfor s in sequences:\n if len(s) != max_len:\n rai...
<|body_start_0|> self.task_controller = task_controller self.clear_before = clear_before self.clear_after = clear_after self.retries = retries self.recovery_task = recovery_task self.depend = depend self.block = block <|end_body_0|> <|body_start_1|> max_l...
Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`.
TaskMapper
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskMapper: """Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`.""" def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True): """Create a `IMapper` given a ...
stack_v2_sparse_classes_36k_train_031487
8,554
permissive
[ { "docstring": "Create a `IMapper` given a `TaskController` and arguments. The additional arguments are those that are common to all types of tasks and are described in the documentation for `IPython.kernel.task.BaseTask`. :Parameters: task_controller : an `IBlockingTaskClient` implementer The `TaskController` ...
2
stack_v2_sparse_classes_30k_train_014002
Implement the Python class `TaskMapper` described below. Class description: Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`. Method signatures and docstrings: - def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=No...
Implement the Python class `TaskMapper` described below. Class description: Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`. Method signatures and docstrings: - def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=No...
1cf44de3833929a4cf9e0069e8c75ef9086eeaca
<|skeleton|> class TaskMapper: """Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`.""" def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True): """Create a `IMapper` given a ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskMapper: """Make an `ITaskController` look like an `IMapper`. This class provides a load balanced version of `map`.""" def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True): """Create a `IMapper` given a `TaskControll...
the_stack_v2_python_sparse
IPython/kernel/mapper.py
omazapa/ipython
train
3
42154493083a67dac70c4862fc1205eb76e4c0e9
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IntelligenceProfileIndicator()", "from .indicator import Indicator\nfrom .indicator import Indicator\nfields: Dict[str, Callable[[Any], None]] = {'firstSeenDateTime': lambda n: setattr(self, 'first_seen_date_time', n.get_datetime_value...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return IntelligenceProfileIndicator() <|end_body_0|> <|body_start_1|> from .indicator import Indicator from .indicator import Indicator fields: Dict[str, Callable[[Any], None]] = {'firs...
IntelligenceProfileIndicator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IntelligenceProfileIndicator: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfileIndicator: """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...
stack_v2_sparse_classes_36k_train_031488
2,959
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: IntelligenceProfileIndicator", "name": "create_from_discriminator_value", "signature": "def create_from_disc...
3
null
Implement the Python class `IntelligenceProfileIndicator` described below. Class description: Implement the IntelligenceProfileIndicator class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfileIndicator: Creates a new instance of the a...
Implement the Python class `IntelligenceProfileIndicator` described below. Class description: Implement the IntelligenceProfileIndicator class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfileIndicator: Creates a new instance of the a...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class IntelligenceProfileIndicator: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfileIndicator: """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...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IntelligenceProfileIndicator: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfileIndicator: """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 th...
the_stack_v2_python_sparse
msgraph/generated/models/security/intelligence_profile_indicator.py
microsoftgraph/msgraph-sdk-python
train
135
63bbe8f7d77741dfc788f3417aa42f93ac6222d0
[ "super(PanopticClassMapper, self).__init__(nusc)\nself.things = self.get_things()\nself.stuff = self.get_stuff()", "stuff_names = {'driveable_surface', 'other_flat', 'sidewalk', 'terrain', 'manmade', 'vegetation'}\ncoarse_name_to_id = self.get_coarse2idx()\nassert stuff_names <= set(coarse_name_to_id.keys()), 'In...
<|body_start_0|> super(PanopticClassMapper, self).__init__(nusc) self.things = self.get_things() self.stuff = self.get_stuff() <|end_body_0|> <|body_start_1|> stuff_names = {'driveable_surface', 'other_flat', 'sidewalk', 'terrain', 'manmade', 'vegetation'} coarse_name_to_id = se...
Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)
PanopticClassMapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PanopticClassMapper: """Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)""" def __init__(self, nusc: N...
stack_v2_sparse_classes_36k_train_031489
2,913
permissive
[ { "docstring": "Initialize a PanopticClassMapper object. :param nusc: A NuScenes object.", "name": "__init__", "signature": "def __init__(self, nusc: NuScenes)" }, { "docstring": "Returns the mapping from the challenge (coarse) class names to the challenge class indices for stuff. :return: A dic...
3
stack_v2_sparse_classes_30k_train_002217
Implement the Python class `PanopticClassMapper` described below. Class description: Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nu...
Implement the Python class `PanopticClassMapper` described below. Class description: Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nu...
a5c089133baa001d3ab3c5583a103957e4ae8375
<|skeleton|> class PanopticClassMapper: """Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)""" def __init__(self, nusc: N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PanopticClassMapper: """Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)""" def __init__(self, nusc: NuScenes): ...
the_stack_v2_python_sparse
python-sdk/nuscenes/eval/panoptic/utils.py
nutonomy/nuscenes-devkit
train
1,945
5858c52e445f4c33a905975b868e80daf02b78d9
[ "self.locations = locations\npairs = [(alpha, beta) for alpha in alphas for beta in betas]\nthinkbayes2.Suite.__init__(self, pairs)", "alpha, beta = hypo\nx = data\npmf = MakeLocationPmf(alpha, beta, self.locations)\nlike = pmf.Prob(x)\nreturn like" ]
<|body_start_0|> self.locations = locations pairs = [(alpha, beta) for alpha in alphas for beta in betas] thinkbayes2.Suite.__init__(self, pairs) <|end_body_0|> <|body_start_1|> alpha, beta = hypo x = data pmf = MakeLocationPmf(alpha, beta, self.locations) like =...
Represents hypotheses about the location of an opponent.
Paintball
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Paintball: """Represents hypotheses about the location of an opponent.""" def __init__(self, alphas, betas, locations): """Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locations for use in Likelihood. alphas: possible values for alp...
stack_v2_sparse_classes_36k_train_031490
5,533
permissive
[ { "docstring": "Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locations for use in Likelihood. alphas: possible values for alpha betas: possible values for beta locations: possible locations along the wall", "name": "__init__", "signature": "def __init_...
2
null
Implement the Python class `Paintball` described below. Class description: Represents hypotheses about the location of an opponent. Method signatures and docstrings: - def __init__(self, alphas, betas, locations): Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locatio...
Implement the Python class `Paintball` described below. Class description: Represents hypotheses about the location of an opponent. Method signatures and docstrings: - def __init__(self, alphas, betas, locations): Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locatio...
53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f
<|skeleton|> class Paintball: """Represents hypotheses about the location of an opponent.""" def __init__(self, alphas, betas, locations): """Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locations for use in Likelihood. alphas: possible values for alp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Paintball: """Represents hypotheses about the location of an opponent.""" def __init__(self, alphas, betas, locations): """Makes a joint suite of parameters alpha and beta. Enumerates all pairs of alpha and beta. Stores locations for use in Likelihood. alphas: possible values for alpha betas: pos...
the_stack_v2_python_sparse
python/learn/thinkbayes/paintball.py
qrsforever/workspace
train
2
fe91bbf55ac403e6240c5d5dadde4f44b983e2e1
[ "demand_per_product_group = {demand_aluminium_electricity_energetic: self.ELECTRICITY_PRODUCTS, demand_aluminium_network_gas_energetic: self.NETWORK_GAS_PRODUCTS}\nall_amounts_to_shift = self.energy_balance.all_product_amounts_proportionate(self.IND_NON_FER_MET, demand_per_product_group)\nself.energy_balance.shift_...
<|body_start_0|> demand_per_product_group = {demand_aluminium_electricity_energetic: self.ELECTRICITY_PRODUCTS, demand_aluminium_network_gas_energetic: self.NETWORK_GAS_PRODUCTS} all_amounts_to_shift = self.energy_balance.all_product_amounts_proportionate(self.IND_NON_FER_MET, demand_per_product_group) ...
IndustryMetalConverter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IndustryMetalConverter: def conversion(self, demand_aluminium_electricity_energetic, demand_aluminium_network_gas_energetic): """Splits industry non-ferrous metals demand into 'aluminium' and 'other', based on the total demand of aluminium Params: demand_aluminium_electricity_energetic (...
stack_v2_sparse_classes_36k_train_031491
3,199
no_license
[ { "docstring": "Splits industry non-ferrous metals demand into 'aluminium' and 'other', based on the total demand of aluminium Params: demand_aluminium_electricity_energetic (float): The total amount of TJ that should end up in the aluminium sector for electricity", "name": "conversion", "signature": "d...
2
stack_v2_sparse_classes_30k_train_012417
Implement the Python class `IndustryMetalConverter` described below. Class description: Implement the IndustryMetalConverter class. Method signatures and docstrings: - def conversion(self, demand_aluminium_electricity_energetic, demand_aluminium_network_gas_energetic): Splits industry non-ferrous metals demand into '...
Implement the Python class `IndustryMetalConverter` described below. Class description: Implement the IndustryMetalConverter class. Method signatures and docstrings: - def conversion(self, demand_aluminium_electricity_energetic, demand_aluminium_network_gas_energetic): Splits industry non-ferrous metals demand into '...
bef8f76c7e0ebc172646fef085c8705245998b2f
<|skeleton|> class IndustryMetalConverter: def conversion(self, demand_aluminium_electricity_energetic, demand_aluminium_network_gas_energetic): """Splits industry non-ferrous metals demand into 'aluminium' and 'other', based on the total demand of aluminium Params: demand_aluminium_electricity_energetic (...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IndustryMetalConverter: def conversion(self, demand_aluminium_electricity_energetic, demand_aluminium_network_gas_energetic): """Splits industry non-ferrous metals demand into 'aluminium' and 'other', based on the total demand of aluminium Params: demand_aluminium_electricity_energetic (float): The to...
the_stack_v2_python_sparse
tools/energy_balance_generator/etm_tools/energy_balance_operations/converters/industry_metal.py
quintel/etdataset-public
train
4
4c8bf972155cab0ea9c4e4e9fb70e27403160dbe
[ "if isinstance(model_or_obj_or_qs, QuerySet):\n _, fname = model_map[model_or_obj_or_qs.model]\nelse:\n cls = model_or_obj_or_qs if inspect.isclass(model_or_obj_or_qs) else model_or_obj_or_qs.__class__\n _, fname = model_map[cls]\nreturn fname", "follow = Follow(user=user)\nfollow.target = obj\nfollow.sa...
<|body_start_0|> if isinstance(model_or_obj_or_qs, QuerySet): _, fname = model_map[model_or_obj_or_qs.model] else: cls = model_or_obj_or_qs if inspect.isclass(model_or_obj_or_qs) else model_or_obj_or_qs.__class__ _, fname = model_map[cls] return fname <|end_bo...
FollowManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FollowManager: def fname(self, model_or_obj_or_qs): """Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.""" <|body_0|> def create(self, user, obj, **kwargs): """Create a new follow link between a user and an object of a registered model t...
stack_v2_sparse_classes_36k_train_031492
27,387
no_license
[ { "docstring": "Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.", "name": "fname", "signature": "def fname(self, model_or_obj_or_qs)" }, { "docstring": "Create a new follow link between a user and an object of a registered model type.", "name": "create", "s...
5
null
Implement the Python class `FollowManager` described below. Class description: Implement the FollowManager class. Method signatures and docstrings: - def fname(self, model_or_obj_or_qs): Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``. - def create(self, user, obj, **kwargs): Create a ne...
Implement the Python class `FollowManager` described below. Class description: Implement the FollowManager class. Method signatures and docstrings: - def fname(self, model_or_obj_or_qs): Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``. - def create(self, user, obj, **kwargs): Create a ne...
0ac6653219c2701c13c508c5c4fc9bc3437eea06
<|skeleton|> class FollowManager: def fname(self, model_or_obj_or_qs): """Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.""" <|body_0|> def create(self, user, obj, **kwargs): """Create a new follow link between a user and an object of a registered model t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FollowManager: def fname(self, model_or_obj_or_qs): """Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.""" if isinstance(model_or_obj_or_qs, QuerySet): _, fname = model_map[model_or_obj_or_qs.model] else: cls = model_or_obj_or_qs if...
the_stack_v2_python_sparse
repoData/caffeinehit-django-follow/allPythonContent.py
aCoffeeYin/pyreco
train
0
23a132cbd8bd7855b639e2e447030b7030b815bc
[ "result = parse_ip_and_port(self.get(section, option), default_port)\nif result == (None, 0):\n result = None\nreturn result", "try:\n return ConfigParser.get(self, section, option)\nexcept (NoSectionError, NoOptionError):\n return None", "try:\n return ConfigParser.getint(self, section, option)\nex...
<|body_start_0|> result = parse_ip_and_port(self.get(section, option), default_port) if result == (None, 0): result = None return result <|end_body_0|> <|body_start_1|> try: return ConfigParser.get(self, section, option) except (NoSectionError, NoOptionEr...
Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.
ExtendedConfigParser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtendedConfigParser: """Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.""" def getaddress(self, section, option, default_port=None): """Gets IP address with port and stores it in a tuple. Returns None on invalid format or exc...
stack_v2_sparse_classes_36k_train_031493
1,315
no_license
[ { "docstring": "Gets IP address with port and stores it in a tuple. Returns None on invalid format or exceptions.", "name": "getaddress", "signature": "def getaddress(self, section, option, default_port=None)" }, { "docstring": "Gets string value. Returns None on exceptions.", "name": "get",...
4
stack_v2_sparse_classes_30k_train_012077
Implement the Python class `ExtendedConfigParser` described below. Class description: Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple. Method signatures and docstrings: - def getaddress(self, section, option, default_port=None): Gets IP address with port and st...
Implement the Python class `ExtendedConfigParser` described below. Class description: Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple. Method signatures and docstrings: - def getaddress(self, section, option, default_port=None): Gets IP address with port and st...
0abf116e1703bca09a946f39d18b1f537a38ccdc
<|skeleton|> class ExtendedConfigParser: """Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.""" def getaddress(self, section, option, default_port=None): """Gets IP address with port and stores it in a tuple. Returns None on invalid format or exc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExtendedConfigParser: """Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.""" def getaddress(self, section, option, default_port=None): """Gets IP address with port and stores it in a tuple. Returns None on invalid format or exceptions.""" ...
the_stack_v2_python_sparse
ExtendedConfigParser.py
wojtekka/gort
train
0
42e98e66854ccd9caa342f21e41600ab8cbc8362
[ "if len(nums) <= 1:\n return 0\nm = max(nums)\ntemp = nums.copy()\ntemp.remove(m)\nn = max(temp)\nif m >= n * 2:\n return nums.index(m)\nreturn -1", "a = max(nums) * 2\nprint(a)\nprint(nums * 2)\nprint(max(nums * 2))\nif a == max([x * 2 for x in nums]):\n return nums.index(max(nums))\nelse:\n return -...
<|body_start_0|> if len(nums) <= 1: return 0 m = max(nums) temp = nums.copy() temp.remove(m) n = max(temp) if m >= n * 2: return nums.index(m) return -1 <|end_body_0|> <|body_start_1|> a = max(nums) * 2 print(a) pri...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dominantIndex(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def dominantIndex2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(nums) <= 1: return 0 ...
stack_v2_sparse_classes_36k_train_031494
1,909
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "dominantIndex", "signature": "def dominantIndex(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "dominantIndex2", "signature": "def dominantIndex2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_010578
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dominantIndex(self, nums): :type nums: List[int] :rtype: int - def dominantIndex2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dominantIndex(self, nums): :type nums: List[int] :rtype: int - def dominantIndex2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def domina...
f022677c042db3598003df1a320a70f0edc4f870
<|skeleton|> class Solution: def dominantIndex(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def dominantIndex2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def dominantIndex(self, nums): """:type nums: List[int] :rtype: int""" if len(nums) <= 1: return 0 m = max(nums) temp = nums.copy() temp.remove(m) n = max(temp) if m >= n * 2: return nums.index(m) return -1 ...
the_stack_v2_python_sparse
ArrayDeal/zhishaoshiqitashuziliangbeizuidashu.py
daisyzl/program-exercise-python
train
0
372c2ad449be64e7b97db88b0cb6005f0ac139ce
[ "self.output_sz = output_sz\nself.scope = 'double_lstm_dense'\nself.keep_prob = keep_prob\nself.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lstm', 'encoder1')\nself.lstm_encoder2 = RNNEncoder(output_sz, keep_prob, 'gru', 'encoder2')", "with vs.variable_scope(self.scope):\n lstm_1_out = self.lstm_encoder1...
<|body_start_0|> self.output_sz = output_sz self.scope = 'double_lstm_dense' self.keep_prob = keep_prob self.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lstm', 'encoder1') self.lstm_encoder2 = RNNEncoder(output_sz, keep_prob, 'gru', 'encoder2') <|end_body_0|> <|body_start_...
base class for output representation
OutputDoubleLSTMDense
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OutputDoubleLSTMDense: """base class for output representation""" def __init__(self, output_sz, keep_prob): """Args:""" <|body_0|> def build_graph(self, reps, context_mask): """Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, out...
stack_v2_sparse_classes_36k_train_031495
1,464
no_license
[ { "docstring": "Args:", "name": "__init__", "signature": "def __init__(self, output_sz, keep_prob)" }, { "docstring": "Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, output_sz]", "name": "build_graph", "signature": "def build_graph(self, reps, context_...
2
stack_v2_sparse_classes_30k_train_009807
Implement the Python class `OutputDoubleLSTMDense` described below. Class description: base class for output representation Method signatures and docstrings: - def __init__(self, output_sz, keep_prob): Args: - def build_graph(self, reps, context_mask): Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz...
Implement the Python class `OutputDoubleLSTMDense` described below. Class description: base class for output representation Method signatures and docstrings: - def __init__(self, output_sz, keep_prob): Args: - def build_graph(self, reps, context_mask): Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz...
66756a0019b294ec4e2e048473f10115bda45bde
<|skeleton|> class OutputDoubleLSTMDense: """base class for output representation""" def __init__(self, output_sz, keep_prob): """Args:""" <|body_0|> def build_graph(self, reps, context_mask): """Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, out...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OutputDoubleLSTMDense: """base class for output representation""" def __init__(self, output_sz, keep_prob): """Args:""" self.output_sz = output_sz self.scope = 'double_lstm_dense' self.keep_prob = keep_prob self.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lst...
the_stack_v2_python_sparse
src/code/modules/output_double_lstm_dense.py
dengl11/CS224N-Project-Machine-Reading
train
2
0489d1c77971b9c37cafeb8e41d4086cf9d4ac36
[ "dataset_package = import_module('mindspore.dataset')\ntry:\n dataset_dict = dataset_package.serialize(dataset)\nexcept (TypeError, OSError) as exc:\n logger.warning('Summary can not collect dataset graph, there is an error in dataset internal, detail: %s.', str(exc))\n return None\ndataset_graph_proto = l...
<|body_start_0|> dataset_package = import_module('mindspore.dataset') try: dataset_dict = dataset_package.serialize(dataset) except (TypeError, OSError) as exc: logger.warning('Summary can not collect dataset graph, there is an error in dataset internal, detail: %s.', str...
Handle the data graph and packages it into binary data.
DatasetGraph
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "OpenSSL", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause-Open-MPI", "MIT", "MPL-2.0-no-copyleft-exception", "NTP", "BSD-3-Clause", "GPL-1.0-or-later", "0BSD", "MPL-2.0", "LicenseRef-scancode-f...
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetGraph: """Handle the data graph and packages it into binary data.""" def package_dataset_graph(self, dataset): """packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: DatasetGraph, a object of lineage_pb2.DatasetGraph.""" ...
stack_v2_sparse_classes_36k_train_031496
6,216
permissive
[ { "docstring": "packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: DatasetGraph, a object of lineage_pb2.DatasetGraph.", "name": "package_dataset_graph", "signature": "def package_dataset_graph(self, dataset)" }, { "docstring": "Package children i...
5
null
Implement the Python class `DatasetGraph` described below. Class description: Handle the data graph and packages it into binary data. Method signatures and docstrings: - def package_dataset_graph(self, dataset): packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: Datase...
Implement the Python class `DatasetGraph` described below. Class description: Handle the data graph and packages it into binary data. Method signatures and docstrings: - def package_dataset_graph(self, dataset): packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: Datase...
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
<|skeleton|> class DatasetGraph: """Handle the data graph and packages it into binary data.""" def package_dataset_graph(self, dataset): """packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: DatasetGraph, a object of lineage_pb2.DatasetGraph.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatasetGraph: """Handle the data graph and packages it into binary data.""" def package_dataset_graph(self, dataset): """packages dataset graph into binary data Args: dataset (MindDataset): Refer to MindDataset. Returns: DatasetGraph, a object of lineage_pb2.DatasetGraph.""" dataset_packa...
the_stack_v2_python_sparse
mindspore/python/mindspore/train/callback/_dataset_graph.py
mindspore-ai/mindspore
train
4,178
b8e2e87a930aa21de2f02fbcc6a42590ef48c94f
[ "matches = []\nprim_type = kwargs.get('primitive_type')\nif prim_type == 'List':\n valid_values = kwargs.get('valid_values')\n if valid_values:\n if value not in valid_values:\n message = 'Allowed values for {0} are ({1})'\n matches.append(RuleMatch(path, message.format(kwargs.get...
<|body_start_0|> matches = [] prim_type = kwargs.get('primitive_type') if prim_type == 'List': valid_values = kwargs.get('valid_values') if valid_values: if value not in valid_values: message = 'Allowed values for {0} are ({1})' ...
Check Update Policy Configuration
Configuration
[ "MIT-0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Configuration: """Check Update Policy Configuration""" def check_value(self, value, path, **kwargs): """Check a primitive value""" <|body_0|> def check_attributes(self, cfn, properties, spec_type, path): """Check the properties against the spec""" <|body_...
stack_v2_sparse_classes_36k_train_031497
8,942
permissive
[ { "docstring": "Check a primitive value", "name": "check_value", "signature": "def check_value(self, value, path, **kwargs)" }, { "docstring": "Check the properties against the spec", "name": "check_attributes", "signature": "def check_attributes(self, cfn, properties, spec_type, path)" ...
4
null
Implement the Python class `Configuration` described below. Class description: Check Update Policy Configuration Method signatures and docstrings: - def check_value(self, value, path, **kwargs): Check a primitive value - def check_attributes(self, cfn, properties, spec_type, path): Check the properties against the sp...
Implement the Python class `Configuration` described below. Class description: Check Update Policy Configuration Method signatures and docstrings: - def check_value(self, value, path, **kwargs): Check a primitive value - def check_attributes(self, cfn, properties, spec_type, path): Check the properties against the sp...
5176573c2f4cb7313998b4bc0bcb0716b58ea380
<|skeleton|> class Configuration: """Check Update Policy Configuration""" def check_value(self, value, path, **kwargs): """Check a primitive value""" <|body_0|> def check_attributes(self, cfn, properties, spec_type, path): """Check the properties against the spec""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Configuration: """Check Update Policy Configuration""" def check_value(self, value, path, **kwargs): """Check a primitive value""" matches = [] prim_type = kwargs.get('primitive_type') if prim_type == 'List': valid_values = kwargs.get('valid_values') ...
the_stack_v2_python_sparse
src/cfnlint/rules/resources/updatepolicy/Configuration.py
rene84/cfn-python-lint
train
1
fded1f3221e1411e9c94067e3e21f204ec5e1195
[ "self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('current_name', required=True, type=str, help='Current subtheme name required', location=['form', 'json'])\nself.reqparser.add_argument('new_name', required=True, type=str, help='New subtheme name required', location=['form', 'json'])\nself.req...
<|body_start_0|> self.reqparser = reqparse.RequestParser() self.reqparser.add_argument('current_name', required=True, type=str, help='Current subtheme name required', location=['form', 'json']) self.reqparser.add_argument('new_name', required=True, type=str, help='New subtheme name required', lo...
Rename an existing SubTheme
RenameSubTheme
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RenameSubTheme: """Rename an existing SubTheme""" def __init__(self) -> None: """Set required arguments for POST request""" <|body_0|> def post(self) -> ({str: str}, HTTPStatus): """Rename an existing SubTheme :param current_name: the name of the sub theme to ren...
stack_v2_sparse_classes_36k_train_031498
3,437
permissive
[ { "docstring": "Set required arguments for POST request", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Rename an existing SubTheme :param current_name: the name of the sub theme to rename :param new_name: the new name for the sub theme :param theme_id: Parent ...
2
null
Implement the Python class `RenameSubTheme` described below. Class description: Rename an existing SubTheme Method signatures and docstrings: - def __init__(self) -> None: Set required arguments for POST request - def post(self) -> ({str: str}, HTTPStatus): Rename an existing SubTheme :param current_name: the name of...
Implement the Python class `RenameSubTheme` described below. Class description: Rename an existing SubTheme Method signatures and docstrings: - def __init__(self) -> None: Set required arguments for POST request - def post(self) -> ({str: str}, HTTPStatus): Rename an existing SubTheme :param current_name: the name of...
5d123691d1f25d0b85e20e4e8293266bf23c9f8a
<|skeleton|> class RenameSubTheme: """Rename an existing SubTheme""" def __init__(self) -> None: """Set required arguments for POST request""" <|body_0|> def post(self) -> ({str: str}, HTTPStatus): """Rename an existing SubTheme :param current_name: the name of the sub theme to ren...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RenameSubTheme: """Rename an existing SubTheme""" def __init__(self) -> None: """Set required arguments for POST request""" self.reqparser = reqparse.RequestParser() self.reqparser.add_argument('current_name', required=True, type=str, help='Current subtheme name required', locatio...
the_stack_v2_python_sparse
Analytics/resources/themes/rename_subtheme.py
thanosbnt/SharingCitiesDashboard
train
0
0211c3646d2ba7888dfbaa11bf12d5a6f254d778
[ "result = [0, 0]\nl = len(A)\nL = [0] * (l + 1)\nfor i, a in enumerate(A):\n if i - a >= 0:\n L[i - a] += 1\ns = 0\nmax_index = l - 1\nfor i in range(l):\n print(L)\n a = L.pop(0)\n L.append(0)\n s -= a\n if max_index - A[i] >= 0:\n L[max_index - A[i]] += 1\n s += 1\n if s ...
<|body_start_0|> result = [0, 0] l = len(A) L = [0] * (l + 1) for i, a in enumerate(A): if i - a >= 0: L[i - a] += 1 s = 0 max_index = l - 1 for i in range(l): print(L) a = L.pop(0) L.append(0) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def bestRotation(self, A): """:type A: List[int] :rtype: int 880ms""" <|body_0|> def bestRotation_1(self, A): """:type A: List[int] :rtype: int 119ms""" <|body_1|> def bestRotation_2(self, A): """127ms :param A: :return:""" <|bo...
stack_v2_sparse_classes_36k_train_031499
3,416
no_license
[ { "docstring": ":type A: List[int] :rtype: int 880ms", "name": "bestRotation", "signature": "def bestRotation(self, A)" }, { "docstring": ":type A: List[int] :rtype: int 119ms", "name": "bestRotation_1", "signature": "def bestRotation_1(self, A)" }, { "docstring": "127ms :param A...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bestRotation(self, A): :type A: List[int] :rtype: int 880ms - def bestRotation_1(self, A): :type A: List[int] :rtype: int 119ms - def bestRotation_2(self, A): 127ms :param A:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bestRotation(self, A): :type A: List[int] :rtype: int 880ms - def bestRotation_1(self, A): :type A: List[int] :rtype: int 119ms - def bestRotation_2(self, A): 127ms :param A:...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def bestRotation(self, A): """:type A: List[int] :rtype: int 880ms""" <|body_0|> def bestRotation_1(self, A): """:type A: List[int] :rtype: int 119ms""" <|body_1|> def bestRotation_2(self, A): """127ms :param A: :return:""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def bestRotation(self, A): """:type A: List[int] :rtype: int 880ms""" result = [0, 0] l = len(A) L = [0] * (l + 1) for i, a in enumerate(A): if i - a >= 0: L[i - a] += 1 s = 0 max_index = l - 1 for i in range...
the_stack_v2_python_sparse
SmallestRotationWithHighestScore_HARD_798.py
953250587/leetcode-python
train
2