uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
0017feb771c117ca108a1171
train
class
class PeriodicMemoryHandler(logging.handlers.MemoryHandler): last_flush = 0 flush_period = 10 def flush(self): super().flush() self.last_flush = time.time() def shouldFlush(self, record): """ Check for buffer full or a record at the flushLevel or higher. """ ...
class PeriodicMemoryHandler(logging.handlers.MemoryHandler):
last_flush = 0 flush_period = 10 def flush(self): super().flush() self.last_flush = time.time() def shouldFlush(self, record): """ Check for buffer full or a record at the flushLevel or higher. """ return (len(self.buffer) >= self.capacity) or \ ...
os import sys try: import django from django.db import OperationalError from django.conf import settings except ImportError: print("Warning: Django is not installed") from balsam.__version__ import __version__ # noqa class PeriodicMemoryHandler(logging.handlers.MemoryHandler):
64
64
108
10
53
mgierada/balsam
balsam/__init__.py
Python
PeriodicMemoryHandler
PeriodicMemoryHandler
18
32
18
18
6bcb2af8e83ff0407b3e66ad8ef2747906f40126
bigcode/the-stack
train
b40a40c3cd7cd052c40f23db
train
function
def config_logging(basename, filename=None, buffer_capacity=None): import multiprocessing_logging if filename is None: timestamp = datetime.now().strftime('%Y-%m-%d_%H%M%S') fname = f'{basename}_{timestamp}.log' else: fname = filename HANDLER_FILE = os.path.join(settings.LOGGING...
def config_logging(basename, filename=None, buffer_capacity=None):
import multiprocessing_logging if filename is None: timestamp = datetime.now().strftime('%Y-%m-%d_%H%M%S') fname = f'{basename}_{timestamp}.log' else: fname = filename HANDLER_FILE = os.path.join(settings.LOGGING_DIRECTORY, fname) formatter = logging.Formatter( '%(as...
(): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'balsam.django_config.settings' django.setup() _logger = logging.getLogger() _logger.setLevel(logging.DEBUG) _logger = logging.getLogger(__name__) _logger.setLevel(logging.DEBUG) def config_logging(basename, filename=None, buff...
71
71
239
14
57
mgierada/balsam
balsam/__init__.py
Python
config_logging
config_logging
47
74
47
47
3546ddbfe3d4e7afa23d042418f4a1ae9d0ee141
bigcode/the-stack
train
f01e6740c808873e2bf2fd9f
train
function
def log_uncaught_exceptions(exctype, value, tb): if isinstance(value, OperationalError) and not settings.DATABASES['default']['PORT']: _logger.error("Balsam OperationalError: No DB is currently active") _logger.error("Please use `source balsamactivate` to activate a Balsam DB") _logger.error...
def log_uncaught_exceptions(exctype, value, tb):
if isinstance(value, OperationalError) and not settings.DATABASES['default']['PORT']: _logger.error("Balsam OperationalError: No DB is currently active") _logger.error("Please use `source balsamactivate` to activate a Balsam DB") _logger.error("Use `balsam which --list` for a listing of know...
mem_handler = PeriodicMemoryHandler(capacity=buffer_capacity, target=handler) mem_handler.setLevel(level) mem_handler.setFormatter(formatter) _logger.addHandler(mem_handler) multiprocessing_logging.install_mp_handler() return fname def log_uncaught_exceptions(exctype, value, tb):
64
64
131
13
50
mgierada/balsam
balsam/__init__.py
Python
log_uncaught_exceptions
log_uncaught_exceptions
77
84
77
77
1f4c31e15b90dfcd6432f1ebaec8e3f80dedb373
bigcode/the-stack
train
4f769accdabbdac8f313b00b
train
function
def setup(): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'balsam.django_config.settings' django.setup()
def setup():
if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'balsam.django_config.settings' django.setup()
, record): """ Check for buffer full or a record at the flushLevel or higher. """ return (len(self.buffer) >= self.capacity) or \ (record.levelno >= self.flushLevel) or \ (time.time() - self.last_flush > self.flush_period) def setup():
64
64
33
3
61
mgierada/balsam
balsam/__init__.py
Python
setup
setup
35
38
35
35
db0f8ad4570f42220bed4ccda2ac492ad3b8593b
bigcode/the-stack
train
0bc1b297e398f0e91a9b794b
train
class
class RayOp(object): r"""Linear operator that performs for any v(x) h[i1,...,ir] = \int_R[i1,...,ir] ds M(x) v(x) grid : tuple of ndim Tensors specifying grid coordinates used for interpolation M : the function over V to integrate, defined on the *grid* rays : Tensor with *r* ray index dim...
class RayOp(object):
r"""Linear operator that performs for any v(x) h[i1,...,ir] = \int_R[i1,...,ir] ds M(x) v(x) grid : tuple of ndim Tensors specifying grid coordinates used for interpolation M : the function over V to integrate, defined on the *grid* rays : Tensor with *r* ray index dimensions and last dim ...
import tensorflow as tf import numpy as np from ionotomo.settings import TFSettings from ionotomo.tomography.interpolation import RegularGridInterpolator from ionotomo.tomography.integrate import simps class RayOp(object):
49
201
671
5
43
Joshuaalbert/IonoTomo
src/ionotomo/tomography/linear_operators.py
Python
RayOp
RayOp
7
73
7
7
c01126778d9700ab411db0b783c33694c185ec8a
bigcode/the-stack
train
1aeaf774ec03238a3447b45a
train
class
class TECForwardEquation(RayOp): def __init__(self,i0, grid,M,rays,dx = None, weight = None, transpose = False, dtype=TFSettings.tf_float): super(TECForwardEquation,self).__init__(grid,M,rays,dx, weight, transpose, dtype) self.i0 = tf.cast(i0,TFSettings.tf_int) ...
class TECForwardEquation(RayOp):
def __init__(self,i0, grid,M,rays,dx = None, weight = None, transpose = False, dtype=TFSettings.tf_float): super(TECForwardEquation,self).__init__(grid,M,rays,dx, weight, transpose, dtype) self.i0 = tf.cast(i0,TFSettings.tf_int) def matmul(self,x,adjoint=False...
.grid,Ax,method='linear') if self.weight is None: Ax = Ax(tf.unstack(self.rays,axis=-2)) else: Ax = self.weight*Ax(tf.unstack(self.rays,axis=-2)) Ax = simps(Ax, self.dx,axis = -1) return Ax class TECForwardEquation(RayOp):
79
79
265
8
70
Joshuaalbert/IonoTomo
src/ionotomo/tomography/linear_operators.py
Python
TECForwardEquation
TECForwardEquation
75
98
75
75
530d79d67e50b753c59d2ba1e28ec483906cdaab
bigcode/the-stack
train
f87c7ff4ecfbcac2d6b36cae
train
class
class IndexCallable: """Provide getitem syntax for functions >>> def inc(x): ... return x + 1 >>> I = IndexCallable(inc) >>> I[3] 4 """ __slots__ = ("fn",) def __init__(self, fn): self.fn = fn def __getitem__(self, key): return self.fn(key)
class IndexCallable:
"""Provide getitem syntax for functions >>> def inc(x): ... return x + 1 >>> I = IndexCallable(inc) >>> I[3] 4 """ __slots__ = ("fn",) def __init__(self, fn): self.fn = fn def __getitem__(self, key): return self.fn(key)
_cwd = os.getcwd() os.chdir(new_cwd) try: yield finally: os.chdir(old_cwd) @contextmanager def tmp_cwd(dir=None): with tmpdir(dir) as dirname: with changed_cwd(dirname): yield dirname class IndexCallable:
64
64
88
4
59
nordange/dask
dask/utils.py
Python
IndexCallable
IndexCallable
276
293
276
276
8b30f366afd51c8ccd7d616e2a56ea274ca0b81c
bigcode/the-stack
train
ac92f7fc6b5b77f10817c20b
train
class
class methodcaller: """ Return a callable object that calls the given method on its operand. Unlike the builtin `operator.methodcaller`, instances of this class are cached and arguments are passed at call time instead of build time. """ __slots__ = ("method",) method: str @property ...
class methodcaller:
""" Return a callable object that calls the given method on its operand. Unlike the builtin `operator.methodcaller`, instances of this class are cached and arguments are passed at call time instead of build time. """ __slots__ = ("method",) method: str @property def func(self) -> ...
bar, header, bar, data, bar]) def put_lines(buf, lines): if any(not isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write("\n".join(lines)) _method_cache: dict[str, methodcaller] = {} class methodcaller:
67
68
229
4
63
nordange/dask
dask/utils.py
Python
methodcaller
methodcaller
992
1,026
992
992
c79610ff3f04ad1165e246baaa219e2d80b65a91
bigcode/the-stack
train
810b8b4a521ae292e826a9b0
train
function
def deepmap(func, *seqs): """Apply function inside nested lists >>> inc = lambda x: x + 1 >>> deepmap(inc, [[1, 2], [3, 4]]) [[2, 3], [4, 5]] >>> add = lambda x, y: x + y >>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]]) [[11, 22], [33, 44]] """ if isinstance(seqs[0], (list,...
def deepmap(func, *seqs):
"""Apply function inside nested lists >>> inc = lambda x: x + 1 >>> deepmap(inc, [[1, 2], [3, 4]]) [[2, 3], [4, 5]] >>> add = lambda x, y: x + y >>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]]) [[11, 22], [33, 44]] """ if isinstance(seqs[0], (list, Iterator)): retur...
: msg = message @functools.wraps(func) def wrapper(*args, **kwargs): warnings.warn(msg, category=category, stacklevel=2) return func(*args, **kwargs) return wrapper return decorator def deepmap(func, *seqs):
64
64
160
9
54
nordange/dask
dask/utils.py
Python
deepmap
deepmap
107
121
107
107
ef6ee3e7cfd7fa9bf58d182d9eb1ca19e37c4a24
bigcode/the-stack
train
5eb69dc3d051abdde9ea8d91
train
function
def skip_doctest(doc): if doc is None: return "" return "\n".join([_skip_doctest(line) for line in doc.split("\n")])
def skip_doctest(doc):
if doc is None: return "" return "\n".join([_skip_doctest(line) for line in doc.split("\n")])
elif ">>>" in stripped and "+SKIP" not in stripped: if "# doctest:" in line: return line + ", +SKIP" else: return line + " # doctest: +SKIP" else: return line def skip_doctest(doc):
64
64
39
7
56
nordange/dask
dask/utils.py
Python
skip_doctest
skip_doctest
641
644
641
641
f4ae8103dd17e02c84ae9c11029c0619df43a1cb
bigcode/the-stack
train
1e461431cb591235bb8ae9c7
train
function
def typename(typ, short=False): """ Return the name of a type Examples -------- >>> typename(int) 'int' >>> from dask.core import literal >>> typename(literal) 'dask.core.literal' >>> typename(literal, short=True) 'dask.literal' """ if not isinstance(typ, type): ...
def typename(typ, short=False):
""" Return the name of a type Examples -------- >>> typename(int) 'int' >>> from dask.core import literal >>> typename(literal) 'dask.core.literal' >>> typename(literal, short=True) 'dask.literal' """ if not isinstance(typ, type): return typename(type(typ)) ...
(func.pyfunc))[:50] # All other callables try: name = func.__name__ if name == "<lambda>": return "lambda" return name[:50] except AttributeError: return str(func)[:50] def typename(typ, short=False):
64
64
164
8
56
nordange/dask
dask/utils.py
Python
typename
typename
852
879
852
852
07c95012912579ba90b483a127d536d883ee62fc
bigcode/the-stack
train
ee0bfc0e0c3192e6b65f1dc9
train
function
def iter_chunks(sizes, max_size): """Split sizes into chunks of total max_size each Parameters ---------- sizes : iterable of numbers The sizes to be chunked max_size : number Maximum total size per chunk. It must be greater or equal than each size in sizes """ chunk...
def iter_chunks(sizes, max_size):
"""Split sizes into chunks of total max_size each Parameters ---------- sizes : iterable of numbers The sizes to be chunked max_size : number Maximum total size per chunk. It must be greater or equal than each size in sizes """ chunk, chunk_sum = [], 0 iter_sizes...
parameters except Exception: return False def ndimlist(seq): if not isinstance(seq, (list, tuple)): return 0 elif not seq: return 1 else: return 1 + ndimlist(seq[0]) def iter_chunks(sizes, max_size):
64
64
169
9
55
nordange/dask
dask/utils.py
Python
iter_chunks
iter_chunks
1,631
1,656
1,631
1,631
e49c412123fb6734b539da9d687abb7a07e92195
bigcode/the-stack
train
dce5ab043f82c0dc74782f93
train
function
def get_scheduler_lock(collection=None, scheduler=None): """Get an instance of the appropriate lock for a certain situation based on scheduler used.""" from . import multiprocessing from .base import get_scheduler actual_get = get_scheduler(collections=[collection], scheduler=scheduler) if act...
def get_scheduler_lock(collection=None, scheduler=None):
"""Get an instance of the appropriate lock for a certain situation based on scheduler used.""" from . import multiprocessing from .base import get_scheduler actual_get = get_scheduler(collections=[collection], scheduler=scheduler) if actual_get == multiprocessing.get: return multiproce...
return self.token def __setstate__(self, token): self.__init__(token) def __str__(self): return f"<{self.__class__.__name__}: {self.token}>" __repr__ = __str__ def get_scheduler_lock(collection=None, scheduler=None):
63
64
82
10
53
nordange/dask
dask/utils.py
Python
get_scheduler_lock
get_scheduler_lock
1,135
1,146
1,135
1,135
36914fc35ac89405b3362131997facf453e78272
bigcode/the-stack
train
53bfd3c51567cf69f31ccde2
train
function
def has_keyword(func, keyword): try: return keyword in inspect.signature(func).parameters except Exception: return False
def has_keyword(func, keyword):
try: return keyword in inspect.signature(func).parameters except Exception: return False
prefix = s[:index] suffix = s[index:] or default n = float(prefix) multiplier = timedelta_sizes[suffix.lower()] result = n * multiplier if int(result) == result: result = int(result) return result def has_keyword(func, keyword):
64
64
28
7
56
nordange/dask
dask/utils.py
Python
has_keyword
has_keyword
1,615
1,619
1,615
1,615
e20085ca7c02626a033d3dc4ff4eea2c99f5885c
bigcode/the-stack
train
12915f859a280b3771885c53
train
function
def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i i...
def asciitable(columns, rows):
"""Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns...
def memory_repr(num): for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f} {x}" num /= 1024.0 def asciitable(columns, rows):
64
64
207
7
56
nordange/dask
dask/utils.py
Python
asciitable
asciitable
962
980
962
962
26d2876e9e4caba76ec2b0cfeddc0c565fb5e4a7
bigcode/the-stack
train
b9e3724b4e4562290286d7aa
train
function
def _deprecated( *, version: str | None = None, after_version: str | None = None, message: str | None = None, use_instead: str | None = None, category: type[Warning] = FutureWarning, ): """Decorator to mark a function as deprecated Parameters ---------- version : str, optional ...
def _deprecated( *, version: str | None = None, after_version: str | None = None, message: str | None = None, use_instead: str | None = None, category: type[Warning] = FutureWarning, ):
"""Decorator to mark a function as deprecated Parameters ---------- version : str, optional Version of Dask in which the function was deprecated. If specified, the version will be included in the default warning message. This should no longer be used after the introduction of au...
from .core import get_deps K = TypeVar("K") V = TypeVar("V") system_encoding = sys.getdefaultencoding() if system_encoding == "ascii": system_encoding = "utf-8" def apply(func, args, kwargs=None): if kwargs: return func(*args, **kwargs) else: return func(*args) def _deprecated( *, ...
134
134
448
57
77
nordange/dask
dask/utils.py
Python
_deprecated
_deprecated
44
104
44
51
d3901cd975de0e4e24cf7d15b7961cdf3d615331
bigcode/the-stack
train
4c2384643a67fc294239e2aa
train
function
def random_state_data(n, random_state=None): """Return a list of arrays that can initialize ``np.random.RandomState``. Parameters ---------- n : int Number of arrays to return. random_state : int or np.random.RandomState, optional If an int, is used to seed a new ``RandomState``...
def random_state_data(n, random_state=None):
"""Return a list of arrays that can initialize ``np.random.RandomState``. Parameters ---------- n : int Number of arrays to return. random_state : int or np.random.RandomState, optional If an int, is used to seed a new ``RandomState``. """ import numpy as np if not ...
) out = np.empty(n, dtype="i1") for i, (low, high) in enumerate(zip(cp[:-1], cp[1:])): out[(x >= low) & (x < high)] = i return out def random_state_data(n, random_state=None):
64
64
184
10
53
nordange/dask
dask/utils.py
Python
random_state_data
random_state_data
374
395
374
374
6b4a07aaff478a71afafdeaa2f9ce605c4a31e7e
bigcode/the-stack
train
15e14a5cef4a91e084ffd6aa
train
function
def format_time_ago(n: datetime) -> str: """Calculate a '3 hours ago' type string from a Python datetime. Examples -------- >>> from datetime import datetime, timedelta >>> now = datetime.now() >>> format_time_ago(now) 'Just now' >>> past = datetime.now() - timedelta(minutes=1) >>...
def format_time_ago(n: datetime) -> str:
"""Calculate a '3 hours ago' type string from a Python datetime. Examples -------- >>> from datetime import datetime, timedelta >>> now = datetime.now() >>> format_time_ago(now) 'Just now' >>> past = datetime.now() - timedelta(minutes=1) >>> format_time_ago(past) '1 minute ago...
format integers as time >>> from dask.utils import format_time >>> format_time(1) '1.00 s' >>> format_time(0.001234) '1.23 ms' >>> format_time(0.00012345) '123.45 us' >>> format_time(123.456) '123.46 s' """ if n >= 1: return "%.2f s" % n if n >= 1e-3: ret...
153
153
512
12
141
nordange/dask
dask/utils.py
Python
format_time_ago
format_time_ago
1,445
1,512
1,445
1,445
af9c6c1896ea8b90a3ae7ffed9dbc050bd97be0b
bigcode/the-stack
train
eab21af7f1198b4341871e5b
train
function
def ndeepmap(n, func, seq): """Call a function on every element within a nested container >>> def inc(x): ... return x + 1 >>> L = [[1, 2], [3, 4, 5]] >>> ndeepmap(2, inc, L) [[2, 3], [4, 5, 6]] """ if n == 1: return [func(item) for item in seq] elif n > 1: retur...
def ndeepmap(n, func, seq):
"""Call a function on every element within a nested container >>> def inc(x): ... return x + 1 >>> L = [[1, 2], [3, 4, 5]] >>> ndeepmap(2, inc, L) [[2, 3], [4, 5, 6]] """ if n == 1: return [func(item) for item in seq] elif n > 1: return [ndeepmap(n - 1, func, ite...
, seq): if not seq: return seq n = 0 tmp = seq while isinstance(tmp, list): n += 1 tmp = tmp[0] return ndeepmap(n, func, seq) def ndeepmap(n, func, seq):
64
64
154
10
54
nordange/dask
dask/utils.py
Python
ndeepmap
ndeepmap
137
153
137
137
726d0eca7c4d435eebc1ca2ee7c18ce3cdad333e
bigcode/the-stack
train
2faf0790dc01149d7e014a61
train
function
@_deprecated() def homogeneous_deepmap(func, seq): if not seq: return seq n = 0 tmp = seq while isinstance(tmp, list): n += 1 tmp = tmp[0] return ndeepmap(n, func, seq)
@_deprecated() def homogeneous_deepmap(func, seq):
if not seq: return seq n = 0 tmp = seq while isinstance(tmp, list): n += 1 tmp = tmp[0] return ndeepmap(n, func, seq)
22], [33, 44]] """ if isinstance(seqs[0], (list, Iterator)): return [deepmap(func, *items) for items in zip(*seqs)] else: return func(*seqs) @_deprecated() def homogeneous_deepmap(func, seq):
64
64
64
13
51
nordange/dask
dask/utils.py
Python
homogeneous_deepmap
homogeneous_deepmap
124
134
124
125
4a7bd4d0b91540edc7e89d7b064b52d018c2cefe
bigcode/the-stack
train
afd02a4f725dc6c928466045
train
function
def apply(func, args, kwargs=None): if kwargs: return func(*args, **kwargs) else: return func(*args)
def apply(func, args, kwargs=None):
if kwargs: return func(*args, **kwargs) else: return func(*args)
Dictionary import tlz as toolz from .core import get_deps K = TypeVar("K") V = TypeVar("V") system_encoding = sys.getdefaultencoding() if system_encoding == "ascii": system_encoding = "utf-8" def apply(func, args, kwargs=None):
64
64
31
9
55
nordange/dask
dask/utils.py
Python
apply
apply
37
41
37
37
a55e9466cb9e41e1fb233243b708e5f6fbf43847
bigcode/the-stack
train
3e5d930886ba3217c0ff3be9
train
function
def import_required(mod_name, error_msg): """Attempt to import a required dependency. Raises a RuntimeError if the requested module is not available. """ try: return import_module(mod_name) except ImportError as e: raise RuntimeError(error_msg) from e
def import_required(mod_name, error_msg):
"""Attempt to import a required dependency. Raises a RuntimeError if the requested module is not available. """ try: return import_module(mod_name) except ImportError as e: raise RuntimeError(error_msg) from e
) for item in seq] elif n > 1: return [ndeepmap(n - 1, func, item) for item in seq] elif isinstance(seq, list): return func(seq[0]) else: return func(seq) def import_required(mod_name, error_msg):
64
64
60
9
55
nordange/dask
dask/utils.py
Python
import_required
import_required
156
164
156
156
dab6ce6701e49010f8aef269e32b95076b46a10d
bigcode/the-stack
train
4e7681697f6f0c556ac53ece
train
class
class SerializableLock: """A Serializable per-process Lock This wraps a normal ``threading.Lock`` object and satisfies the same interface. However, this lock can also be serialized and sent to different processes. It will not block concurrent operations between processes (for this you should look...
class SerializableLock:
"""A Serializable per-process Lock This wraps a normal ``threading.Lock`` object and satisfies the same interface. However, this lock can also be serialized and sent to different processes. It will not block concurrent operations between processes (for this you should look at ``multiprocessing.Lo...
itemgetter, (self.index,)) def __eq__(self, other): return type(self) is type(other) and self.index == other.index class MethodCache: """Attribute access on this object returns a methodcaller for that attribute. Examples -------- >>> a = [1, 3, 3] >>> M.count(a, 3) == a.count(3) ...
132
132
441
4
128
nordange/dask
dask/utils.py
Python
SerializableLock
SerializableLock
1,068
1,132
1,068
1,068
be9402f2664ad47fd3682665924d3ba70ad14d80
bigcode/the-stack
train
d7ca1c7a900518c34f46b3ce
train
function
def is_arraylike(x): """Is this object a numpy array or something similar? This function tests specifically for an object that already has array attributes (e.g. np.ndarray, dask.array.Array, cupy.ndarray, sparse.COO), **NOT** for something that can be coerced into an array object (e.g. Python list...
def is_arraylike(x):
"""Is this object a numpy array or something similar? This function tests specifically for an object that already has array attributes (e.g. np.ndarray, dask.array.Array, cupy.ndarray, sparse.COO), **NOT** for something that can be coerced into an array object (e.g. Python lists and tuples). It is ...
"""Must return a method used by binary operator""" raise NotImplementedError def partial_by_order(*args, **kwargs): """ >>> from operator import add >>> partial_by_order(5, function=add, other=[(1, 10)]) 15 """ function = kwargs.pop("function") other = kwargs.pop("other") arg...
116
116
389
6
110
nordange/dask
dask/utils.py
Python
is_arraylike
is_arraylike
1,228
1,268
1,228
1,228
f4476bc4b1e80a825e76fb2fb9aaeeadbd6fd096
bigcode/the-stack
train
dace8fc915c17a83d75a481c
train
function
def cached_cumsum(seq, initial_zero=False): """Compute :meth:`toolz.accumulate` with caching. Caching is by the identify of `seq` rather than the value. It is thus important that `seq` is a tuple of immutable objects, and this function is intended for use where `seq` is a value that will persist (gener...
def cached_cumsum(seq, initial_zero=False):
"""Compute :meth:`toolz.accumulate` with caching. Caching is by the identify of `seq` rather than the value. It is thus important that `seq` is a tuple of immutable objects, and this function is intended for use where `seq` is a value that will persist (generally block sizes). Parameters -...
, initial_zero): if isinstance(seq, _HashIdWrapper): seq = seq.wrapped if initial_zero: return tuple(toolz.accumulate(add, seq, 0)) else: return tuple(toolz.accumulate(add, seq)) def cached_cumsum(seq, initial_zero=False):
64
64
213
10
54
nordange/dask
dask/utils.py
Python
cached_cumsum
cached_cumsum
1,904
1,930
1,904
1,904
523ffd7fb99076d3ee53c3e708846e7be575af54
bigcode/the-stack
train
c08281178671c329dd975277
train
function
def extra_titles(doc): lines = doc.split("\n") titles = { i: lines[i].strip() for i in range(len(lines) - 1) if lines[i + 1].strip() and all(c == "-" for c in lines[i + 1].strip()) } seen = set() for i, title in sorted(titles.items()): if title in seen: n...
def extra_titles(doc):
lines = doc.split("\n") titles = { i: lines[i].strip() for i in range(len(lines) - 1) if lines[i + 1].strip() and all(c == "-" for c in lines[i + 1].strip()) } seen = set() for i, title in sorted(titles.items()): if title in seen: new_title = "Extra " + t...
return line + " # doctest: +SKIP" else: return line def skip_doctest(doc): if doc is None: return "" return "\n".join([_skip_doctest(line) for line in doc.split("\n")]) def extra_titles(doc):
64
64
154
5
59
nordange/dask
dask/utils.py
Python
extra_titles
extra_titles
647
664
647
647
5c6731d59b4b7fa4186cd451e952da30eff5fbb8
bigcode/the-stack
train
3f7bec26b4d994b2944635a1
train
function
def takes_multiple_arguments(func, varargs=True): """Does this function take multiple arguments? >>> def f(x, y): pass >>> takes_multiple_arguments(f) True >>> def f(x): pass >>> takes_multiple_arguments(f) False >>> def f(x, y=None): pass >>> takes_multiple_arguments(f) False...
def takes_multiple_arguments(func, varargs=True):
"""Does this function take multiple arguments? >>> def f(x, y): pass >>> takes_multiple_arguments(f) True >>> def f(x): pass >>> takes_multiple_arguments(f) False >>> def f(x, y=None): pass >>> takes_multiple_arguments(f) False >>> def f(*args): pass >>> takes_multipl...
pec that works with partial and warps.""" if isinstance(func, functools.partial): return getargspec(func.func) func = getattr(func, "__wrapped__", func) if isinstance(func, type): return inspect.getfullargspec(func.__init__) else: return inspect.getfullargspec(func) def takes_mu...
76
76
255
10
66
nordange/dask
dask/utils.py
Python
takes_multiple_arguments
takes_multiple_arguments
485
529
485
485
33442999befaa9b7d298b0d1de510df1fc2f3217
bigcode/the-stack
train
e831eedfdeb1566714846533
train
function
def stringify_collection_keys(obj): """Convert all collection keys in ``obj`` to strings. This is a specialized version of ``stringify()`` that only converts keys of the form: ``("a string", ...)`` """ typ = type(obj) if typ is tuple and obj: obj0 = obj[0] if type(obj0) is str ...
def stringify_collection_keys(obj):
"""Convert all collection keys in ``obj`` to strings. This is a specialized version of ``stringify()`` that only converts keys of the form: ``("a string", ...)`` """ typ = type(obj) if typ is tuple and obj: obj0 = obj[0] if type(obj0) is str or type(obj0) is bytes: ...
stringify(obj) except TypeError: # `obj` not hashable pass if typ is tuple: # If the tuple itself isn't a key, check its elements return tuple(stringify(v, exclusive) for v in obj) return obj def stringify_collection_keys(obj):
64
64
203
6
57
nordange/dask
dask/utils.py
Python
stringify_collection_keys
stringify_collection_keys
1,787
1,807
1,787
1,787
e26ae4db3f1d20bed7d4852caedff9885290cfb3
bigcode/the-stack
train
b355b0e7f4a47a1ed91edfea
train
function
def key_split(s): """ >>> key_split('x') 'x' >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split("('x-2', 1)") 'x' >>> key_split('hello-world-1') 'hello-world' >>> key_split(b'hello-world-1') 'hello-world' >>> ...
def key_split(s):
""" >>> key_split('x') 'x' >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split("('x-2', 1)") 'x' >>> key_split('hello-world-1') 'hello-world' >>> key_split(b'hello-world-1') 'hello-world' >>> key_split('ae05086...
size in sizes """ chunk, chunk_sum = [], 0 iter_sizes = iter(sizes) size = next(iter_sizes, None) while size is not None: assert size <= max_size if chunk_sum + size <= max_size: chunk.append(size) chunk_sum += size size = next(iter_sizes, None) ...
121
121
404
5
116
nordange/dask
dask/utils.py
Python
key_split
key_split
1,662
1,713
1,662
1,662
c4977d0035dcee96d7011e25dbf1284590cc7e67
bigcode/the-stack
train
28282465fc7736cc04aa013a
train
function
@contextmanager def changed_cwd(new_cwd): old_cwd = os.getcwd() os.chdir(new_cwd) try: yield finally: os.chdir(old_cwd)
@contextmanager def changed_cwd(new_cwd):
old_cwd = os.getcwd() os.chdir(new_cwd) try: yield finally: os.chdir(old_cwd)
"): with tmpfile(extension=extension) as filename: f = open(filename, mode=mode) try: f.write(text) finally: try: f.close() except AttributeError: pass yield filename @contextmanager def changed_cwd(new_cwd):
64
64
43
12
51
nordange/dask
dask/utils.py
Python
changed_cwd
changed_cwd
259
266
259
260
d246eb4bd209cb7ad31487a257d8d7d51cfd5a37
bigcode/the-stack
train
482decdb4ea8683f8ca1a881
train
function
def ensure_bytes(s): """Turn string or bytes to bytes >>> ensure_bytes('123') b'123' >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ if isinstance(s, bytes): return s if hasattr(s, "encode"): return s.encode() msg = "Object %s is neither a ...
def ensure_bytes(s):
"""Turn string or bytes to bytes >>> ensure_bytes('123') b'123' >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ if isinstance(s, bytes): return s if hasattr(s, "encode"): return s.encode() msg = "Object %s is neither a bytes object nor has ...
builtins": return typ.__name__ else: if short: module, *_ = typ.__module__.split(".") else: module = typ.__module__ return module + "." + typ.__name__ except AttributeError: return str(typ) def ensure_bytes(s):
64
64
103
5
59
nordange/dask
dask/utils.py
Python
ensure_bytes
ensure_bytes
882
897
882
882
2952d736478a1d808e3d7f060fadbefc8c4a0427
bigcode/the-stack
train
b626603d97204c207610087c
train
function
def pseudorandom(n, p, random_state=None): """Pseudorandom array of integer indexes >>> pseudorandom(5, [0.5, 0.5], random_state=123) array([1, 0, 0, 1, 1], dtype=int8) >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], random_state=5) array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8) """ import n...
def pseudorandom(n, p, random_state=None):
"""Pseudorandom array of integer indexes >>> pseudorandom(5, [0.5, 0.5], random_state=123) array([1, 0, 0, 1, 1], dtype=int8) >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], random_state=5) array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8) """ import numpy as np p = list(p) cp = np.cum...
]] >>> seq = iter(map(iter, data)) >>> concrete(seq) [[1, 2], [3, 4]] """ if isinstance(seq, Iterator): seq = list(seq) if isinstance(seq, (tuple, list)): seq = list(map(concrete, seq)) return seq def pseudorandom(n, p, random_state=None):
80
80
268
12
67
nordange/dask
dask/utils.py
Python
pseudorandom
pseudorandom
347
371
347
347
137c946a799de297720084a8453a9125f1dd33f3
bigcode/the-stack
train
840b255899920346edd651e5
train
function
def digit(n, k, base): """ >>> digit(1234, 0, 10) 4 >>> digit(1234, 1, 10) 3 >>> digit(1234, 2, 10) 2 >>> digit(1234, 3, 10) 1 """ return n // base**k % base
def digit(n, k, base):
""" >>> digit(1234, 0, 10) 4 >>> digit(1234, 1, 10) 3 >>> digit(1234, 2, 10) 2 >>> digit(1234, 3, 10) 1 """ return n // base**k % base
_unicode(b'123') '123' """ if isinstance(s, str): return s if hasattr(s, "decode"): return s.decode() raise TypeError(f"Object {s} is neither a str object nor has an decode method") def digit(n, k, base):
64
64
90
8
56
nordange/dask
dask/utils.py
Python
digit
digit
915
927
915
915
99ad87408730a64807ca32b50d6ff77bae3e4b7a
bigcode/the-stack
train
09b0c8a5653a87220ebba71a
train
function
def ensure_not_exists(filename): """ Ensure that a file does not exist. """ try: os.unlink(filename) except OSError as e: if e.errno != ENOENT: raise
def ensure_not_exists(filename):
""" Ensure that a file does not exist. """ try: os.unlink(filename) except OSError as e: if e.errno != ENOENT: raise
return meth(arg, *args, **kwargs) @property def __doc__(self): try: func = self.dispatch(object) return func.__doc__ except TypeError: return "Single Dispatch for %s" % self.__name__ def ensure_not_exists(filename):
63
64
47
6
57
nordange/dask
dask/utils.py
Python
ensure_not_exists
ensure_not_exists
616
624
616
616
db171b43600f4bd9a8ea37c30ac9d45706499cb7
bigcode/the-stack
train
5d5719111a5a1021902f0664
train
function
def concrete(seq): """Make nested iterators concrete lists >>> data = [[1, 2], [3, 4]] >>> seq = iter(map(iter, data)) >>> concrete(seq) [[1, 2], [3, 4]] """ if isinstance(seq, Iterator): seq = list(seq) if isinstance(seq, (tuple, list)): seq = list(map(concrete, seq)) ...
def concrete(seq):
"""Make nested iterators concrete lists >>> data = [[1, 2], [3, 4]] >>> seq = iter(map(iter, data)) >>> concrete(seq) [[1, 2], [3, 4]] """ if isinstance(seq, Iterator): seq = list(seq) if isinstance(seq, (tuple, list)): seq = list(map(concrete, seq)) return seq
w" + mode) try: f.write(text) finally: try: f.close() except AttributeError: pass yield list(d) for filename in d: if os.path.exists(filename): with suppress(OSEr...
64
64
96
4
60
nordange/dask
dask/utils.py
Python
concrete
concrete
332
344
332
332
fedd2d14b03c7881bed143e279f34942d6ffa9cc
bigcode/the-stack
train
71f3767c4372eebee8da9b6a
train
function
@contextmanager def filetext(text, extension="", open=open, mode="w"): with tmpfile(extension=extension) as filename: f = open(filename, mode=mode) try: f.write(text) finally: try: f.close() except AttributeError: pass ...
@contextmanager def filetext(text, extension="", open=open, mode="w"):
with tmpfile(extension=extension) as filename: f = open(filename, mode=mode) try: f.write(text) finally: try: f.close() except AttributeError: pass yield filename
yield dirname finally: if os.path.exists(dirname): if os.path.isdir(dirname): with suppress(OSError): shutil.rmtree(dirname) else: with suppress(OSError): os.remove(dirname) @contextmanager def filetext(text, ex...
64
64
69
18
46
nordange/dask
dask/utils.py
Python
filetext
filetext
244
256
244
245
7fecd7af972c9c1532772ff8b08a9099239ca35b
bigcode/the-stack
train
0af796626d4a439216f008c5
train
class
class _HashIdWrapper: """Hash and compare a wrapped object by identity instead of value""" def __init__(self, wrapped): self.wrapped = wrapped def __eq__(self, other): if not isinstance(other, _HashIdWrapper): return NotImplemented return self.wrapped is other.wrapped ...
class _HashIdWrapper:
"""Hash and compare a wrapped object by identity instead of value""" def __init__(self, wrapped): self.wrapped = wrapped def __eq__(self, other): if not isinstance(other, _HashIdWrapper): return NotImplemented return self.wrapped is other.wrapped def __ne__(self, o...
) from None return val class cached_property(_cached_property): """Read only version of functools.cached_property.""" def __set__(self, instance, val): """Raise an error when attempting to set a cached property.""" raise AttributeError("Can't set attribute") class _HashIdWrapper:
64
64
121
6
58
nordange/dask
dask/utils.py
Python
_HashIdWrapper
_HashIdWrapper
1,874
1,891
1,874
1,874
588426109d7c98bcc1ab9e28db945f9bd22e5a81
bigcode/the-stack
train
f1859e9171f97f44bad49c97
train
function
@functools.lru_cache() def _cumsum(seq, initial_zero): if isinstance(seq, _HashIdWrapper): seq = seq.wrapped if initial_zero: return tuple(toolz.accumulate(add, seq, 0)) else: return tuple(toolz.accumulate(add, seq))
@functools.lru_cache() def _cumsum(seq, initial_zero):
if isinstance(seq, _HashIdWrapper): seq = seq.wrapped if initial_zero: return tuple(toolz.accumulate(add, seq, 0)) else: return tuple(toolz.accumulate(add, seq))
ne__(self, other): if not isinstance(other, _HashIdWrapper): return NotImplemented return self.wrapped is not other.wrapped def __hash__(self): return id(self.wrapped) @functools.lru_cache() def _cumsum(seq, initial_zero):
64
64
67
17
47
nordange/dask
dask/utils.py
Python
_cumsum
_cumsum
1,894
1,901
1,894
1,895
9d3ca4ae7fd8439e97847957837893673889e257
bigcode/the-stack
train
f4171d23d96d2a4191a7bf9a
train
function
def natural_sort_key(s): """ Sorting `key` function for performing a natural sort on a collection of strings See https://en.wikipedia.org/wiki/Natural_sort_order Parameters ---------- s : str A string that is an element of the collection being sorted Returns ------- tu...
def natural_sort_key(s):
""" Sorting `key` function for performing a natural sort on a collection of strings See https://en.wikipedia.org/wiki/Natural_sort_order Parameters ---------- s : str A string that is an element of the collection being sorted Returns ------- tuple[str or int] T...
a Pandas Index""" typ = s.__class__ return ( all(hasattr(s, name) for name in ("name", "dtype")) and "index" in typ.__name__.lower() ) def is_cupy_type(x): # TODO: avoid explicit reference to CuPy return "cupy" in str(type(x)) def natural_sort_key(s):
81
81
272
6
75
nordange/dask
dask/utils.py
Python
natural_sort_key
natural_sort_key
1,311
1,337
1,311
1,311
374f73fd7c7fd58f41615ca96980cae392bb0151
bigcode/the-stack
train
b3a1419118c5cd6e33aa827c
train
function
def memory_repr(num): for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f} {x}" num /= 1024.0
def memory_repr(num):
for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f} {x}" num /= 1024.0
_deps(key): if not deps[key]: return 1 d = 1 + max(max_depth_by_deps(dep_key) for dep_key in deps[key]) return d return max(max_depth_by_deps(dep_key) for dep_key in deps.keys()) def memory_repr(num):
64
64
57
5
59
nordange/dask
dask/utils.py
Python
memory_repr
memory_repr
955
959
955
955
58ea93c14681a39045e57c55e74db4048cbc2f22
bigcode/the-stack
train
5ce346cadda2817ad8c3457e
train
function
def get_named_args(func): """Get all non ``*args/**kwargs`` arguments for a function""" s = inspect.signature(func) return [ n for n, p in s.parameters.items() if p.kind in [p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY, p.KEYWORD_ONLY] ]
def get_named_args(func):
"""Get all non ``*args/**kwargs`` arguments for a function""" s = inspect.signature(func) return [ n for n, p in s.parameters.items() if p.kind in [p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY, p.KEYWORD_ONLY] ]
, type) except Exception: is_constructor = False if varargs and spec.varargs: return True ndefaults = 0 if spec.defaults is None else len(spec.defaults) return len(spec.args) - ndefaults - is_constructor > 1 def get_named_args(func):
64
64
72
6
57
nordange/dask
dask/utils.py
Python
get_named_args
get_named_args
532
539
532
532
971500b6a3a88e7275161c6173d63224ed4e906c
bigcode/the-stack
train
bed6d8083c8cd4feab3ec5b5
train
function
def derived_from(original_klass, version=None, ua_args=None, skipblocks=0): """Decorator to attach original class's docstring to the wrapped method. The output structure will be: top line of docstring, disclaimer about this being auto-derived, any extra text associated with the method being patched, th...
def derived_from(original_klass, version=None, ua_args=None, skipblocks=0):
"""Decorator to attach original class's docstring to the wrapped method. The output structure will be: top line of docstring, disclaimer about this being auto-derived, any extra text associated with the method being patched, the body of the docstring and finally, the list of keywords that exist in ...
original_args = get_named_args(original_method) not_supported = [m for m in original_args if m not in method_args] except ValueError: not_supported = [] if len(ua_args) > 0: not_supported.extend(ua_args) if len(not_supported) > 0: doc = unsupported_arguments(doc, not_support...
115
115
384
19
95
nordange/dask
dask/utils.py
Python
derived_from
derived_from
769
817
769
769
fbdfa5a9b65283a8cfc235b48cc0680b19186b60
bigcode/the-stack
train
d868d15738bf3db71153ca36
train
function
def is_index_like(s): """Looks like a Pandas Index""" typ = s.__class__ return ( all(hasattr(s, name) for name in ("name", "dtype")) and "index" in typ.__name__.lower() )
def is_index_like(s):
"""Looks like a Pandas Index""" typ = s.__class__ return ( all(hasattr(s, name) for name in ("name", "dtype")) and "index" in typ.__name__.lower() )
return ( all(hasattr(typ, name) for name in ("groupby", "head", "mean")) and all(hasattr(s, name) for name in ("dtype", "name")) and "index" not in typ.__name__.lower() ) def is_index_like(s):
64
64
56
6
58
nordange/dask
dask/utils.py
Python
is_index_like
is_index_like
1,297
1,303
1,297
1,297
522936bd696832af0061abf9ee9fbe33a82c3aa4
bigcode/the-stack
train
4763921107230c15fa718c88
train
class
class Dispatch: """Simple single dispatch.""" def __init__(self, name=None): self._lookup = {} self._lazy = {} if name: self.__name__ = name def register(self, type, func=None): """Register dispatch of `func` on arguments of type `type`""" def wrapper(f...
class Dispatch:
"""Simple single dispatch.""" def __init__(self, name=None): self._lookup = {} self._lazy = {} if name: self.__name__ = name def register(self, type, func=None): """Register dispatch of `func` on arguments of type `type`""" def wrapper(func): ...
isinstance(func, type) except Exception: is_constructor = False if varargs and spec.varargs: return True ndefaults = 0 if spec.defaults is None else len(spec.defaults) return len(spec.args) - ndefaults - is_constructor > 1 def get_named_args(func): """Get all non ``*args/**kwarg...
135
136
455
3
132
nordange/dask
dask/utils.py
Python
Dispatch
Dispatch
542
613
542
542
93f704954d006bf64f629cbb3e4cbbb7a083d690
bigcode/the-stack
train
5ecd735bc14ff63b180bebb1
train
function
def factors(n): """Return the factors of an integer https://stackoverflow.com/a/6800214/616616 """ seq = ([i, n // i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0) return set(functools.reduce(list.__add__, seq))
def factors(n):
"""Return the factors of an integer https://stackoverflow.com/a/6800214/616616 """ seq = ([i, n // i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0) return set(functools.reduce(list.__add__, seq))
f2', 'f8', 'f9', 'f10', 'f11', 'f19', 'f20', 'f21'] """ return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", s)] def factors(n):
63
64
80
4
59
nordange/dask
dask/utils.py
Python
factors
factors
1,340
1,346
1,340
1,340
af388388804b256d6da2fae00e88143e61c012e4
bigcode/the-stack
train
06b3950c04121c41b538420c
train
function
def ndimlist(seq): if not isinstance(seq, (list, tuple)): return 0 elif not seq: return 1 else: return 1 + ndimlist(seq[0])
def ndimlist(seq):
if not isinstance(seq, (list, tuple)): return 0 elif not seq: return 1 else: return 1 + ndimlist(seq[0])
_sizes[suffix.lower()] result = n * multiplier if int(result) == result: result = int(result) return result def has_keyword(func, keyword): try: return keyword in inspect.signature(func).parameters except Exception: return False def ndimlist(seq):
64
64
45
5
58
nordange/dask
dask/utils.py
Python
ndimlist
ndimlist
1,622
1,628
1,622
1,622
fcdfe2b1ecbce5fe38927c8fd109e4821fdfee5b
bigcode/the-stack
train
d1e89046bb5bca2aeca9d7b0
train
function
def is_integer(i): """ >>> is_integer(6) True >>> is_integer(42.0) True >>> is_integer('abc') False """ return isinstance(i, Integral) or (isinstance(i, float) and i.is_integer())
def is_integer(i):
""" >>> is_integer(6) True >>> is_integer(42.0) True >>> is_integer('abc') False """ return isinstance(i, Integral) or (isinstance(i, float) and i.is_integer())
= random_state.bytes(624 * n * 4) # `n * 624` 32-bit integers l = list(np.frombuffer(random_data, dtype=np.uint32).reshape((n, -1))) assert len(l) == n return l def is_integer(i):
64
64
61
5
58
nordange/dask
dask/utils.py
Python
is_integer
is_integer
398
407
398
398
be9c3532a383f0f0294c0ff3c9e7e9c584cce5d6
bigcode/the-stack
train
84c045487ea71dc1ace60b87
train
function
def dependency_depth(dsk): deps, _ = get_deps(dsk) @lru_cache(maxsize=None) def max_depth_by_deps(key): if not deps[key]: return 1 d = 1 + max(max_depth_by_deps(dep_key) for dep_key in deps[key]) return d return max(max_depth_by_deps(dep_key) for dep_key in deps.ke...
def dependency_depth(dsk):
deps, _ = get_deps(dsk) @lru_cache(maxsize=None) def max_depth_by_deps(key): if not deps[key]: return 1 d = 1 + max(max_depth_by_deps(dep_key) for dep_key in deps[key]) return d return max(max_depth_by_deps(dep_key) for dep_key in deps.keys())
up, loc, val): """ >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L) def dependency_depth(dsk):
64
64
90
6
58
nordange/dask
dask/utils.py
Python
dependency_depth
dependency_depth
941
952
941
941
5fbaafd35d98381fd2688bc9ab91bc88b83e3b29
bigcode/the-stack
train
6db9fc2e8256bec60027ceeb
train
function
def stringify(obj, exclusive: Iterable | None = None): """Convert an object to a string If ``exclusive`` is specified, search through `obj` and convert values that are in ``exclusive``. Note that when searching through dictionaries, only values are converted, not the keys. Parameters ----...
def stringify(obj, exclusive: Iterable | None = None):
"""Convert an object to a string If ``exclusive`` is specified, search through `obj` and convert values that are in ``exclusive``. Note that when searching through dictionaries, only values are converted, not the keys. Parameters ---------- obj : Any Object (or values within) ...
not words[0][0].isalpha(): result = words[0].strip("_'()\"") else: result = words[0] for word in words[1:]: if word.isalpha() and not ( len(word) == 8 and hex_pattern.match(word) is not None ): result += "-" + word ...
165
165
550
12
153
nordange/dask
dask/utils.py
Python
stringify
stringify
1,716
1,784
1,716
1,716
72fc11b7f6e4cdaa85d5d968d3abe10d8de79ed4
bigcode/the-stack
train
37ded6ad91819b9725da6d2d
train
class
class MethodCache: """Attribute access on this object returns a methodcaller for that attribute. Examples -------- >>> a = [1, 3, 3] >>> M.count(a, 3) == a.count(3) True """ def __getattr__(self, item): return methodcaller(item) def __dir__(self): return list(_...
class MethodCache:
"""Attribute access on this object returns a methodcaller for that attribute. Examples -------- >>> a = [1, 3, 3] >>> M.count(a, 3) == a.count(3) True """ def __getattr__(self, item): return methodcaller(item) def __dir__(self): return list(_method_cache)
index def __call__(self, x): return x[self.index] def __reduce__(self): return (itemgetter, (self.index,)) def __eq__(self, other): return type(self) is type(other) and self.index == other.index class MethodCache:
64
64
90
4
59
nordange/dask
dask/utils.py
Python
MethodCache
MethodCache
1,047
1,062
1,047
1,047
e72414ffc08efa925c085789081a6c5e16aaddf5
bigcode/the-stack
train
dc9d393ec85d3ef0977bcde9
train
function
def is_series_like(s): """Looks like a Pandas Series""" typ = s.__class__ return ( all(hasattr(typ, name) for name in ("groupby", "head", "mean")) and all(hasattr(s, name) for name in ("dtype", "name")) and "index" not in typ.__name__.lower() )
def is_series_like(s):
"""Looks like a Pandas Series""" typ = s.__class__ return ( all(hasattr(typ, name) for name in ("groupby", "head", "mean")) and all(hasattr(s, name) for name in ("dtype", "name")) and "index" not in typ.__name__.lower() )
) for name in ("groupby", "head", "merge", "mean")) and all(hasattr(df, name) for name in ("dtypes", "columns")) and not any(hasattr(typ, name) for name in ("name", "dtype")) ) def is_series_like(s):
64
64
80
6
58
nordange/dask
dask/utils.py
Python
is_series_like
is_series_like
1,287
1,294
1,287
1,287
bfe32eb8537b36bc420202da18cf0ca443ec5bff
bigcode/the-stack
train
606f2768742aa61cb77d5f7c
train
function
def format_time(n): """format integers as time >>> from dask.utils import format_time >>> format_time(1) '1.00 s' >>> format_time(0.001234) '1.23 ms' >>> format_time(0.00012345) '123.45 us' >>> format_time(123.456) '123.46 s' """ if n >= 1: return "%.2f s" % n ...
def format_time(n):
"""format integers as time >>> from dask.utils import format_time >>> format_time(1) '1.00 s' >>> format_time(0.001234) '1.23 ms' >>> format_time(0.00012345) '123.45 us' >>> format_time(123.456) '123.46 s' """ if n >= 1: return "%.2f s" % n if n >= 1e-3: ...
byte_sizes.items()} byte_sizes.update({k[0]: v for k, v in byte_sizes.items() if k and "i" not in k}) byte_sizes.update({k[:-1]: v for k, v in byte_sizes.items() if k and "i" in k}) def format_time(n):
64
64
148
5
59
nordange/dask
dask/utils.py
Python
format_time
format_time
1,425
1,442
1,425
1,425
942d7ee01d3044174c80ebb1b0173151ce795023
bigcode/the-stack
train
62ea4d2c2ab4555978dc9eb9
train
function
def _derived_from(cls, method, ua_args=None, extra="", skipblocks=0): """Helper function for derived_from to ease testing""" ua_args = ua_args or [] # do not use wraps here, as it hides keyword arguments displayed # in the doc original_method = getattr(cls, method.__name__) if isinstance(origi...
def _derived_from(cls, method, ua_args=None, extra="", skipblocks=0):
"""Helper function for derived_from to ease testing""" ua_args = ua_args or [] # do not use wraps here, as it hides keyword arguments displayed # in the doc original_method = getattr(cls, method.__name__) if isinstance(original_method, property): # some things like SeriesGroupBy.unique...
doc.split("\n") for arg in args: subset = [ (i, line) for i, line in enumerate(lines) if re.match(r"^\s*" + arg + " ?:", line) ] if len(subset) == 1: [(i, line)] = subset lines[i] = line + " (Not supported in Dask)" return "\n...
111
111
371
19
92
nordange/dask
dask/utils.py
Python
_derived_from
_derived_from
719
766
719
719
2fb77507e7bdddc334eccf265d0d20672f889094
bigcode/the-stack
train
64a7989e59fcddb7d71fc0e2
train
function
def ensure_unicode(s): """Turn string or bytes to bytes >>> ensure_unicode('123') '123' >>> ensure_unicode(b'123') '123' """ if isinstance(s, str): return s if hasattr(s, "decode"): return s.decode() raise TypeError(f"Object {s} is neither a str object nor has an dec...
def ensure_unicode(s):
"""Turn string or bytes to bytes >>> ensure_unicode('123') '123' >>> ensure_unicode(b'123') '123' """ if isinstance(s, str): return s if hasattr(s, "decode"): return s.decode() raise TypeError(f"Object {s} is neither a str object nor has an decode method")
123') b'123' """ if isinstance(s, bytes): return s if hasattr(s, "encode"): return s.encode() msg = "Object %s is neither a bytes object nor has an encode method" raise TypeError(msg % s) def ensure_unicode(s):
64
64
84
5
59
nordange/dask
dask/utils.py
Python
ensure_unicode
ensure_unicode
900
912
900
900
47f2e3011e950fafb6b40a7050c521b82839dfb4
bigcode/the-stack
train
40a06e7e8f78d8bd2be83335
train
function
def _skip_doctest(line): # NumPy docstring contains cursor and comment only example stripped = line.strip() if stripped == ">>>" or stripped.startswith(">>> #"): return line elif ">>>" in stripped and "+SKIP" not in stripped: if "# doctest:" in line: return line + ", +SKIP" ...
def _skip_doctest(line): # NumPy docstring contains cursor and comment only example
stripped = line.strip() if stripped == ">>>" or stripped.startswith(">>> #"): return line elif ">>>" in stripped and "+SKIP" not in stripped: if "# doctest:" in line: return line + ", +SKIP" else: return line + " # doctest: +SKIP" else: return lin...
(filename): """ Ensure that a file does not exist. """ try: os.unlink(filename) except OSError as e: if e.errno != ENOENT: raise def _skip_doctest(line): # NumPy docstring contains cursor and comment only example
64
64
103
21
42
nordange/dask
dask/utils.py
Python
_skip_doctest
_skip_doctest
627
638
627
628
c18c18741ca381c86fe853cd66c7d8be9dc7c9d5
bigcode/the-stack
train
40a4e52d07e7db426709a76c
train
function
def put_lines(buf, lines): if any(not isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write("\n".join(lines))
def put_lines(buf, lines):
if any(not isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write("\n".join(lines))
bar = "+%s+" % "+".join("-" * (w + 2) for w in widths) data = "\n".join(row_template % r for r in rows) return "\n".join([bar, header, bar, data, bar]) def put_lines(buf, lines):
64
64
42
7
57
nordange/dask
dask/utils.py
Python
put_lines
put_lines
983
986
983
983
1fdc2ac0cbe5d85e75d260cbb0317e41cc1352c0
bigcode/the-stack
train
8efba54c80a83faefbf4ae40
train
class
class cached_property(_cached_property): """Read only version of functools.cached_property.""" def __set__(self, instance, val): """Raise an error when attempting to set a cached property.""" raise AttributeError("Can't set attribute")
class cached_property(_cached_property):
"""Read only version of functools.cached_property.""" def __set__(self, instance, val): """Raise an error when attempting to set a cached property.""" raise AttributeError("Can't set attribute")
msg = ( f"The '__dict__' attribute on {type(instance).__name__!r} instance " f"does not support item assignment for caching {self.attrname!r} property." ) raise TypeError(msg) from None r...
64
64
50
7
56
nordange/dask
dask/utils.py
Python
cached_property
cached_property
1,866
1,871
1,866
1,866
dc05bc9e6af27022fe2a397937a960ae91e09b2a
bigcode/the-stack
train
fb5665af7771952cf2ff3418
train
function
def ignore_warning(doc, cls, name, extra="", skipblocks=0): """Expand docstring by adding disclaimer and extra text""" import inspect if inspect.isclass(cls): l1 = "This docstring was copied from {}.{}.{}.\n\n".format( cls.__module__, cls.__name__, name, ...
def ignore_warning(doc, cls, name, extra="", skipblocks=0):
"""Expand docstring by adding disclaimer and extra text""" import inspect if inspect.isclass(cls): l1 = "This docstring was copied from {}.{}.{}.\n\n".format( cls.__module__, cls.__name__, name, ) else: l1 = f"This docstring was copied from {c...
.items()): if title in seen: new_title = "Extra " + title lines[i] = lines[i].replace(title, new_title) lines[i + 1] = lines[i + 1].replace("-" * len(title), "-" * len(new_title)) else: seen.add(title) return "\n".join(lines) def ignore_warning(doc, c...
91
91
305
16
75
nordange/dask
dask/utils.py
Python
ignore_warning
ignore_warning
667
701
667
667
43529cdf3ecf5a0e9af248513db7ce783de7eb5e
bigcode/the-stack
train
0a413bda2c715c2540308428
train
function
@contextmanager def tmpfile(extension="", dir=None): """ Function to create and return a unique temporary file with the given extension, if provided. Parameters ---------- extension : str The extension of the temporary file to be created dir : str If ``dir`` is not None, the fil...
@contextmanager def tmpfile(extension="", dir=None):
""" Function to create and return a unique temporary file with the given extension, if provided. Parameters ---------- extension : str The extension of the temporary file to be created dir : str If ``dir`` is not None, the file will be created in that directory; otherwise, ...
return func(seq) def import_required(mod_name, error_msg): """Attempt to import a required dependency. Raises a RuntimeError if the requested module is not available. """ try: return import_module(mod_name) except ImportError as e: raise RuntimeError(error_msg) from e @contextman...
76
76
255
12
63
nordange/dask
dask/utils.py
Python
tmpfile
tmpfile
167
207
167
168
30eb6c9395ede74d181171f8c27ef94c7794e3d0
bigcode/the-stack
train
d0d0c638ac889fa987bd19cf
train
function
def partial_by_order(*args, **kwargs): """ >>> from operator import add >>> partial_by_order(5, function=add, other=[(1, 10)]) 15 """ function = kwargs.pop("function") other = kwargs.pop("other") args2 = list(args) for i, arg in other: args2.insert(i, arg) return functio...
def partial_by_order(*args, **kwargs):
""" >>> from operator import add >>> partial_by_order(5, function=add, other=[(1, 10)]) 15 """ function = kwargs.pop("function") other = kwargs.pop("other") args2 = list(args) for i, arg in other: args2.insert(i, arg) return function(*args2, **kwargs)
, op): """Must return a method used by unary operator""" raise NotImplementedError @classmethod def _get_binary_operator(cls, op, inv=False): """Must return a method used by binary operator""" raise NotImplementedError def partial_by_order(*args, **kwargs):
64
64
94
10
53
nordange/dask
dask/utils.py
Python
partial_by_order
partial_by_order
1,213
1,225
1,213
1,213
ec1afb51392355ad4f4bbb9741c5fe27ccb38af4
bigcode/the-stack
train
bd92a970e93b626a1069c39b
train
function
def is_dataframe_like(df): """Looks like a Pandas DataFrame""" if (df.__class__.__module__, df.__class__.__name__) == ( "pandas.core.frame", "DataFrame", ): # fast exec for most likely input return True typ = df.__class__ return ( all(hasattr(typ, name) for na...
def is_dataframe_like(df):
"""Looks like a Pandas DataFrame""" if (df.__class__.__module__, df.__class__.__name__) == ( "pandas.core.frame", "DataFrame", ): # fast exec for most likely input return True typ = df.__class__ return ( all(hasattr(typ, name) for name in ("groupby", "head", "...
or `map_blocks` with scikit-learn functions on dask arrays and dask dataframes. # https://github.com/dask/dask/pull/3738 and (is_duck_array or "scipy.sparse" in typename(type(x))) ) def is_dataframe_like(df):
64
64
136
6
58
nordange/dask
dask/utils.py
Python
is_dataframe_like
is_dataframe_like
1,271
1,284
1,271
1,271
791d5e58133cfa6be822d0cea6bca5f4e1e7aa5e
bigcode/the-stack
train
200e682da16b62e5c4102b95
train
function
@contextmanager def filetexts(d, open=open, mode="t", use_tmpdir=True): """Dumps a number of textfiles to disk Parameters ---------- d : dict a mapping from filename to text like {'a.csv': '1,1\n2,2'} Since this is meant for use in tests, this context manager will automatically switch ...
@contextmanager def filetexts(d, open=open, mode="t", use_tmpdir=True):
"""Dumps a number of textfiles to disk Parameters ---------- d : dict a mapping from filename to text like {'a.csv': '1,1\n2,2'} Since this is meant for use in tests, this context manager will automatically switch to a temporary current directory, to avoid race conditions when runn...
4 """ __slots__ = ("fn",) def __init__(self, fn): self.fn = fn def __getitem__(self, key): return self.fn(key) @contextmanager def filetexts(d, open=open, mode="t", use_tmpdir=True):
64
64
212
21
43
nordange/dask
dask/utils.py
Python
filetexts
filetexts
296
329
296
297
8f57d2ef833573c9a4868a891cf35571264ac7d8
bigcode/the-stack
train
a6649210da89f42e58f9a760
train
function
def insert(tup, loc, val): """ >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L)
def insert(tup, loc, val):
""" >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L)
1, 10) 3 >>> digit(1234, 2, 10) 2 >>> digit(1234, 3, 10) 1 """ return n // base**k % base def insert(tup, loc, val):
64
64
61
9
54
nordange/dask
dask/utils.py
Python
insert
insert
930
938
930
930
0cd5463364368b8c47365eea3a0c2edc59bd6850
bigcode/the-stack
train
991c62796d271195181b48c0
train
function
def getargspec(func): """Version of inspect.getargspec that works with partial and warps.""" if isinstance(func, functools.partial): return getargspec(func.func) func = getattr(func, "__wrapped__", func) if isinstance(func, type): return inspect.getfullargspec(func.__init__) else: ...
def getargspec(func):
"""Version of inspect.getargspec that works with partial and warps.""" if isinstance(func, functools.partial): return getargspec(func.func) func = getattr(func, "__wrapped__", func) if isinstance(func, type): return inspect.getfullargspec(func.__init__) else: return inspect....
vars, zip, memoryview, } MULTI_ARITY_BUILTINS = { compile, delattr, divmod, filter, getattr, hasattr, isinstance, issubclass, map, pow, setattr, } def getargspec(func):
64
64
79
6
58
nordange/dask
dask/utils.py
Python
getargspec
getargspec
473
482
473
473
a240144e9e7af2ab8bd3d086465841fff987d62e
bigcode/the-stack
train
7ca542866fb7c313b51f8848
train
function
def is_cupy_type(x): # TODO: avoid explicit reference to CuPy return "cupy" in str(type(x))
def is_cupy_type(x): # TODO: avoid explicit reference to CuPy
return "cupy" in str(type(x))
a Pandas Index""" typ = s.__class__ return ( all(hasattr(s, name) for name in ("name", "dtype")) and "index" in typ.__name__.lower() ) def is_cupy_type(x): # TODO: avoid explicit reference to CuPy
64
64
29
18
46
nordange/dask
dask/utils.py
Python
is_cupy_type
is_cupy_type
1,306
1,308
1,306
1,307
aa8fb6a4895b480cf6a6655d03ec516fcf51f04f
bigcode/the-stack
train
cb96eb24149cda2a1c799452
train
function
@contextmanager def tmp_cwd(dir=None): with tmpdir(dir) as dirname: with changed_cwd(dirname): yield dirname
@contextmanager def tmp_cwd(dir=None):
with tmpdir(dir) as dirname: with changed_cwd(dirname): yield dirname
AttributeError: pass yield filename @contextmanager def changed_cwd(new_cwd): old_cwd = os.getcwd() os.chdir(new_cwd) try: yield finally: os.chdir(old_cwd) @contextmanager def tmp_cwd(dir=None):
64
64
31
11
53
nordange/dask
dask/utils.py
Python
tmp_cwd
tmp_cwd
269
273
269
270
f952aa1234e1fc612c25962ba25cdd90808c3ce9
bigcode/the-stack
train
37131ca04220139f1e4ba8f2
train
function
def ensure_dict(d: Mapping[K, V], *, copy: bool = False) -> dict[K, V]: """Convert a generic Mapping into a dict. Optimize use case of :class:`~dask.highlevelgraph.HighLevelGraph`. Parameters ---------- d : Mapping copy : bool If True, guarantee that the return value is always a shallow...
def ensure_dict(d: Mapping[K, V], *, copy: bool = False) -> dict[K, V]:
"""Convert a generic Mapping into a dict. Optimize use case of :class:`~dask.highlevelgraph.HighLevelGraph`. Parameters ---------- d : Mapping copy : bool If True, guarantee that the return value is always a shallow copy of d; otherwise it may be the input itself. """ if...
get_scheduler actual_get = get_scheduler(collections=[collection], scheduler=scheduler) if actual_get == multiprocessing.get: return multiprocessing.get_context().Manager().Lock() return SerializableLock() def ensure_dict(d: Mapping[K, V], *, copy: bool = False) -> dict[K, V]:
64
64
168
23
41
nordange/dask
dask/utils.py
Python
ensure_dict
ensure_dict
1,149
1,170
1,149
1,149
f32ebc88324f8d3a69a3a02a899b7b18cff2601a
bigcode/the-stack
train
c493f43392bc9fd6aaf79fea
train
class
class itemgetter: """Variant of operator.itemgetter that supports equality tests""" __slots__ = ("index",) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] def __reduce__(self): return (itemgetter, (self.index,)) def __eq__(se...
class itemgetter:
"""Variant of operator.itemgetter that supports equality tests""" __slots__ = ("index",) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] def __reduce__(self): return (itemgetter, (self.index,)) def __eq__(self, other): ...
self.method)(*args, **kwargs) def __reduce__(self): return (methodcaller, (self.method,)) def __str__(self): return f"<{self.__class__.__name__}: {self.method}>" __repr__ = __str__ class itemgetter:
63
64
98
4
59
nordange/dask
dask/utils.py
Python
itemgetter
itemgetter
1,029
1,044
1,029
1,029
46e5d54531df59355ec2fa4fcbe16309977b06eb
bigcode/the-stack
train
2564167cbbb648a8575e50e6
train
function
def unsupported_arguments(doc, args): """Mark unsupported arguments with a disclaimer""" lines = doc.split("\n") for arg in args: subset = [ (i, line) for i, line in enumerate(lines) if re.match(r"^\s*" + arg + " ?:", line) ] if len(subset) == 1: ...
def unsupported_arguments(doc, args):
"""Mark unsupported arguments with a disclaimer""" lines = doc.split("\n") for arg in args: subset = [ (i, line) for i, line in enumerate(lines) if re.match(r"^\s*" + arg + " ?:", line) ] if len(subset) == 1: [(i, line)] = subset ...
[indent, extra.rstrip("\n") + "\n\n"] else: more = [] bits = [head, indent, l1, indent, l2, "\n\n"] + more + [tail] doc = "".join(bits) return doc def unsupported_arguments(doc, args):
64
64
111
7
56
nordange/dask
dask/utils.py
Python
unsupported_arguments
unsupported_arguments
704
716
704
704
0b173a6d96c911c89259b064e99ab37d2c244ed3
bigcode/the-stack
train
0239d9c662d65fbd2eab6d7d
train
function
def parse_bytes(s): """Parse byte string to numbers >>> from dask.utils import parse_bytes >>> parse_bytes('100') 100 >>> parse_bytes('100 MB') 100000000 >>> parse_bytes('100M') 100000000 >>> parse_bytes('5kB') 5000 >>> parse_bytes('5.4 kB') 5400 >>> parse_bytes('1ki...
def parse_bytes(s):
"""Parse byte string to numbers >>> from dask.utils import parse_bytes >>> parse_bytes('100') 100 >>> parse_bytes('100 MB') 100000000 >>> parse_bytes('100M') 100000000 >>> parse_bytes('5kB') 5000 >>> parse_bytes('5.4 kB') 5400 >>> parse_bytes('1kiB') 1024 >>>...
21'] """ return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", s)] def factors(n): """Return the factors of an integer https://stackoverflow.com/a/6800214/616616 """ seq = ([i, n // i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0) return set(functools.reduc...
116
116
387
5
111
nordange/dask
dask/utils.py
Python
parse_bytes
parse_bytes
1,349
1,403
1,349
1,349
5e97e1510d32269418b348d1f31e24de8d91430e
bigcode/the-stack
train
ee3bb5c03371eb36bd6c113f
train
function
def format_bytes(n: int) -> str: """Format bytes as text >>> from dask.utils import format_bytes >>> format_bytes(1) '1 B' >>> format_bytes(1234) '1.21 kiB' >>> format_bytes(12345678) '11.77 MiB' >>> format_bytes(1234567890) '1.15 GiB' >>> format_bytes(1234567890000) '1....
def format_bytes(n: int) -> str:
"""Format bytes as text >>> from dask.utils import format_bytes >>> format_bytes(1) '1 B' >>> format_bytes(1234) '1.21 kiB' >>> format_bytes(12345678) '11.77 MiB' >>> format_bytes(1234567890) '1.15 GiB' >>> format_bytes(1234567890000) '1.12 TiB' >>> format_bytes(1234...
for unit in units: dur = int(units[unit](diff)) if dur > 0: if dur == 1: # De-pluralize unit = unit[:-1] return f"{dur} {unit} ago" return "Just now" def format_bytes(n: int) -> str:
71
71
239
10
61
nordange/dask
dask/utils.py
Python
format_bytes
format_bytes
1,515
1,543
1,515
1,515
0135c72bef5ce7b4336ff3d457f7e6ca21746e9c
bigcode/the-stack
train
7b90389b9bfc01562b140b9c
train
class
class OperatorMethodMixin: """A mixin for dynamically implementing operators""" __slots__ = () @classmethod def _bind_operator(cls, op): """bind operator to this class""" name = op.__name__ if name.endswith("_"): # for and_ and or_ name = name[:-1] ...
class OperatorMethodMixin:
"""A mixin for dynamically implementing operators""" __slots__ = () @classmethod def _bind_operator(cls, op): """bind operator to this class""" name = op.__name__ if name.endswith("_"): # for and_ and or_ name = name[:-1] elif name == "inv": ...
if type(d) is dict: return d.copy() if copy else d # type: ignore try: layers = d.layers # type: ignore except AttributeError: return dict(d) result = {} for layer in toolz.unique(layers.values(), key=id): result.update(layer) return result class OperatorMethodMix...
78
78
263
5
72
nordange/dask
dask/utils.py
Python
OperatorMethodMixin
OperatorMethodMixin
1,173
1,210
1,173
1,173
7e6399f1a3e5642c8d6bc6b677e029272dd78f44
bigcode/the-stack
train
525e07c4d9f0d0098ff142e6
train
function
@contextmanager def tmpdir(dir=None): """ Function to create and return a unique temporary directory. Parameters ---------- dir : str If ``dir`` is not None, the directory will be created in that directory; otherwise, Python's default temporary directory is used. Returns --...
@contextmanager def tmpdir(dir=None):
""" Function to create and return a unique temporary directory. Parameters ---------- dir : str If ``dir`` is not None, the directory will be created in that directory; otherwise, Python's default temporary directory is used. Returns ------- out : str Path to th...
try: yield filename finally: if os.path.exists(filename): with suppress(OSError): # sometimes we can't remove a generated temp file if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename) @con...
64
64
164
10
54
nordange/dask
dask/utils.py
Python
tmpdir
tmpdir
210
241
210
211
b5a07a8378f7ea56712a2155a6dff24493cb5419
bigcode/the-stack
train
07c8258929b8b6868f50b65d
train
function
def parse_timedelta(s, default="seconds"): """Parse timedelta string to number of seconds Examples -------- >>> from datetime import timedelta >>> from dask.utils import parse_timedelta >>> parse_timedelta('3s') 3 >>> parse_timedelta('3.5 seconds') 3.5 >>> parse_timedelta('300ms...
def parse_timedelta(s, default="seconds"):
"""Parse timedelta string to number of seconds Examples -------- >>> from datetime import timedelta >>> from dask.utils import parse_timedelta >>> parse_timedelta('3s') 3 >>> parse_timedelta('3.5 seconds') 3.5 >>> parse_timedelta('300ms') 0.3 >>> parse_timedelta(timedelt...
"microsecond": 1e-6, "nanosecond": 1e-9, } tds2.update({k + "s": v for k, v in tds2.items()}) timedelta_sizes.update(tds2) timedelta_sizes.update({k.upper(): v for k, v in timedelta_sizes.items()}) def parse_timedelta(s, default="seconds"):
85
85
285
10
75
nordange/dask
dask/utils.py
Python
parse_timedelta
parse_timedelta
1,570
1,612
1,570
1,570
9f1fe7929eebac847a0381a753ffcbcf7f4ef52c
bigcode/the-stack
train
635d9e80221518dabd92b4df
train
function
def funcname(func): """Get the name of a function.""" # functools.partial if isinstance(func, functools.partial): return funcname(func.func) # methodcaller if isinstance(func, methodcaller): return func.method[:50] module_name = getattr(func, "__module__", None) or "" type_n...
def funcname(func):
"""Get the name of a function.""" # functools.partial if isinstance(func, functools.partial): return funcname(func.func) # methodcaller if isinstance(func, methodcaller): return func.method[:50] module_name = getattr(func, "__module__", None) or "" type_name = getattr(type(f...
= f"Base package doesn't support '{method.__name__}'." if version is not None: msg2 = " Use {0} {1} or later to use this method." msg += msg2.format(module_name, version) raise NotImplementedError(msg) return wrapped return wrapp...
71
71
239
5
65
nordange/dask
dask/utils.py
Python
funcname
funcname
820
849
820
820
e60db7ce1ab66f7ed0c73869064839379fd377cc
bigcode/the-stack
train
6add6c3f282222b1bdc5e808
train
class
class VM(): class VMState(enum.Enum): ERROR = 0 CREATED = 1 READY = 2 RUNNING = 3 DESTROYED = 4 def __init__(self, vmPath, vmName): logging.info("Creating VM from %s"%(vmPath,)) self.vmPath = vmPath self.dirName = os.path.dirname(vmPath) ...
class VM():
class VMState(enum.Enum): ERROR = 0 CREATED = 1 READY = 2 RUNNING = 3 DESTROYED = 4 def __init__(self, vmPath, vmName): logging.info("Creating VM from %s"%(vmPath,)) self.vmPath = vmPath self.dirName = os.path.dirname(vmPath) self.imgD...
copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furni...
256
256
1,124
3
252
PPPy290351/Hitcon-Agent
kofserver/vm_manager.py
Python
VM
VM
34
161
34
34
5de834de13a740f87067145985d3a866c42f6c31
bigcode/the-stack
train
efaf9a477edb790d4ed2c2c6
train
class
class VMManager(): def __init__(self): pass # vmPath is the path to a template that describes the VM to be created. # The template format is specific to KOF. # Throw an exception for failure. def CreateVM(self, vmPath, vmName): vm = VM(vmPath, vmName) return vm
class VMManager():
def __init__(self): pass # vmPath is the path to a template that describes the VM to be created. # The template format is specific to KOF. # Throw an exception for failure. def CreateVM(self, vmPath, vmName): vm = VM(vmPath, vmName) return vm
def LoadVM(vmPath): try: with open(vmPath) as f: result = yaml.load(f, Loader=yaml.FullLoader) except Exception: logging.exception("Failed to open vm config yml file %s"%vmPath) raise return result class VMManager():
64
64
77
4
59
PPPy290351/Hitcon-Agent
kofserver/vm_manager.py
Python
VMManager
VMManager
163
172
163
163
640a9eeb5b4dc6899e6e7fe8104afc05321e7232
bigcode/the-stack
train
3659270959fd8450a9748e6a
train
function
def clustalw_alignment_tree(seqrecs, **kwargs): """Generate phylogenetic tree using ClustalW. Note that ClustalW is an older generation of Clustal aligner compared to Clustal Omega. It is considered to be slower and less robust for aligning large sequence sets, but it is included here because it does no...
def clustalw_alignment_tree(seqrecs, **kwargs):
"""Generate phylogenetic tree using ClustalW. Note that ClustalW is an older generation of Clustal aligner compared to Clustal Omega. It is considered to be slower and less robust for aligning large sequence sets, but it is included here because it does not require scikit-bio. :param seqrecs: a lis...
omega_distance_matrix(seqrecs, **kwargs) ids = [s.id for s in seqrecs] skbio_tree = skbio.tree.nj(skbio.DistanceMatrix(distance_matrix, ids)) return skbio2phylo(skbio_tree) def clustalw_alignment_tree(seqrecs, **kwargs):
69
69
231
14
55
modernatx/seqlike
seqlike/alignment_commands.py
Python
clustalw_alignment_tree
clustalw_alignment_tree
188
205
188
188
bd8ddaa5cdaf4ae1eb7243a65d3454870fe96789
bigcode/the-stack
train
2b6a6d23599c0fc421d80663
train
function
def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs): """Align sequences using Clustal Omega :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param preserve_order: if True, reorder aligned seqrecs to match input order. :param **kwargs: additional arguments for ali...
def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs):
"""Align sequences using Clustal Omega :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param preserve_order: if True, reorder aligned seqrecs to match input order. :param **kwargs: additional arguments for alignment command :returns: a MultipleSeqAlignment object with align...
if set if "reorder" not in kwargs: kwargs["reorder"] = not preserve_order return _generic_alignment(commandline, seqrecs, preserve_order=preserve_order, **kwargs) def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs):
64
64
185
18
46
modernatx/seqlike
seqlike/alignment_commands.py
Python
clustal_omega_alignment
clustal_omega_alignment
105
122
105
105
9d1502c7dfb1ff70aa29a4b177e77c646f4c84a1
bigcode/the-stack
train
e2ece4cf5ade27a0e823eeb0
train
function
def clustal_omega_distance_matrix(seqrecs, **kwargs): """Generate a distance matrix using Clustal Omega :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param **kwargs: additional arguments for command line alignment :returns: the pairwise distance matrix """ def comman...
def clustal_omega_distance_matrix(seqrecs, **kwargs):
"""Generate a distance matrix using Clustal Omega :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param **kwargs: additional arguments for command line alignment :returns: the pairwise distance matrix """ def commandline(ft, **kwargs): with tempfile.NamedTempor...
alOmegaCommandline("clustalo", infile=file_obj.name, outputorder=outputorder, **kwargs) return _generic_aligner_commandline_stdout(cline) return _generic_alignment(commandline, seqrecs, **kwargs) def clustal_omega_distance_matrix(seqrecs, **kwargs):
65
65
218
15
50
modernatx/seqlike
seqlike/alignment_commands.py
Python
clustal_omega_distance_matrix
clustal_omega_distance_matrix
125
148
125
125
ab3d075aba82f3d738414aa7c95a4ff38ebc432d
bigcode/the-stack
train
7acf244ced190661fc7e6989
train
function
def mafft_alignment(seqrecs, preserve_order=True, **kwargs): """Align sequences using MAFFT. :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param preserve_order: if True, reorder aligned seqrecs to match input order. :param **kwargs: additional arguments for alignment command ...
def mafft_alignment(seqrecs, preserve_order=True, **kwargs):
"""Align sequences using MAFFT. :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param preserve_order: if True, reorder aligned seqrecs to match input order. :param **kwargs: additional arguments for alignment command :returns: a MultipleSeqAlignment object with aligned sequ...
: aligned = SeqIO.to_dict(aligned) aligned = MultipleSeqAlignment(aligned[key] for key in keys) # make all alignment uppercase return MultipleSeqAlignment([seqrec.upper() for seqrec in aligned]) def mafft_alignment(seqrecs, preserve_order=True, **kwargs):
64
64
212
15
49
modernatx/seqlike
seqlike/alignment_commands.py
Python
mafft_alignment
mafft_alignment
84
102
84
84
697f3e53e3eefdf7e9a947ad09bd7ece7487465f
bigcode/the-stack
train
34dfee1c731324b66379855a
train
function
def _generic_aligner_commandline_stdout(cline, **kwargs): """Execute aligner commandline that writes to stdout and return an alignment. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param **kwargs: additional arguments for alignment command :returns...
def _generic_aligner_commandline_stdout(cline, **kwargs):
"""Execute aligner commandline that writes to stdout and return an alignment. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param **kwargs: additional arguments for alignment command :returns: a MultipleSeqAlignment object """ stdout, _ = cl...
Type :returns: a MultipleSeqAlignment object """ df = pd.DataFrame({"seqs": [SeqLike(seq, seq_type="aa") for seq in seqs]}) return df.seqs.seq.as_alignment() def _generic_aligner_commandline_stdout(cline, **kwargs):
64
64
126
14
50
modernatx/seqlike
seqlike/alignment_commands.py
Python
_generic_aligner_commandline_stdout
_generic_aligner_commandline_stdout
29
41
29
29
a6fbee6d0d80f1d030a90badcbccabb17e98876a
bigcode/the-stack
train
9ff4b1fc3281f8f274db1b79
train
function
def pad_seq_records_for_alignment(seqs: List[SeqLikeType]): """Pad sequences so that lengths match for multiple sequence alignment. :param seqs: a list of SeqLikeType :returns: a MultipleSeqAlignment object """ df = pd.DataFrame({"seqs": [SeqLike(seq, seq_type="aa") for seq in seqs]}) return df...
def pad_seq_records_for_alignment(seqs: List[SeqLikeType]):
"""Pad sequences so that lengths match for multiple sequence alignment. :param seqs: a list of SeqLikeType :returns: a MultipleSeqAlignment object """ df = pd.DataFrame({"seqs": [SeqLike(seq, seq_type="aa") for seq in seqs]}) return df.seqs.seq.as_alignment()
import MultipleSeqAlignment from Bio.Align.Applications import ClustalOmegaCommandline from .AlignCommandline import MafftCommandline from .SeqLike import SeqLikeType, SeqLike pd = lazy.load("pandas") def pad_seq_records_for_alignment(seqs: List[SeqLikeType]):
64
64
89
15
49
modernatx/seqlike
seqlike/alignment_commands.py
Python
pad_seq_records_for_alignment
pad_seq_records_for_alignment
19
26
19
19
0d9ec185b3aa79ce1a40f4d6b69adb552ede9c76
bigcode/the-stack
train
70e52b773f5d0464d10dfbec
train
function
def clustal_omega_alignment_tree(seqrecs, **kwargs): """Generate phylogenetic tree using Clustal Omega and scikit-bio Neighbor Joining This function computes a distance matrix using Clustal Omega, which skbio.tree.nj uses to generate a newick file. Bio.Phylo can read this newick file. Note: this funct...
def clustal_omega_alignment_tree(seqrecs, **kwargs):
"""Generate phylogenetic tree using Clustal Omega and scikit-bio Neighbor Joining This function computes a distance matrix using Clustal Omega, which skbio.tree.nj uses to generate a newick file. Bio.Phylo can read this newick file. Note: this function requires scikit-bio. :param seqrecs: a list ...
", infile=ft.name, force=True, distmat_out=ft_out.name, distmat_full=True, distmat_full_iter=True, ) stdout, stderr = cline() df = pd.read_csv(ft_out.name, delim_whitespace=True, skiprows=1, header=None, index_co...
118
118
396
15
103
modernatx/seqlike
seqlike/alignment_commands.py
Python
clustal_omega_alignment_tree
clustal_omega_alignment_tree
151
185
151
151
c817ced1d9008c7697666f10f7b58cdaca0907c0
bigcode/the-stack
train
ec417afdad4efdeb06e9bb08
train
function
def _generic_alignment(cline, seqrecs, preserve_order=True, **kwargs): """Align sequences using command line stored as cline. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param seqrecs: an iterator of SeqRecord that will be aligned :param preserve_...
def _generic_alignment(cline, seqrecs, preserve_order=True, **kwargs):
"""Align sequences using command line stored as cline. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param seqrecs: an iterator of SeqRecord that will be aligned :param preserve_order: if True, reorder aligned seqrecs to match input order. :para...
_alignment(seqrecs) # execute alignment with tempfile.NamedTemporaryFile(delete=False, mode="w") as tempf: AlignIO.write(unaligned, tempf, "fasta") tempf.flush() return cline(tempf, **kwargs) def _generic_alignment(cline, seqrecs, preserve_order=True, **kwargs):
75
75
253
18
57
modernatx/seqlike
seqlike/alignment_commands.py
Python
_generic_alignment
_generic_alignment
62
81
62
62
92cb77591edfb00482d3f9fe356191071b7bf6c8
bigcode/the-stack
train
e0621aa004f5f4afa34a0837
train
function
def _generic_aligner_commandline_file(cline, seqrecs, **kwargs): """Execute aligner commandline that requires file i/o and return an alignment. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param seqrecs: a list of SeqRecord that will be aligned :pa...
def _generic_aligner_commandline_file(cline, seqrecs, **kwargs):
"""Execute aligner commandline that requires file i/o and return an alignment. Helper function. :param cline: a subprocess object from Bio.Align.Applications.AbstractCommandline :param seqrecs: a list of SeqRecord that will be aligned :param **kwargs: additional arguments for alignment command :ret...
cline() try: stdout = StringIO(stdout) except TypeError: stdout = StringIO(unicode(stdout, "utf-8")) return AlignIO.read(stdout, "fasta", **kwargs) def _generic_aligner_commandline_file(cline, seqrecs, **kwargs):
64
64
201
18
46
modernatx/seqlike
seqlike/alignment_commands.py
Python
_generic_aligner_commandline_file
_generic_aligner_commandline_file
44
59
44
44
240338b01f2f589689abf6a4125ef271afb9f905
bigcode/the-stack
train
351bf2795e8f9afa69c57afd
train
class
class Novel: _p = re.compile('<p>(.*?)</p>') max_thrs = 5 def __init__(self, url, pagen): if not url.endswith('/'): url += '/' self.url = url self.pagen = pagen self._ses = None @property def ses(self): if not self._ses: self._ses = r...
class Novel:
_p = re.compile('<p>(.*?)</p>') max_thrs = 5 def __init__(self, url, pagen): if not url.endswith('/'): url += '/' self.url = url self.pagen = pagen self._ses = None @property def ses(self): if not self._ses: self._ses = requests.sessi...
import re import os.path import codecs import zipfile import requests from threading import Thread from collections import deque class Novel:
30
215
719
3
26
jeefies/reptile
getNovelYinianyonghen/getNovel.py
Python
Novel
Novel
9
96
9
9
875f9b5b4811336ca2c8013285dc8f07ddad1c81
bigcode/the-stack
train
030cfcc3a7ea7bb3a0751ba0
train
class
class Migration(migrations.Migration): dependencies = [ ('projects', '0005_projects_guest'), ] operations = [ migrations.AddField( model_name='projects', name='ibm_api_key', field=models.CharField(blank=True, max_length=200, null=True), ), ]
class Migration(migrations.Migration):
dependencies = [ ('projects', '0005_projects_guest'), ] operations = [ migrations.AddField( model_name='projects', name='ibm_api_key', field=models.CharField(blank=True, max_length=200, null=True), ), ]
# Generated by Django 3.0.6 on 2020-10-21 08:56 from django.db import migrations, models class Migration(migrations.Migration):
38
64
66
7
30
Code-and-Response/ISAC-SIMO-Repo-2
projects/migrations/0006_projects_ibm_api_key.py
Python
Migration
Migration
6
18
6
7
b230f71f57951d3529bf215939d01996ecc96c6f
bigcode/the-stack
train
755b185389f0296613d7c061
train
function
@asyncio.coroutine def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the SPC alarm control panel platform.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_AREAS] is None): return entities = [SpcAlarm(hass=ha...
@asyncio.coroutine def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the SPC alarm control panel platform.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_AREAS] is None): return entities = [SpcAlarm(hass=hass, area_id=area['id'], name=area['name'], state=_...
_ARMED_HOME, '3': STATE_ALARM_ARMED_AWAY} def _get_alarm_state(spc_mode): return SPC_AREA_MODE_TO_STATE.get(spc_mode, STATE_UNKNOWN) @asyncio.coroutine def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
64
64
120
24
40
EmitKiwi/home-assistant
homeassistant/components/alarm_control_panel/spc.py
Python
async_setup_platform
async_setup_platform
29
43
29
31
1ca82f5c72d0b1f4b437ac27a0e3bc4d51ed236e
bigcode/the-stack
train
ed0adc362800fd729d003278
train
class
class SpcAlarm(alarm.AlarmControlPanel): """Represents the SPC alarm panel.""" def __init__(self, hass, area_id, name, state): """Initialize the SPC alarm panel.""" self._hass = hass self._area_id = area_id self._name = name self._state = state self._api = hass.d...
class SpcAlarm(alarm.AlarmControlPanel):
"""Represents the SPC alarm panel.""" def __init__(self, hass, area_id, name, state): """Initialize the SPC alarm panel.""" self._hass = hass self._area_id = area_id self._name = name self._state = state self._api = hass.data[DATA_API] hass.data[DATA_REG...
_info=None): """Set up the SPC alarm control panel platform.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_AREAS] is None): return entities = [SpcAlarm(hass=hass, area_id=area['id'], name=area['name'], ...
110
110
369
11
99
EmitKiwi/home-assistant
homeassistant/components/alarm_control_panel/spc.py
Python
SpcAlarm
SpcAlarm
46
96
46
46
e481554120b00ba0b25659e43f9cc919bd006806
bigcode/the-stack
train
767add0b247e3c5b350a71db
train
function
def _get_alarm_state(spc_mode): return SPC_AREA_MODE_TO_STATE.get(spc_mode, STATE_UNKNOWN)
def _get_alarm_state(spc_mode):
return SPC_AREA_MODE_TO_STATE.get(spc_mode, STATE_UNKNOWN)
ED, STATE_UNKNOWN) _LOGGER = logging.getLogger(__name__) SPC_AREA_MODE_TO_STATE = {'0': STATE_ALARM_DISARMED, '1': STATE_ALARM_ARMED_HOME, '3': STATE_ALARM_ARMED_AWAY} def _get_alarm_state(spc_mode):
64
64
24
9
55
EmitKiwi/home-assistant
homeassistant/components/alarm_control_panel/spc.py
Python
_get_alarm_state
_get_alarm_state
25
26
25
25
eca49f42858623eb460bae7cce62ff9194d1ad76
bigcode/the-stack
train
6d1c852e1b7015a8b7fe86dc
train
class
class InputPipeline(object): """Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... tr...
class InputPipeline(object):
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The val...
implementation is shared in common between train/eval pipelines, and when serving the model. Args: image_bytes: A string Tensor, containing the encoded JPEG. is_training: Whether or not to preprocess for training. bbox: In inception preprocessing, this bbox can be used for cropping. Returns:...
256
256
1,169
5
250
matarof/tpu
models/experimental/inception/inception_v3.py
Python
InputPipeline
InputPipeline
301
440
301
301
1cfead37329c4ce95410bae1d285851b078f940b
bigcode/the-stack
train
d37fb7bbfad96c1c2f64ce74
train
function
def main(unused_argv): del unused_argv # Unused tpu_cluster_resolver = contrib_cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) assert FLAGS.precision == 'bfloat16' or FLAGS.precision == 'float32', ( 'Invalid value for --precision flag; must be bfloat1...
def main(unused_argv):
del unused_argv # Unused tpu_cluster_resolver = contrib_cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) assert FLAGS.precision == 'bfloat16' or FLAGS.precision == 'float32', ( 'Invalid value for --precision flag; must be bfloat16 or float32.') tf.lo...
(logits, labels, 5), tf.float32) top_5_accuracy = tf.metrics.mean(in_top_5) return { 'accuracy': top_1_accuracy, 'accuracy@5': top_5_accuracy, } eval_metrics = (metric_fn, [labels, logits]) return contrib_tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_...
256
256
1,080
7
249
matarof/tpu
models/experimental/inception/inception_v3.py
Python
main
main
756
878
756
756
899cc53388122224aec725687a6b6ef18b3284b8
bigcode/the-stack
train
a41ab9f9ac5c3e72aef0c951
train
function
def preprocess_raw_bytes(image_bytes, is_training=False, bbox=None): """Preprocesses a raw JPEG image. This implementation is shared in common between train/eval pipelines, and when serving the model. Args: image_bytes: A string Tensor, containing the encoded JPEG. is_training: Whether or not to prepr...
def preprocess_raw_bytes(image_bytes, is_training=False, bbox=None):
"""Preprocesses a raw JPEG image. This implementation is shared in common between train/eval pipelines, and when serving the model. Args: image_bytes: A string Tensor, containing the encoded JPEG. is_training: Whether or not to preprocess for training. bbox: In inception preprocessing, this...
RMSProp. # Constants dictating moving average. MOVING_AVERAGE_DECAY = 0.995 # Batchnorm moving mean/variance parameters BATCH_NORM_DECAY = 0.996 BATCH_NORM_EPSILON = 1e-3 WEIGHT_DECAY = 0.00004 def preprocess_raw_bytes(image_bytes, is_training=False, bbox=None):
83
83
277
14
68
matarof/tpu
models/experimental/inception/inception_v3.py
Python
preprocess_raw_bytes
preprocess_raw_bytes
263
298
263
263
19ad52416d8a8bf0a229a10e931771403499961c
bigcode/the-stack
train
aa9d743ad871a1df49664351
train
function
def tensor_transform_fn(data, perm): """Transpose function. This function is used to transpose an image tensor on the host and then perform an inverse transpose on the TPU. The transpose on the TPU gets effectively elided thus voiding any associated computational cost. NOTE: Eventually the compiler will be ...
def tensor_transform_fn(data, perm):
"""Transpose function. This function is used to transpose an image tensor on the host and then perform an inverse transpose on the TPU. The transpose on the TPU gets effectively elided thus voiding any associated computational cost. NOTE: Eventually the compiler will be able to detect when this kind of op...
None], dtype=tf.string, ) images = tf.map_fn( preprocess_raw_bytes, image_bytes_list, back_prop=False, dtype=tf.float32) return tf.estimator.export.ServingInputReceiver( images, {'image_bytes': image_bytes_list}) def tensor_transform_fn(data, perm):
64
64
144
8
56
matarof/tpu
models/experimental/inception/inception_v3.py
Python
tensor_transform_fn
tensor_transform_fn
462
482
462
462
4384f8303521a1588cd1cb3779fdb376ff53fdc3
bigcode/the-stack
train
c06fdcf432a7f530141fd39b
train
function
def inception_model_fn(features, labels, mode, params): """Inception v3 model using Estimator API.""" num_classes = FLAGS.num_classes is_training = (mode == tf.estimator.ModeKeys.TRAIN) is_eval = (mode == tf.estimator.ModeKeys.EVAL) if isinstance(features, dict): features = features['feature'] feature...
def inception_model_fn(features, labels, mode, params):
"""Inception v3 model using Estimator API.""" num_classes = FLAGS.num_classes is_training = (mode == tf.estimator.ModeKeys.TRAIN) is_eval = (mode == tf.estimator.ModeKeys.EVAL) if isinstance(features, dict): features = features['feature'] features = tensor_transform_fn(features, params['input_perm']) ...
fn for raw images. This function is consumed when exporting a SavedModel. Returns: A ServingInputReceiver capable of serving MobileNet predictions. """ image_bytes_list = tf.placeholder( shape=[None], dtype=tf.string, ) images = tf.map_fn( preprocess_raw_bytes, image_bytes_list, ba...
256
256
2,263
12
243
matarof/tpu
models/experimental/inception/inception_v3.py
Python
inception_model_fn
inception_model_fn
485
735
485
485
b6c01ef1d01b6d6e3370c5d7e0730f19e2d9db88
bigcode/the-stack
train
3f11bff52c4b3263b4f2276b
train
class
class LoadEMAHook(tf.train.SessionRunHook): """Hook to load exponential moving averages into corresponding variables.""" def __init__(self, model_dir): super(LoadEMAHook, self).__init__() self._model_dir = model_dir def begin(self): ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY) v...
class LoadEMAHook(tf.train.SessionRunHook):
"""Hook to load exponential moving averages into corresponding variables.""" def __init__(self, model_dir): super(LoadEMAHook, self).__init__() self._model_dir = model_dir def begin(self): ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY) variables_to_restore = ema.variables_to_resto...
_metrics = (metric_fn, [labels, logits]) return contrib_tpu.TPUEstimatorSpec( mode=mode, loss=loss, train_op=train_op, host_call=host_call, eval_metrics=eval_metrics) class LoadEMAHook(tf.train.SessionRunHook):
64
64
143
11
53
matarof/tpu
models/experimental/inception/inception_v3.py
Python
LoadEMAHook
LoadEMAHook
738
753
738
738
baeade311a8cd456ec493c1684adbb715333da35
bigcode/the-stack
train
9273d3abe273a2eed25f5667
train
function
def image_serving_input_fn(): """Serving input fn for raw images. This function is consumed when exporting a SavedModel. Returns: A ServingInputReceiver capable of serving MobileNet predictions. """ image_bytes_list = tf.placeholder( shape=[None], dtype=tf.string, ) images = tf.map_fn( ...
def image_serving_input_fn():
"""Serving input fn for raw images. This function is consumed when exporting a SavedModel. Returns: A ServingInputReceiver capable of serving MobileNet predictions. """ image_bytes_list = tf.placeholder( shape=[None], dtype=tf.string, ) images = tf.map_fn( preprocess_raw_bytes, im...
if FLAGS.transpose_enabled: def transpose_images(images): return tf.transpose(images, params['output_perm']) dataset = dataset.map( lambda images, labels: (transpose_images(images), labels), num_parallel_calls=FLAGS.num_parallel_calls) return dataset def image_servin...
64
64
111
7
56
matarof/tpu
models/experimental/inception/inception_v3.py
Python
image_serving_input_fn
image_serving_input_fn
443
459
443
443
4e6dac84486f511aa4844d2116ca810ed9eadda6
bigcode/the-stack
train
ace4ea56fff1c359c3450e89
train
function
def is_same_language(lst: List[dict]) -> bool: return True if len(set([i['language'] for i in lst])) == 1 else False
def is_same_language(lst: List[dict]) -> bool:
return True if len(set([i['language'] for i in lst])) == 1 else False
from typing import List def is_same_language(lst: List[dict]) -> bool:
19
64
36
14
4
yaznasivasai/python_codewars
7KYU/is_same_language.py
Python
is_same_language
is_same_language
4
5
4
4
ce53f6a36119799dd28d3763e9614184ee274035
bigcode/the-stack
train
996c7faec3833c8c9ba1173c
train
class
class Migration(migrations.Migration): dependencies = [ ('saved_reports', '0001_initial'), ] operations = [ migrations.CreateModel( name='ScheduledReportLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verb...
class Migration(migrations.Migration):
dependencies = [ ('saved_reports', '0001_initial'), ] operations = [ migrations.CreateModel( name='ScheduledReportLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sent_...
# Generated by Django 2.2.24 on 2021-09-24 15:45 import datetime from django.db import migrations, models class Migration(migrations.Migration):
41
64
164
7
33
akashkj/commcare-hq
corehq/apps/saved_reports/migrations/0002_scheduledreportlog.py
Python
Migration
Migration
7
27
7
8
582bbfc9980491f33dd29264a02f03ad71e875bc
bigcode/the-stack
train