id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
15,067
import configparser import errno import json import os import re import subprocess import sys HANDLERS = {} The provided code snippet includes necessary dependencies for implementing the `register_vcs_handler` function. Write a Python function `def register_vcs_handler(vcs, method)` to solve the following problem: Cre...
Create decorator to mark a method as the handler of a VCS.
15,068
import configparser import errno import json import os import re import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `git_get_keywords` function. Write a Python function `def git_get_keywords(versionfile_abs)` to solve the following problem: Extract version infor...
Extract version information from the given file.
15,069
import configparser import errno import json import os import re import subprocess import sys class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" The provided code snippet includes necessary dependencies for implementing the `git_versions_from_keywords` functio...
Get version information from git keywords.
15,070
import configparser import errno import json import os import re import subprocess import sys class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" The provided code snippet includes necessary dependencies for implementing the `git_pieces_from_vcs` function. Writ...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
15,071
import configparser import errno import json import os import re import subprocess import sys def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion ...
Get the short version string for this project.
15,072
import configparser import errno import json import os import re import subprocess import sys def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.re...
Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument.
15,073
import configparser import errno import json import os import re import subprocess import sys def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.re...
Do main VCS-independent setup function for installing Versioneer.
15,074
import configparser import errno import json import os import re import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `scan_setup_py` function. Write a Python function `def scan_setup_py()` to solve the following problem: Validate the contents of setup.py against ...
Validate the contents of setup.py against Versioneer's expectations.
15,075
from glob import glob from setuptools import setup import versioneer def read_file(fname): with open(fname, "r", encoding="utf8") as f: return f.read()
null
15,076
from ipyflow._version import get_versions __version__ = get_versions()["version"] def make_version_tuple(vstr=None): if vstr is None: vstr = __version__ if vstr[0] == "v": vstr = vstr[1:] components = [] for component in vstr.split("+")[0].split("."): try: components...
null
15,077
import argparse import json import os import platform import sys from IPython.utils.tempdir import TemporaryDirectory from jupyter_client.kernelspec import KernelSpecManager PACKAGE = __package__.split(".")[0] kernel_json = { "argv": [ sys.executable, "-m", "ipyflow.kernel", "-f", ...
null
15,078
import argparse import json import os import platform import sys from IPython.utils.tempdir import TemporaryDirectory from jupyter_client.kernelspec import KernelSpecManager def _is_root(): try: return os.geteuid() == 0 except AttributeError: return False # assume not an admin on non-Unix plat...
null
15,079
import asyncio import inspect import logging from typing import TYPE_CHECKING, NamedTuple, Optional from typing import Type as TypeType from ipykernel.ipkernel import IPythonKernel from IPython import get_ipython from traitlets import Type from ipyflow import singletons from ipyflow.flow import NotebookFlow from ipyflo...
null
15,080
import asyncio import inspect import logging from typing import TYPE_CHECKING, NamedTuple, Optional from typing import Type as TypeType from ipykernel.ipkernel import IPythonKernel from IPython import get_ipython from traitlets import Type from ipyflow import singletons from ipyflow.flow import NotebookFlow from ipyflo...
null
15,081
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding Symbol metadata.
15,082
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding code for that symbol.
15,083
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding timestamp for that symbol.
15,084
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding dependencies for that symbol.
15,085
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding users of that symbol.
15,086
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding recursive dependencies for that symbol.
15,087
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding users of that symbol.
15,088
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Given the programmatic usage of some symbol, look up the corresponding watchpoints for that symbol.
15,089
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Add the tag `value` to the symbol.
15,090
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Remove the tag `value` from the symbol.
15,091
from typing import TYPE_CHECKING, Any, List, Set, Union, cast from ipyflow.data_model.symbol import Symbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.tracing.watchpoint import Watchpoints def _validate(sym: Any) -> Symbol: if sym is None or not isinstance(sym, Symbol): raise ValueError(...
Test whether the symbol has the `value` tag.
15,092
from typing import Optional, Union from ipyflow.data_model.cell import cells from ipyflow.data_model.timestamp import Timestamp def _to_cell_num(ts_or_cell_num: Union[int, Timestamp]) -> int: return ( ts_or_cell_num.cell_num if isinstance(ts_or_cell_num, Timestamp) else ts_or_cell_num ) ...
null
15,093
from typing import Optional, Union from ipyflow.data_model.cell import cells from ipyflow.data_model.timestamp import Timestamp def _to_cell_num(ts_or_cell_num: Union[int, Timestamp]) -> int: return ( ts_or_cell_num.cell_num if isinstance(ts_or_cell_num, Timestamp) else ts_or_cell_num ) ...
null
15,094
from typing import Optional, Union from ipyflow.data_model.cell import cells from ipyflow.data_model.timestamp import Timestamp def reproduce_cell( ctr: int, show_input: bool = True, show_output: bool = True, lookback: int = 0 ): return ( cells() .at_counter(ctr) .reproduce(show_input=s...
null
15,095
import ast import inspect import json import os.path import re import shlex import sys from typing import TYPE_CHECKING, Iterable, Optional, Sequence, Type, cast import pyccolo as pyc from IPython import get_ipython from IPython.core.magic import register_line_magic from ipyflow.analysis.symbol_ref import SymbolRef fro...
null
15,096
import errno import os import re import subprocess import sys from typing import Callable, Dict import functools HANDLERS: Dict[str, Dict[str, Callable]] = {} The provided code snippet includes necessary dependencies for implementing the `register_vcs_handler` function. Write a Python function `def register_vcs_handle...
Create decorator to mark a method as the handler of a VCS.
15,097
import errno import os import re import subprocess import sys from typing import Callable, Dict import functools The provided code snippet includes necessary dependencies for implementing the `git_get_keywords` function. Write a Python function `def git_get_keywords(versionfile_abs)` to solve the following problem: Ex...
Extract version information from the given file.
15,098
import errno import os import re import subprocess import sys from typing import Callable, Dict import functools def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variab...
Get version information or return default if unable to do so.
15,099
from types import FunctionType, LambdaType, ModuleType from typing import TYPE_CHECKING, Type, Union from ipyflow.tracing.uninstrument import uninstrument def uninstrument( obj: Union[FunctionType, LambdaType], seen: Optional[Set[int]] = None ) -> Optional[Union[FunctionType, LambdaType]]: if seen is None: ...
null
15,100
from types import ModuleType from typing import TYPE_CHECKING, Type from ipyflow.tracing.uninstrument import uninstrument def uninstrument( obj: Union[FunctionType, LambdaType], seen: Optional[Set[int]] = None ) -> Optional[Union[FunctionType, LambdaType]]: if seen is None: seen = set() if id(obj) ...
null
15,101
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow if TYPE_CHECKING: def cells(cell_id: None = None) -> Type["Cell"]: ... def cells(cell_id: "IdType") -> "Cell": ... def cells(cell_id: Optional["IdType"] = None) -> Union[Type["Cell"], "Cel...
null
15,102
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow if TYPE_CHECKING: def cells(cell_id: None = None) -> Type["Cell"]: ... def cells(cell_id: "IdType") -> "Cell": ... def cells(cell_id: Optional["IdType"] = None) -> Union[Type["Cell"], "Cel...
null
15,103
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow if TYPE_CHECKING: def cells(cell_id: None = None) -> Type["Cell"]: ... def cells(cell_id: "IdType") -> "Cell": ... def cells(cell_id: Optional["IdType"] = None) -> Union[Type["Cell"], "Cel...
null
15,104
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow if TYPE_CHECKING: def cells(cell_id: None = None) -> Type["Cell"]: ... def cells(cell_id: "IdType") -> "Cell": ... def cells(cell_id: Optional["IdType"] = None) -> Union[Type["Cell"], "Cel...
null
15,105
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow _NamespaceContainer: List[Type["Namespace"]] = [] def namespaces() -> Type["Namespace"]: return _NamespaceContainer[0]
null
15,106
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow _ScopeContainer: List[Type["Scope"]] = [] def scopes() -> Type["Scope"]: return _ScopeContainer[0]
null
15,107
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow def symbols(sym: None = None) -> Type["Symbol"]: ...
null
15,108
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow def symbols(sym: "Symbol") -> "Symbol": ...
null
15,109
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow _SymbolContainer: List[Type["Symbol"]] = [] def symbols(sym: Optional["Symbol"] = None) -> Union[Type["Symbol"], "Symbol"]: if sym is None: return _SymbolContainer[0] else: return sym
null
15,110
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow _StatementContainer: List[Type["Statement"]] = [] def statements() -> Type["Statement"]: return _StatementContainer[0]
null
15,111
from typing import TYPE_CHECKING, List, Optional, Type, Union, overload from ipyflow.singletons import flow _TimestampContainer: List[Type["Timestamp"]] = [] def timestamps() -> Type["Timestamp"]: return _TimestampContainer[0]
null
15,112
import os from enum import Enum from typing import Any, Dict, List, Optional, Set from ipyflow.data_model.symbol import Symbol from ipyflow.singletons import flow from ipyflow.tracing.external_calls.base_handlers import ExternalCallHandler, HasGetitem The provided code snippet includes necessary dependencies for imple...
Just a marker decorator to indicate that the handler is used for functions / methods named differently from the decorated function / method
15,113
import sys from IPython.core.interactiveshell import InteractiveShell from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config from ipyflow import singletons from ipyflow.shell.interactiveshell import UsesIPyflowShell class IPyflowInteractiveShellEmbed( singlet...
Call this to embed IPyflow at the current point in your program. The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the su...
15,114
import ast import logging from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union def match_container_obj_or_namespace_with_literal_nodes( container_obj_or_namespace: Union[ "Namespace", Dict[Any, Any], List[Any], Tuple[Any, ...] ], literal_node: Union[ast.Dict, ast.List, ast.Tuple], ): ...
null
15,115
from contextlib import contextmanager from contextvars import ContextVar from enum import Enum from typing import Generator, Optional from ipyflow.utils.misc_utils import yield_in_loop class SlicingContext(Enum): DYNAMIC = "dynamic" STATIC = "static" def iter_slicing_contexts(cls) -> Generator[None, None, N...
null
15,116
from contextlib import contextmanager from contextvars import ContextVar from enum import Enum from typing import Generator, Optional from ipyflow.utils.misc_utils import yield_in_loop class SlicingContext(Enum): DYNAMIC = "dynamic" STATIC = "static" def iter_slicing_contexts(cls) -> Generator[None, None, N...
null
15,117
from contextlib import contextmanager from contextvars import ContextVar from enum import Enum from typing import Generator, Optional from ipyflow.utils.misc_utils import yield_in_loop class SlicingContext(Enum): DYNAMIC = "dynamic" STATIC = "static" def iter_slicing_contexts(cls) -> Generator[None, None, N...
null
15,118
from contextlib import contextmanager from contextvars import ContextVar from enum import Enum from typing import Generator, Optional from ipyflow.utils.misc_utils import yield_in_loop class SlicingContext(Enum): DYNAMIC = "dynamic" STATIC = "static" def iter_slicing_contexts(cls) -> Generator[None, None, N...
null
15,119
import ast import logging import sys from enum import Enum from types import FrameType, FunctionType from typing import ( TYPE_CHECKING, Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple, Type, cast, ) from ipyflow.config import ExecutionSchedule, FlowD...
null
15,120
import typing from typing import Any, Iterable, List def make_annotation_string(ann) -> str: if ann is type(None): ret = "None" elif hasattr(ann, "__name__"): ret = ann.__name__ elif hasattr(ann, "_name"): ret = ann._name if ret is None: args = ann.__args__ ...
null
15,121
from typing import TYPE_CHECKING import pyccolo as pyc from IPython.core.interactiveshell import InteractiveShellABC from traitlets.config.configurable import SingletonConfigurable class SingletonBaseTracer(pyc.BaseTracer): pass def tracer_initialized() -> bool: return SingletonBaseTracer.initialized()
null
15,122
import ast import logging import sys class ContainsNamedExprVisitor(ast.NodeVisitor): def __init__(self): self.contains_named_expr = False def __call__(self, node: ast.stmt) -> bool: if sys.version_info.minor < 8: return False self.visit(node) return self.contains_nam...
null
15,123
import ast import builtins import itertools import logging import sys from contextlib import contextmanager from typing import ( TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple, Union, cast, ) from ipyflow.analysis.mixins import ( SaveOffAttributesMixin, SkipUnbound...
null
15,124
import ast import builtins import itertools import logging import sys from contextlib import contextmanager from typing import ( TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple, Union, cast, ) from ipyflow.analysis.mixins import ( SaveOffAttributesMixin, SkipUnbound...
null
15,125
import ast import builtins import itertools import logging import sys from contextlib import contextmanager from typing import ( TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Tuple, Union, cast, ) from ipyflow.analysis.mixins import ( SaveOffAttributesMixin, SkipUnbound...
null
15,126
import ast import logging from typing import ( TYPE_CHECKING, Any, Generator, Iterable, List, Optional, Sequence, Tuple, Union, cast, ) from ipyflow.analysis.resolved_symbols import ResolvedSymbol from ipyflow.data_model.timestamp import Timestamp from ipyflow.singletons import f...
Version-independent way to get at the slice data
15,127
import ast import logging from typing import List, Sequence, Tuple, Union from ipyflow.analysis.mixins import ( SaveOffAttributesMixin, SkipUnboundArgsMixin, VisitListsMixin, ) class GetSymbolEdges( SaveOffAttributesMixin, SkipUnboundArgsMixin, VisitListsMixin, ast.NodeVisitor ): def __init__(self) ...
null
15,128
import ast import logging from collections import defaultdict from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple from ipyflow.config import ExecutionSchedule, FlowDirection from ipyflow.data_model.cell import Cell, CheckerResult, cells from ipyflow.data_model.symbol import Symbol from ipyflo...
null
15,129
import re from threading import Timer from typing import Callable def cleanup_discard(d, key, val): s = d.get(key, set()) s.discard(val) if len(s) == 0: d.pop(key, None)
null
15,130
import re from threading import Timer from typing import Callable def cleanup_pop(d, key, val): d2 = d.get(key, {}) d2.pop(val, None) if len(d2) == 0: d.pop(key, None)
null
15,131
import re from threading import Timer from typing import Callable The provided code snippet includes necessary dependencies for implementing the `debounce` function. Write a Python function `def debounce(wait: float) -> Callable[[Callable[..., None]], Callable[..., bool]]` to solve the following problem: Decorator tha...
Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked.
15,132
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,133
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,134
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,135
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,136
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,137
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,138
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,139
import ast import logging import sys from contextlib import contextmanager from io import StringIO from typing import Any, Callable, Generator, List, Optional, TextIO from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import CapturingDisplayPublisher, DisplayPublisher from IPython.core.intera...
null
15,140
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools HANDLERS: Dict[str, Dict[str, Callable]] = {} The provided code snippet includes necessary dependencies for implementing the `register_vcs_handler` function. Write a Python f...
Create decorator to mark a method as the handler of a VCS.
15,141
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools The provided code snippet includes necessary dependencies for implementing the `git_get_keywords` function. Write a Python function `def git_get_keywords(versionfile_abs)` to...
Extract version information from the given file.
15,142
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" The provided code snippet includes necessary dependencies for im...
Get version information from git keywords.
15,143
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" def run_command(commands, args, cwd=None, verbose=False, hide_std...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
15,144
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versio...
Get the short version string for this project.
15,145
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg...
Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument.
15,146
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg...
Do main VCS-independent setup function for installing Versioneer.
15,147
import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools The provided code snippet includes necessary dependencies for implementing the `scan_setup_py` function. Write a Python function `def scan_setup_py()` to solve the following ...
Validate the contents of setup.py against Versioneer's expectations.
15,156
import os import re from setuptools import setup, find_packages def get_version(): with open(os.path.join("fastedit", "__init__.py"), "r", encoding="utf-8") as f: file_content = f.read() pattern = r"{0}\W*=\W*\"([^\"]+)\"".format("__version__") version, = re.findall(pattern, file_content) ...
null
15,157
import os import fire import json from typing import Optional from .rome import ROMEHyperParams, apply_rome_to_model from .utils.prints import print_loud from .utils.template import Template from .utils.mtloader import load_model_and_tokenizer from .utils.generate import generate_fast, generate_interactive def print_l...
r""" Edits a pre-trained model using model-editing algorithms. Args: data (`str`): The path of the `json` file containing the samples for editing. model (`str`): The name or path of the pre-trained transformer model to be edited. config (`str`): The name of the hyper-parameters to use for editing the model. template (`...
15,158
import time import torch from copy import deepcopy from typing import Dict, List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer from .compute_u import compute_u from .compute_v import compute_v from .rome_hparams import ROMEHyperParams from ..utils import nethook from ..utils.cont...
r""" Edits a pre-trained model using model-editing algorithms. Args: model (`PreTrainedModel`): The pre-trained transformer model to be edited. tokeniser (`PreTrainedTokenizer`): The pre-trained tokenizer of the model. requests (`List[Dict[str, Union[List[str], str]]]`): The samples for editing. hparams (`ROMEHyperPara...
15,159
import copy import torch import inspect import contextlib from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `recursive_copy` function. Write a Python function `def recursive_copy(x, clone=None, detach=None, retain_grad=None)` to solve the following probl...
r""" Copies a reference to a tensor, or an object that contains tensors, optionally detaching and cloning the tensor(s). If retain_grad is true, the original tensors are marked to have grads retained.
15,160
import copy import torch import inspect import contextlib from collections import OrderedDict def hierarchical_subsequence( sequential, first, last, after, upto, share_weights=False, depth=0 ): r""" Recursive helper for subsequence() to support descent into dotted layer names. In this helper, first, la...
r""" Creates a subsequence of a pytorch Sequential model, copying over modules together with parameters for the subsequence. Only modules from first_layer to last_layer (inclusive) are included, or modules between after_layer and upto_layer (exclusive). Handles descent into dotted layer names as long as all references ...
15,161
import copy import torch import inspect import contextlib from collections import OrderedDict def get_module(model, name): r""" Finds the named module within the given model. """ for n, m in model.named_modules(): if n == name: return m raise LookupError(name) The provided code ...
r""" Replaces the named module within the given model.
15,162
import copy import torch import inspect import contextlib from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `invoke_with_optional_args` function. Write a Python function `def invoke_with_optional_args(fn, *args, **kwargs)` to solve the following problem:...
r""" Invokes a function with only the arguments that it is written to accept, giving priority to arguments that match by-name, using the following rules. (1) arguments with matching names are passed by name. (2) remaining non-name-matched args are passed by order. (3) extra caller arguments that the function cannot acc...
15,163
( (...,...), # 最后一个“,”最好别删! ) d', 30), params = (('period', 30), params = (('p1', 5), ('p2', 30),) r['年化收益率(%)'] = result[0].analyzers._Returns.get_analysis()['rnorm100']大回撤(%)'] = result[0].analyzers._DrawDown.get_analysis()['max']['drawdown'] * (-1)化夏普比率'] = res...
null
15,164
def next(self): ... o1 = self.buy(...) ... o2 = self.buy(..., oco=o1) ... o3 = self.buy(..., oco=o1)
null
15,165
def next(self): ... o1 = self.buy(...) ... o2 = self.buy(..., oco=o1) ... o3 = self.buy(..., oco=o2)
null
15,166
import backtrader as bt import backtrader.indicators as btinds pd import datetime import tushare as ts import json ts.set_token(token) df = df[['trade_date', 'open', 'high', 'low', 'close','vol']] df.columns = ['trade_date', 'open', 'high', 'low', 'close','volume'] df.trade_date = pd.to_datetime(df.trade_d...
null
15,167
import backtrader as bt import pandas as pd import datetime import tushare as ts import json ts.set_token(token) df = ts.pro_bar(ts_code=code, adj='qfq',start_date=start_date, end_date=end_date) df = df[['trade_date', 'open', 'high', 'low', 'close','vol']] df.columns = ['trade_date', 'open', 'high', 'low',...
null
15,168
import glob import re from os import path import setuptools import torch from torch.utils.cpp_extension import CppExtension with open('damo/__init__.py', 'r') as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) with open('README.md', 'r', enc...
null
15,169
import copy import random import torch import torchvision.transforms as transforms from damo.augmentations.box_level_augs.gaussian_maps import _gaussian_map pixel_mean = [102.9801, 115.9465, 122.7717] def scale_area(box, height, width, scale_ratio=1.0): y1, x1, y2, x2 = box h, w = x2 - x1, y2 - y1 h_new, w_...
null
15,170
import random import numpy as np from .color_augs import color_aug_func from .geometric_augs import geometric_aug_func def _box_sample_prob(bbox, scale_ratios_splits, box_prob=0.3): color_aug_func = { 'AutoContrast': lambda x, level, target, scale_ratios_splits, box_sample_probs: _color_aug_func( x...
null
15,171
import random import torch import torch.nn.functional as F from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian def solarize(image, threshold=0.5): # For each pixel in the image, select the pixel # if the value is less than the threshold. # Otherwise, subtract 255 from the pixel. ...
null
15,172
import random import torch import torch.nn.functional as F from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian def solarize_add(image, addition=0, threshold=0.5): # For each pixel in the image less than threshold # we add 'addition' amount to it and then clip the # pixel value to be...
null
15,173
import random import torch import torch.nn.functional as F from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only i...
Equivalent of PIL Color.
15,174
import random import torch import torch.nn.functional as F from damo.augmentations.box_level_augs.gaussian_maps import _merge_gaussian def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only i...
null