language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
doocs__leetcode
solution/3100-3199/3138.Minimum Length of Anagram Concatenation/Solution.py
{ "start": 0, "end": 474 }
class ____: def minAnagramLength(self, s: str) -> int: def check(k: int) -> bool: for i in range(0, n, k): cnt1 = Counter(s[i : i + k]) for c, v in cnt.items(): if cnt1[c] * (n // k) != v: return False return True cnt = Counter(s) n = len(s) for i in range(1, n + 1): if n % i == 0 and check(i): return i
Solution
python
has2k1__plotnine
plotnine/scales/scale_xy.py
{ "start": 7143, "end": 7202 }
class ____(scale_x_discrete): pass @alias
scale_x_ordinal
python
getsentry__sentry
tests/sentry/discover/test_dashboard_widget_split.py
{ "start": 24674, "end": 24841 }
class ____(DashboardWidgetDatasetSplitTestCase): def setUp(self) -> None: super().setUp() self.dry_run = True
DashboardWidgetDatasetSplitDryRunTestCase
python
huggingface__transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
{ "start": 8991, "end": 9654 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->LayoutLMv2
LayoutLMv2SelfOutput
python
run-llama__llama_index
llama-index-integrations/indices/llama-index-indices-managed-vectara/llama_index/indices/managed/vectara/base.py
{ "start": 1087, "end": 1294 }
class ____(IndexDict): """Vectara Index Struct.""" @classmethod def get_type(cls) -> IndexStructType: """Get index struct type.""" return IndexStructType.VECTARA
VectaraIndexStruct
python
django-guardian__django-guardian
guardian/testapp/migrations/0006_auto_20230727_0658.py
{ "start": 93, "end": 2641 }
class ____(migrations.Migration): dependencies = [ ("testapp", "0005_uuidpkmodel"), ] operations = [ migrations.AlterField( model_name="customuser", name="first_name", field=models.CharField(blank=True, max_length=150, verbose_name="first name"), ), migrations.AlterField( model_name="customusernameuser", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="mixed", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="mixedgroupobjectpermission", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="parenttestmodel", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="post", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="project", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="projectgroupobjectpermission", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="projectuserobjectpermission", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="reversemixed", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), migrations.AlterField( model_name="reversemixeduserobjectpermission", name="id", field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"), ), ]
Migration
python
python-pillow__Pillow
src/PIL/SgiImagePlugin.py
{ "start": 1052, "end": 5378 }
class ____(ImageFile.ImageFile): format = "SGI" format_description = "SGI Image File Format" def _open(self) -> None: # HEAD assert self.fp is not None headlen = 512 s = self.fp.read(headlen) if not _accept(s): msg = "Not an SGI image file" raise ValueError(msg) # compression : verbatim or RLE compression = s[2] # bpc : 1 or 2 bytes (8bits or 16bits) bpc = s[3] # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize) dimension = i16(s, 4) # xsize : width xsize = i16(s, 6) # ysize : height ysize = i16(s, 8) # zsize : channels count zsize = i16(s, 10) # determine mode from bits/zsize try: rawmode = MODES[(bpc, dimension, zsize)] except KeyError: msg = "Unsupported SGI image mode" raise ValueError(msg) self._size = xsize, ysize self._mode = rawmode.split(";")[0] if self.mode == "RGB": self.custom_mimetype = "image/rgb" # orientation -1 : scanlines begins at the bottom-left corner orientation = -1 # decoder info if compression == 0: pagesize = xsize * ysize * bpc if bpc == 2: self.tile = [ ImageFile._Tile( "SGI16", (0, 0) + self.size, headlen, (self.mode, 0, orientation), ) ] else: self.tile = [] offset = headlen for layer in self.mode: self.tile.append( ImageFile._Tile( "raw", (0, 0) + self.size, offset, (layer, 0, orientation) ) ) offset += pagesize elif compression == 1: self.tile = [ ImageFile._Tile( "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc) ) ] def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: if im.mode not in {"RGB", "RGBA", "L"}: msg = "Unsupported SGI image mode" raise ValueError(msg) # Get the keyword arguments info = im.encoderinfo # Byte-per-pixel precision, 1 = 8bits per pixel bpc = info.get("bpc", 1) if bpc not in (1, 2): msg = "Unsupported number of bytes per pixel" raise ValueError(msg) # Flip the image, since the origin of SGI file is the bottom-left corner orientation = -1 # Define the file as SGI File Format magic_number = 474 # Run-Length Encoding Compression - Unsupported at this time rle = 0 # X Dimension = width / Y Dimension = height x, y = im.size # Z Dimension: Number of channels z = len(im.mode) # Number of dimensions (x,y,z) if im.mode == "L": dimension = 1 if y == 1 else 2 else: dimension = 3 # Minimum Byte value pinmin = 0 # Maximum Byte value (255 = 8bits per pixel) pinmax = 255 # Image name (79 characters max, truncated below in write) img_name = os.path.splitext(os.path.basename(filename))[0] if isinstance(img_name, str): img_name = img_name.encode("ascii", "ignore") # Standard representation of pixel in the file colormap = 0 fp.write(struct.pack(">h", magic_number)) fp.write(o8(rle)) fp.write(o8(bpc)) fp.write(struct.pack(">H", dimension)) fp.write(struct.pack(">H", x)) fp.write(struct.pack(">H", y)) fp.write(struct.pack(">H", z)) fp.write(struct.pack(">l", pinmin)) fp.write(struct.pack(">l", pinmax)) fp.write(struct.pack("4s", b"")) # dummy fp.write(struct.pack("79s", img_name)) # truncates to 79 chars fp.write(struct.pack("s", b"")) # force null byte after img_name fp.write(struct.pack(">l", colormap)) fp.write(struct.pack("404s", b"")) # dummy rawmode = "L" if bpc == 2: rawmode = "L;16B" for channel in im.split(): fp.write(channel.tobytes("raw", rawmode, 0, orientation)) if hasattr(fp, "flush"): fp.flush()
SgiImageFile
python
PyCQA__pylint
tests/functional/m/member/member_checks_typed_annotations.py
{ "start": 140, "end": 284 }
class ____(C, B): pass a = A() print(a.myfield) b = B() print(b.myfield) d = D() print(d.myfield) c = C() print(c.myfield) # [no-member]
D
python
python-openxml__python-docx
src/docx/enum/base.py
{ "start": 284, "end": 881 }
class ____(int, enum.Enum): """Base class for Enums that do not map XML attr values. The enum's value will be an integer, corresponding to the integer assigned the corresponding member in the MS API enum of the same name. """ def __new__(cls, ms_api_value: int, docstr: str): self = int.__new__(cls, ms_api_value) self._value_ = ms_api_value self.__doc__ = docstr.strip() return self def __str__(self): """The symbolic name and string value of this member, e.g. 'MIDDLE (3)'.""" return f"{self.name} ({self.value})"
BaseEnum
python
encode__django-rest-framework
tests/test_pagination.py
{ "start": 10531, "end": 12437 }
class ____: """ Unit tests for `pagination.PageNumberPagination`. the Django Paginator Class is overridden. """ def setup_method(self): class OverriddenDjangoPaginator(DjangoPaginator): # override the count in our overridden Django Paginator # we will only return one page, with one item count = 1 class ExamplePagination(pagination.PageNumberPagination): django_paginator_class = OverriddenDjangoPaginator page_size = 5 self.pagination = ExamplePagination() self.queryset = range(1, 101) def paginate_queryset(self, request): return list(self.pagination.paginate_queryset(self.queryset, request)) def get_paginated_content(self, queryset): response = self.pagination.get_paginated_response(queryset) return response.data def get_html_context(self): return self.pagination.get_html_context() def test_no_page_number(self): request = Request(factory.get('/')) queryset = self.paginate_queryset(request) content = self.get_paginated_content(queryset) context = self.get_html_context() assert queryset == [1] assert content == { 'results': [1, ], 'previous': None, 'next': None, 'count': 1 } assert context == { 'previous_url': None, 'next_url': None, 'page_links': [ PageLink('http://testserver/', 1, True, False), ] } assert not self.pagination.display_page_controls assert isinstance(self.pagination.to_html(), str) def test_invalid_page(self): request = Request(factory.get('/', {'page': 'invalid'})) with pytest.raises(exceptions.NotFound): self.paginate_queryset(request)
TestPageNumberPaginationOverride
python
openai__openai-python
src/openai/types/chat/chat_completion_audio_param.py
{ "start": 249, "end": 811 }
class ____(TypedDict, total=False): format: Required[Literal["wav", "aac", "mp3", "flac", "opus", "pcm16"]] """Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. """ voice: Required[ Union[str, Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]] ] """The voice the model uses to respond. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. """
ChatCompletionAudioParam
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_strategy_state.py
{ "start": 998, "end": 5335 }
class ____(RuleBasedStateMachine): def __init__(self): super().__init__() self.database = None strategies = Bundle("strategy") strategy_tuples = Bundle("tuples") objects = Bundle("objects") basic_data = Bundle("basic") varied_floats = Bundle("varied_floats") def teardown(self): self.clear_database() @rule() def clear_database(self): if self.database is not None: self.database = None @rule() def set_database(self): self.teardown() self.database = InMemoryExampleDatabase() @rule( target=strategies, spec=sampled_from( ( integers(), booleans(), floats(), complex_numbers(), fractions(), decimals(), text(), binary(), none(), tuples(), ) ), ) def strategy(self, spec): return spec @rule(target=strategies, values=lists(integers() | text(), min_size=1)) def sampled_from_strategy(self, values): return sampled_from(values) @rule(target=strategies, spec=strategy_tuples) def strategy_for_tupes(self, spec): return tuples(*spec) @rule(target=strategies, source=strategies, level=integers(1, 10), mixer=text()) def filtered_strategy(self, source, level, mixer): def is_good(x): seed = hashlib.sha384((mixer + repr(x)).encode()).digest() return bool(Random(seed).randint(0, level)) return source.filter(is_good) @rule(target=strategies, elements=strategies) def list_strategy(self, elements): return lists(elements) @rule(target=strategies, left=strategies, right=strategies) def or_strategy(self, left, right): return left | right @rule(target=varied_floats, source=floats()) def float(self, source): return source @rule(target=varied_floats, source=varied_floats, offset=integers(-100, 100)) def adjust_float(self, source, offset): return int_to_float(clamp(0, float_to_int(source) + offset, 2**64 - 1)) @rule(target=strategies, left=varied_floats, right=varied_floats) def float_range(self, left, right): assume(math.isfinite(left) and math.isfinite(right)) left, right = sorted((left, right)) assert left <= right # exclude deprecated case where left = 0.0 and right = -0.0 assume(left or right or not (is_negative(right) and not is_negative(left))) return floats(left, right) @rule( target=strategies, source=strategies, result1=strategies, result2=strategies, mixer=text(), p=floats(0, 1), ) def flatmapped_strategy(self, source, result1, result2, mixer, p): assume(result1 is not result2) def do_map(value): rep = repr(value) random = Random(hashlib.sha384((mixer + rep).encode()).digest()) if random.random() <= p: return result1 else: return result2 return source.flatmap(do_map) @rule(target=strategies, value=objects) def just_strategy(self, value): return just(value) @rule(target=strategy_tuples, source=strategies) def single_tuple(self, source): return (source,) @rule(target=strategy_tuples, left=strategy_tuples, right=strategy_tuples) def cat_tuples(self, left, right): return left + right @rule(target=objects, strat=strategies, data=data()) def get_example(self, strat, data): data.draw(strat) @rule(target=strategies, left=integers(), right=integers()) def integer_range(self, left, right): left, right = sorted((left, right)) return integers(left, right) @rule(strat=strategies) def repr_is_good(self, strat): assert " at 0x" not in repr(strat) MAIN = __name__ == "__main__" TestHypothesis = HypothesisSpec.TestCase TestHypothesis.settings = settings( TestHypothesis.settings, stateful_step_count=10 if PYPY else 50, verbosity=max(TestHypothesis.settings.verbosity, Verbosity.verbose), max_examples=10000 if MAIN else 200, ) if MAIN: TestHypothesis().runTest()
HypothesisSpec
python
kamyu104__LeetCode-Solutions
Python/most-frequent-prime.py
{ "start": 1644, "end": 2378 }
class ____(object): def mostFrequentPrime(self, mat): """ :type mat: List[List[int]] :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)) def numbers(i, j, di, dj): curr = 0 while 0 <= i < len(mat) and 0 <= j < len(mat[0]): curr = curr*10+mat[i][j] yield curr i, j = i+di, j+dj cnt = collections.Counter(x for i in xrange(len(mat)) for j in xrange(len(mat[0])) for di, dj in DIRECTIONS for x in numbers(i, j, di, dj) if x > 10) cnt[-1] = 0 return max((p for p in cnt.iterkeys() if is_prime(p) or p == -1), key=lambda x: (cnt[x], x))
Solution2
python
doocs__leetcode
solution/3200-3299/3280.Convert Date to Binary/Solution.py
{ "start": 0, "end": 133 }
class ____: def convertDateToBinary(self, date: str) -> str: return "-".join(f"{int(s):b}" for s in date.split("-"))
Solution
python
tartley__colorama
colorama/ansitowin32.py
{ "start": 2236, "end": 11112 }
class ____: ''' Implements a 'write()' method which, on Windows, will strip ANSI character sequences from the text, and if outputting to a tty, will convert them into win32 function calls. ''' ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # The wrapped stream (normally sys.stdout or sys.stderr) self.wrapped = wrapped # should we reset colors to defaults after every .write() self.autoreset = autoreset # create the proxy wrapping our output stream self.stream = StreamWrapper(wrapped, self) on_windows = os.name == 'nt' # We test if the WinAPI works, because even if we are on Windows # we may be using a terminal that doesn't support the WinAPI # (e.g. Cygwin Terminal). In this case it's up to the terminal # to support the ANSI codes. conversion_supported = on_windows and winapi_test() try: fd = wrapped.fileno() except Exception: fd = -1 system_has_native_ansi = not on_windows or enable_vt_processing(fd) have_tty = not self.stream.closed and self.stream.isatty() need_conversion = conversion_supported and not system_has_native_ansi # should we strip ANSI sequences from our output? if strip is None: strip = need_conversion or not have_tty self.strip = strip # should we should convert ANSI sequences into win32 calls? if convert is None: convert = need_conversion and have_tty self.convert = convert # dict of ansi codes to win32 functions and parameters self.win32_calls = self.get_win32_calls() # are we wrapping stderr? self.on_stderr = self.wrapped is sys.stderr def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init() ''' return self.convert or self.strip or self.autoreset def get_win32_calls(self): if self.convert and winterm: return { AnsiStyle.RESET_ALL: (winterm.reset_all, ), AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), AnsiFore.RED: (winterm.fore, WinColor.RED), AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), AnsiFore.WHITE: (winterm.fore, WinColor.GREY), AnsiFore.RESET: (winterm.fore, ), AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), AnsiBack.BLACK: (winterm.back, WinColor.BLACK), AnsiBack.RED: (winterm.back, WinColor.RED), AnsiBack.GREEN: (winterm.back, WinColor.GREEN), AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), AnsiBack.BLUE: (winterm.back, WinColor.BLUE), AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), AnsiBack.CYAN: (winterm.back, WinColor.CYAN), AnsiBack.WHITE: (winterm.back, WinColor.GREY), AnsiBack.RESET: (winterm.back, ), AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), } return dict() def write(self, text): if self.strip or self.convert: self.write_and_convert(text) else: self.wrapped.write(text) self.wrapped.flush() if self.autoreset: self.reset_all() def reset_all(self): if self.convert: self.call_win32('m', (0,)) elif not self.strip and not self.stream.closed: self.wrapped.write(Style.RESET_ALL) def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text)) def write_plain_text(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(command, paramstring) self.call_win32(command, params) def extract_params(self, command, paramstring): if command in 'Hf': params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) while len(params) < 2: # defaults: params = params + (1,) else: params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) if len(params) == 0: # defaults: if command in 'JKm': params = (0,) elif command in 'ABCD': params = (1,) return params def call_win32(self, command, params): if command == 'm': for param in params: if param in self.win32_calls: func_args = self.win32_calls[param] func = func_args[0] args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) elif command in 'J': winterm.erase_screen(params[0], on_stderr=self.on_stderr) elif command in 'K': winterm.erase_line(params[0], on_stderr=self.on_stderr) elif command in 'Hf': # cursor position - absolute winterm.set_cursor_position(params, on_stderr=self.on_stderr) elif command in 'ABCD': # cursor position - relative n = params[0] # A - up, B - down, C - forward, D - back x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) def convert_osc(self, text): for match in self.ANSI_OSC_RE.finditer(text): start, end = match.span() text = text[:start] + text[end:] paramstring, command = match.groups() if command == BEL: if paramstring.count(";") == 1: params = paramstring.split(";") # 0 - change title and icon (we will only change title) # 1 - change icon (we don't support this) # 2 - change title if params[0] in '02': winterm.set_title(params[1]) return text def flush(self): self.wrapped.flush()
AnsiToWin32
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol30.py
{ "start": 160, "end": 196 }
class ____(Protocol): v1: float
P1
python
realpython__materials
inheritance-and-composition/choosing/productivity.py
{ "start": 850, "end": 960 }
class ____: def perform_duties(self, hours): return f"expends {hours} hours on the phone."
SalesRole
python
kamyu104__LeetCode-Solutions
Python/closest-node-to-path-in-tree.py
{ "start": 1159, "end": 2444 }
class ____(object): # Time: O(N), Space: O(N + Q), N is the number of nodes def __init__(self, children, pairs): def preprocess(curr, parent): # depth of the node i D[curr] = 1 if parent == -1 else D[parent]+1 def divide(curr, parent): stk.append(partial(postprocess, curr)) for i in reversed(xrange(len(children[curr]))): child = children[curr][i] if child == parent: continue stk.append(partial(conquer, child, curr)) stk.append(partial(divide, child, curr)) stk.append(partial(preprocess, curr, parent)) def conquer(curr, parent): uf.union_set(curr, parent) uf.update_ancestor_of_set(parent) def postprocess(u): lookup[u] = True for v in pairs[u]: if not lookup[v]: continue lca[min(u, v), max(u, v)] = uf.find_ancestor_of_set(v) N = len(children) D, uf, lca = [0]*N, UnionFind(N), {} stk, lookup = [], [False]*N stk.append(partial(divide, 0, -1)) while stk: stk.pop()() self.D, self.lca = D, lca # Tarjan's Offline LCA Algorithm
TreeInfos
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 33691, "end": 34451 }
class ____(SetitemCastingEquivalents): # Setting compatible NA values into Series with PeriodDtype @pytest.fixture def expected(self, key): exp = Series(period_range("2000-01-01", periods=10, freq="D")) exp._values.view("i8")[key] = NaT._value assert exp[key] is NaT or all(x is NaT for x in exp[key]) return exp @pytest.fixture def obj(self): return Series(period_range("2000-01-01", periods=10, freq="D")) @pytest.fixture(params=[3, slice(3, 5)]) def key(self, request): return request.param @pytest.fixture(params=[None, np.nan]) def val(self, request): return request.param @pytest.fixture def raises(self): return False
TestSetitemNAPeriodDtype
python
getsentry__sentry
src/sentry/snuba/metrics/fields/base.py
{ "start": 19585, "end": 25021 }
class ____(ABC): @abstractmethod def validate_can_orderby(self) -> None: """ Validate that the expression can be used to order a query """ raise NotImplementedError @abstractmethod def get_entity( self, projects: QuerySet[Project] | Sequence[Project], use_case_id: UseCaseID ) -> MetricEntity | dict[MetricEntity | None, list[str]]: """ Method that generates the entity of an instance of MetricsFieldBase. `entity` property will always be None for instances of DerivedMetric that rely on constituent metrics that span multiple entities. """ raise NotImplementedError @abstractmethod def generate_metric_ids(self, projects: Sequence[Project], use_case_id: UseCaseID) -> set[int]: """ Method that generates all the metric ids required to query an instance of MetricsFieldBase """ raise NotImplementedError @abstractmethod def generate_select_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: """ Method that generates a list of SnQL functions required to query an instance of MetricsFieldBase """ raise NotImplementedError @abstractmethod def generate_orderby_clause( self, direction: Direction, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[OrderBy]: """ Method that generates a list of SnQL OrderBy clauses based on an instance of MetricsFieldBase """ raise NotImplementedError @abstractmethod def generate_default_null_values(self) -> int | list[tuple[float]] | None: """ Method that generates the appropriate default value for an instance of MetricsFieldBase """ raise NotImplementedError @abstractmethod def run_post_query_function( self, data: SnubaDataType, alias: str, params: MetricOperationParams | None = None, idx: int | None = None, ) -> Any: """ Method that runs functions on the values returned from the query """ raise NotImplementedError @abstractmethod def generate_bottom_up_derived_metrics_dependencies( self, alias: str ) -> Iterable[tuple[MetricOperationType | None, str, str]]: """ Function that builds a metrics dependency list from a derived metric_tree As an example, let's consider the `session.errored` derived metric session.errored / \ / session.errored_preaggregated / session.errored_set This function would generate a bottom up dependency list that would look something like this ["session.errored_set", "session.errored_preaggregated", "session.errored"] This is necessary especially for instances of `CompositeEntityDerivedMetric` because these do not have a direct mapping to a query alias but are rather computed post query, and so to calculate the value of that field we would need to guarantee that the values of its constituent metrics are computed first. This is more apparent when the dependency tree contains multiple levels of instances of `CompositeEntityDerivedMetric`. Following up with our example, session.errored / \ / composite_entity_derived_metric / \ / session.errored_preaggregated / session.errored_set In this modified example, our dependency list would change to [ "session.errored_set", "session.errored_preaggregated", "composite_entity_derived_metric", "session.errored" ] And this order is necessary because we would loop over this list to compute `composite_entity_derived_metric` first which does not have a direct mapping to a query alias before we are able to compute `session.errored` which also does not have a direct query alias """ raise NotImplementedError @abstractmethod def generate_groupby_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: """ Method that generates a list of SnQL groupby statements based on whether an instance of MetricsFieldBase supports it """ raise NotImplementedError @abstractmethod def generate_where_statements( self, projects: Sequence[Project], use_case_id: UseCaseID, alias: str, params: MetricOperationParams | None = None, ) -> list[Function]: """ Method that generates a list of SnQL where statements based on whether an instance of MetricsFieldBase supports it """ raise NotImplementedError @abstractmethod def get_meta_type(self) -> str | None: """ Method that returns the snuba meta type of an instance of MetricsFieldBase """ raise NotImplementedError @dataclass
MetricExpressionBase
python
PyCQA__pylint
doc/data/messages/i/invalid-bool-returned/bad.py
{ "start": 0, "end": 121 }
class ____: """__bool__ returns an int""" def __bool__(self): # [invalid-bool-returned] return 1
CustomBool
python
getsentry__sentry-python
tests/integrations/asgi/test_asgi.py
{ "start": 13808, "end": 13863 }
class ____: def __call__(): pass
MockAsgi2App
python
weaviate__weaviate-python-client
weaviate/collections/classes/cluster.py
{ "start": 566, "end": 739 }
class ____: """The statistics of a collection.""" object_count: int shard_count: int Shards = List[Shard] Sh = TypeVar("Sh") St = TypeVar("St") @dataclass
Stats
python
pydantic__pydantic
pydantic-core/tests/benchmarks/test_micro_benchmarks.py
{ "start": 39364, "end": 44910 }
class ____(str, Enum): foo = 'foo_val' bar = 'bar_val' baz = 'baz_val' LARGE_STR_PREFIX = 'a' * 50 @pytest.mark.benchmark(group='validate_literal') @pytest.mark.parametrize( 'allowed_values,input,expected_val_res', [ (list(range(5)), 4, 4), ([f'abc{i}' for i in range(5)], 'abc4', 'abc4'), ([LARGE_STR_PREFIX + f'{i}' for i in range(5)], f'{LARGE_STR_PREFIX}4', f'{LARGE_STR_PREFIX}4'), ([SomeStrEnum.foo, SomeStrEnum.bar], SomeStrEnum.bar, SomeStrEnum.bar), (list(range(100)), 5, 5), ([f'abc{i}' for i in range(100)], 'abc99', 'abc99'), ([LARGE_STR_PREFIX + f'{i}' for i in range(100)], f'{LARGE_STR_PREFIX}99', f'{LARGE_STR_PREFIX}99'), (['null', None, -1, SomeStrEnum.baz], None, None), ], ids=[ 'few_ints', 'few_small_strings', 'few_large_strings', 'few_str_enum', 'many_ints', 'many_small_strings', 'many_large_strings', 'few_mixed', ], ) @pytest.mark.parametrize('py_or_json', ['python', 'json']) def test_validate_literal( benchmark: Any, allowed_values: list[Any], input: Any, expected_val_res: Any, py_or_json: str ) -> None: validator = SchemaValidator(core_schema.literal_schema(expected=allowed_values)) if py_or_json == 'python': res = validator.validate_python(input) assert res == expected_val_res benchmark(validator.validate_python, input) else: input_json = json.dumps(input) res = validator.validate_json(input_json) assert res == expected_val_res benchmark(validator.validate_json, input_json) @pytest.mark.benchmark(group='root_model') def test_core_root_model(benchmark): class MyModel: __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' root: list[int] v = SchemaValidator( core_schema.model_schema(MyModel, core_schema.list_schema(core_schema.int_schema()), root_model=True) ) assert v.validate_python([1, 2, '3']).root == [1, 2, 3] input_data = list(range(100)) benchmark(v.validate_python, input_data) @pytest.mark.benchmark(group='strict_int') def test_strict_int(benchmark): v = SchemaValidator(core_schema.int_schema(strict=True)) benchmark(v.validate_python, 42) @pytest.mark.benchmark(group='strict_int') def test_strict_int_fails(benchmark): v = SchemaValidator(core_schema.int_schema(strict=True)) @benchmark def t(): try: v.validate_python(()) except ValidationError: pass @pytest.mark.benchmark(group='int_range') def test_int_range(benchmark): v = SchemaValidator(core_schema.int_schema(gt=0, lt=100)) assert v.validate_python(42) == 42 with pytest.raises(ValidationError, match='Input should be greater than 0'): v.validate_python(0) benchmark(v.validate_python, 42) @pytest.mark.benchmark(group='int_range') def test_int_range_json(benchmark): v = SchemaValidator(core_schema.int_schema(gt=0, lt=100)) assert v.validate_json('42') == 42 with pytest.raises(ValidationError, match='Input should be greater than 0'): v.validate_python('0') benchmark(v.validate_json, '42') @pytest.mark.benchmark(group='tagged_union_ints') def test_tagged_union_int_keys_python(benchmark): inner_schema = core_schema.typed_dict_schema( { 'x': core_schema.typed_dict_field(core_schema.int_schema()), 'y': core_schema.typed_dict_field(core_schema.int_schema()), } ) v = SchemaValidator(core_schema.tagged_union_schema({x: inner_schema for x in range(1000)}, discriminator='x')) payload = {'x': 999, 'y': '1'} assert v.validate_python(payload) == {'x': 999, 'y': 1} with pytest.raises( ValidationError, match="Input tag '1001' found using 'x' does not match any of the expected tags" ): v.validate_python({'x': 1001, 'y': '1'}) benchmark(v.validate_python, payload) @pytest.mark.benchmark(group='tagged_union_ints') def test_tagged_union_int_keys_json(benchmark): inner_schema = core_schema.typed_dict_schema( { 'x': core_schema.typed_dict_field(core_schema.int_schema()), 'y': core_schema.typed_dict_field(core_schema.int_schema()), } ) v = SchemaValidator(core_schema.tagged_union_schema({x: inner_schema for x in range(1000)}, discriminator='x')) payload = '{"x": 999, "y": "1"}' assert v.validate_json(payload) == {'x': 999, 'y': 1} with pytest.raises( ValidationError, match="Input tag '1001' found using 'x' does not match any of the expected tags" ): v.validate_json('{"x": 1001, "y": "1"}') benchmark(v.validate_json, payload) @skip_pypy_deep_stack @skip_wasm_deep_stack @pytest.mark.benchmark(group='field_function_validator') def test_field_function_validator(benchmark) -> None: def f(v: int, info: core_schema.ValidationInfo) -> int: assert info.field_name == 'x' return v + 1 schema: core_schema.CoreSchema = core_schema.int_schema() limit = pydantic_core._pydantic_core._recursion_limit - 3 for _ in range(limit): schema = core_schema.with_info_after_validator_function(f, schema) schema = core_schema.typed_dict_schema({'x': core_schema.typed_dict_field(schema)}) v = SchemaValidator(schema) payload = {'x': 0} assert v.validate_python(payload) == {'x': limit} benchmark(v.validate_python, payload)
SomeStrEnum
python
facelessuser__soupsieve
tests/test_level3/test_nth_of_type.py
{ "start": 58, "end": 1669 }
class ____(util.TestCase): """Test `nth` of type selectors.""" def test_nth_of_type(self): """Test `nth` of type.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-of-type(3)", ['7'], flags=util.HTML ) def test_nth_of_type_complex(self): """Test `nth` of type complex.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-of-type(2n + 1)", ['0', '7', '9'], flags=util.HTML ) self.assert_selector( markup, "span:nth-of-type(2n + 1)", ['2', '4', '6'], flags=util.HTML ) self.assert_selector( markup, "body :nth-of-type(2n + 1)", ['0', '2', '4', '6', '7', '9'], flags=util.HTML )
TestNthOfType
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 53903, "end": 54151 }
class ____(BatchRequest): """ Adds a batch of events in a single call (json-lines format, stream-friendly) """ _service = "events" _action = "add_batch" _version = "2.23" _batched_request_cls = AddRequest
AddBatchRequest
python
huggingface__transformers
src/transformers/utils/generic.py
{ "start": 14667, "end": 14906 }
class ____(ExplicitEnum): """ Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ PYTORCH = "pt" NUMPY = "np" MLX = "mlx"
TensorType
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 230114, "end": 233557 }
class ____(Request): """ Delete task hyper parameters :param task: Task ID :type task: str :param hyperparams: List of hyper parameters to delete. In case a parameter with an empty name is passed all the section will be deleted :type hyperparams: Sequence[ParamKey] :param force: If set to True then both new and running task hyper params can be deleted. Otherwise only the new task ones. Default is False :type force: bool """ _service = "tasks" _action = "delete_hyper_params" _version = "2.23" _schema = { "definitions": { "param_key": { "properties": { "name": { "description": ( "Name of the parameter. If the name is ommitted then the corresponding operation is" " performed on the whole section" ), "type": ["string", "null"], }, "section": { "description": "Section that the parameter belongs to", "type": ["string", "null"], }, }, "type": "object", } }, "properties": { "force": { "description": ( "If set to True then both new and running task hyper params can be deleted. Otherwise only the new" " task ones. Default is False" ), "type": "boolean", }, "hyperparams": { "description": ( "List of hyper parameters to delete. In case a parameter with an empty name is passed all the" " section will be deleted" ), "items": {"$ref": "#/definitions/param_key"}, "type": "array", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task", "hyperparams"], "type": "object", } def __init__(self, task, hyperparams, force=None, **kwargs): super(DeleteHyperParamsRequest, self).__init__(**kwargs) self.task = task self.hyperparams = hyperparams self.force = force @schema_property("task") def task(self): return self._property_task @task.setter def task(self, value): if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("hyperparams") def hyperparams(self): return self._property_hyperparams @hyperparams.setter def hyperparams(self, value): if value is None: self._property_hyperparams = None return self.assert_isinstance(value, "hyperparams", (ParamKey, dict), is_array=True) value = [(ParamKey(**v) if isinstance(v, dict) else v) for v in value] self._property_hyperparams = value @schema_property("force") def force(self): return self._property_force @force.setter def force(self, value): if value is None: self._property_force = None return self.assert_isinstance(value, "force", (bool,)) self._property_force = value
DeleteHyperParamsRequest
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 17577, "end": 17830 }
class ____(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): def do(self, a, b, tags): ev = linalg.eigvals(a) evalues, evectors = linalg.eig(a) assert_almost_equal(ev, evalues) @instantiate_parametrized_tests
EigvalsCases
python
chroma-core__chroma
chromadb/test/configurations/test_collection_configuration.py
{ "start": 57131, "end": 57229 }
class ____(TypedDict): task: str @register_embedding_function
CustomEmbeddingFunctionQueryConfig
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/connectors/test_data_connector.py
{ "start": 19005, "end": 27257 }
class ____: def overridden_func(self, batch, *args, **kwargs): return batch def reset_instances(self): warning_cache.clear() return BoringDataModule(), BoringModel(), Trainer() def test_no_datamodule_no_overridden(self, hook_name): model, _, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=None) with no_warning_call(match=f"have overridden `{hook_name}` in"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is model def test_with_datamodule_no_overridden(self, hook_name): model, dm, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=dm) with no_warning_call(match=f"have overridden `{hook_name}` in"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is model def test_override_model_hook(self, hook_name): model, dm, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=dm) with no_warning_call(match=f"have overridden `{hook_name}` in"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is model def test_override_datamodule_hook(self, hook_name): model, dm, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=dm) setattr(dm, hook_name, self.overridden_func) with no_warning_call(match=f"have overridden `{hook_name}` in"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is dm def test_override_both_model_and_datamodule(self, hook_name): model, dm, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=dm) setattr(model, hook_name, self.overridden_func) setattr(dm, hook_name, self.overridden_func) with pytest.warns(UserWarning, match=f"have overridden `{hook_name}` in both"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is dm def test_with_datamodule_override_model(self, hook_name): model, dm, trainer = self.reset_instances() trainer._data_connector.attach_datamodule(model, datamodule=dm) setattr(model, hook_name, self.overridden_func) with pytest.warns(UserWarning, match=f"have overridden `{hook_name}` in `LightningModule`"): instance = trainer._data_connector._datahook_selector.get_instance(hook_name) assert instance is model def test_invalid_hook_passed_in_datahook_selector(): dh_selector = _DataHookSelector(BoringModel(), None) with pytest.raises(ValueError, match="is not a shared hook"): dh_selector.get_instance("setup") @pytest.mark.parametrize(("devices", "warn_context"), [(1, no_warning_call), (2, pytest.warns)]) def test_eval_distributed_sampler_warning(devices, warn_context): """Test that a warning is raised when `DistributedSampler` is used with evaluation.""" model = BoringModel() trainer = Trainer(strategy="ddp", devices=devices, accelerator="cpu") trainer.strategy.connect(model) trainer._data_connector.attach_data(model) trainer.state.fn = TrainerFn.VALIDATING with warn_context(PossibleUserWarning, match="multi-device settings use `DistributedSampler`"): trainer.validate_loop.setup_data() trainer.state.fn = TrainerFn.TESTING with warn_context(PossibleUserWarning, match="multi-device settings use `DistributedSampler`"): trainer.test_loop.setup_data() @pytest.mark.parametrize("shuffle", [True, False]) def test_eval_shuffle_with_distributed_sampler_replacement(shuffle): """Test that shuffle is not changed if set to True.""" class CustomModel(BoringModel): def val_dataloader(self): return DataLoader(RandomDataset(32, 64), shuffle=shuffle) trainer = Trainer(accelerator="cpu", devices=2, strategy="ddp") model = CustomModel() trainer.strategy.connect(model) trainer._data_connector.attach_data(model) trainer.fit_loop.epoch_loop.val_loop.setup_data() assert trainer.val_dataloaders.sampler.shuffle == shuffle def test_error_raised_with_insufficient_float_limit_train_dataloader(): batch_size = 16 dl = DataLoader(RandomDataset(32, batch_size * 9), batch_size=batch_size) trainer = Trainer(limit_train_batches=0.1) model = BoringModel() trainer.strategy.connect(model) trainer._data_connector.attach_data(model=model, train_dataloaders=dl) trainer.state.fn = TrainerFn.FITTING trainer.state.stage = RunningStage.TRAINING with pytest.raises( MisconfigurationException, match="Please increase the `limit_train_batches` argument. Try at least", ): trainer.fit_loop.setup_data() @pytest.mark.parametrize( ("trainer_fn_name", "dataloader_name"), [ ("fit", "train_dataloaders"), ("validate", "dataloaders"), ("test", "dataloaders"), ("predict", "dataloaders"), ], ) def test_attach_data_input_validation_with_none_dataloader(trainer_fn_name, dataloader_name, tmp_path): """Test that passing `Trainer.method(x_dataloader=None)` with no module-method implementations available raises an error.""" trainer = Trainer(default_root_dir=tmp_path, fast_dev_run=True) model = BoringModel() datamodule = BoringDataModule() trainer_fn = getattr(trainer, trainer_fn_name) # Pretend that these methods are not implemented model.train_dataloader = None model.val_dataloader = None model.test_dataloader = None model.predict_dataloader = None datamodule.train_dataloader = None datamodule.val_dataloader = None datamodule.test_dataloader = None datamodule.predict_dataloader = None with pytest.raises(TypeError, match=f"An invalid .*dataloader was passed to `Trainer.{trainer_fn_name}"): trainer_fn(model, **{dataloader_name: None}, datamodule=datamodule) with pytest.raises(TypeError, match=f"An invalid .*dataloader was passed to `Trainer.{trainer_fn_name}"): trainer_fn(model, **{dataloader_name: None}, datamodule=None) @pytest.mark.parametrize( ("trainer_fn_name", "dataloader_name", "stage"), [ ("fit", "train_dataloaders", RunningStage.TRAINING), ("validate", "dataloaders", RunningStage.VALIDATING), ("test", "dataloaders", RunningStage.TESTING), ("predict", "dataloaders", RunningStage.PREDICTING), ], ) @pytest.mark.parametrize("dataloader", [None, object(), [1, object()]]) def test_non_iterables_raise(tmp_path, trainer_fn_name, dataloader_name, stage, dataloader): model = BoringModel() # Pretend that these methods are not implemented model.train_dataloader = None model.val_dataloader = None model.test_dataloader = None model.predict_dataloader = None trainer = Trainer(default_root_dir=tmp_path, fast_dev_run=1) trainer_fn = getattr(trainer, trainer_fn_name) with pytest.raises( TypeError, match=rf"invalid dataloader was passed to `Trainer.{trainer_fn_name}\({dataloader_name}" ): trainer_fn(model, **{dataloader_name: dataloader}) dl_method = stage.dataloader_prefix + "_dataloader" setattr(model, dl_method, lambda: dataloader) with pytest.raises(TypeError, match=f"invalid dataloader was returned from `BoringModel.{dl_method}"): trainer_fn(model) def test_iterable_check_on_known_iterators(): """Test that we only call the `iter()` on the dataloader object if it isn't a known type.""" iterable = Mock() iterable.__iter__ = Mock(return_value=iter(range(3))) _check_dataloader_iterable(iterable, Mock(), Mock()) iterable.__iter__.assert_called_once() # If it's a datalaoder, we don't call the expensive `__iter__` method dataloader = Mock(spec=DataLoader) dataloader.__iter__ = Mock() _check_dataloader_iterable(dataloader, Mock(), Mock()) dataloader.__iter__.assert_not_called()
TestDataHookSelector
python
numba__numba
numba/tests/test_dyn_array.py
{ "start": 969, "end": 1500 }
class ____(TestCase): def check_outputs(self, pyfunc, argslist, exact=True): cfunc = nrtjit(pyfunc) for args in argslist: expected = pyfunc(*args) ret = cfunc(*args) self.assertEqual(ret.size, expected.size) self.assertEqual(ret.dtype, expected.dtype) self.assertStridesEqual(ret, expected) if exact: np.testing.assert_equal(expected, ret) else: np.testing.assert_allclose(expected, ret)
BaseTest
python
FactoryBoy__factory_boy
tests/djapp/models.py
{ "start": 1068, "end": 1116 }
class ____(AbstractSon): pass
ConcreteGrandSon
python
pydantic__pydantic
pydantic/types.py
{ "start": 85792, "end": 86976 }
class ____(BaseModel): base64_str: Base64Str # Initialize the model with base64 data m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y') # Access decoded value print(m.base64_str) #> These aren't the droids you're looking for # Serialize into the base64 form print(m.model_dump()) #> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y'} # Validate base64 data try: print(Model(base64_str='undecodable').base64_str) except ValidationError as e: print(e) ''' 1 validation error for Model base64_str Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str] ''' ``` """ Base64UrlBytes = Annotated[bytes, EncodedBytes(encoder=Base64UrlEncoder)] """A bytes type that is encoded and decoded using the URL-safe base64 encoder. Note: Under the hood, `Base64UrlBytes` use standard library `base64.urlsafe_b64encode` and `base64.urlsafe_b64decode` functions. As a result, the `Base64UrlBytes` type can be used to faithfully decode "vanilla" base64 data (using `'+'` and `'/'`). ```python from pydantic import Base64UrlBytes, BaseModel
Model
python
aio-libs__aiohttp
aiohttp/_websocket/models.py
{ "start": 2288, "end": 2449 }
class ____(NamedTuple): data: None = None size: int = 0 extra: str | None = None type: Literal[WSMsgType.CLOSED] = WSMsgType.CLOSED
WSMessageClosed
python
django__django
tests/foreign_object/test_tuple_lookups.py
{ "start": 380, "end": 19564 }
class ____(TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() cls.customer_1 = Customer.objects.create(customer_id=1, company="a") cls.customer_2 = Customer.objects.create(customer_id=1, company="b") cls.customer_3 = Customer.objects.create(customer_id=2, company="c") cls.customer_4 = Customer.objects.create(customer_id=3, company="d") cls.customer_5 = Customer.objects.create(customer_id=1, company="e") cls.contact_1 = Contact.objects.create(customer=cls.customer_1) cls.contact_2 = Contact.objects.create(customer=cls.customer_1) cls.contact_3 = Contact.objects.create(customer=cls.customer_2) cls.contact_4 = Contact.objects.create(customer=cls.customer_3) cls.contact_5 = Contact.objects.create(customer=cls.customer_1) cls.contact_6 = Contact.objects.create(customer=cls.customer_5) def test_exact(self): test_cases = ( (self.customer_1, (self.contact_1, self.contact_2, self.contact_5)), (self.customer_2, (self.contact_3,)), (self.customer_3, (self.contact_4,)), (self.customer_4, ()), (self.customer_5, (self.contact_6,)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer=customer).order_by("id"), contacts ) with self.subTest( "filter(TupleExact)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleExact(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_exact_subquery(self): msg = ( "The QuerySet value for the exact lookup must have 2 selected " "fields (received 1)" ) with self.assertRaisesMessage(ValueError, msg): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer=subquery).order_by("id"), () ) def test_in(self): cust_1, cust_2, cust_3, cust_4, cust_5 = ( self.customer_1, self.customer_2, self.customer_3, self.customer_4, self.customer_5, ) c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( ((), ()), ((cust_1,), (c1, c2, c5)), ((cust_1, cust_2), (c1, c2, c3, c5)), ((cust_1, cust_2, cust_3), (c1, c2, c3, c4, c5)), ((cust_1, cust_2, cust_3, cust_4), (c1, c2, c3, c4, c5)), ((cust_1, cust_2, cust_3, cust_4, cust_5), (c1, c2, c3, c4, c5, c6)), ) for customers, contacts in test_cases: with self.subTest( "filter(customer__in=customers)", customers=customers, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__in=customers).order_by("id"), contacts, ) with self.subTest( "filter(TupleIn)", customers=customers, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = [(c.customer_id, c.company) for c in customers] lookup = TupleIn(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) @skipUnlessDBFeature("allow_sliced_subqueries_with_in") def test_in_subquery(self): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__in=subquery).order_by("id"), (self.contact_1, self.contact_2, self.contact_5), ) def test_tuple_in_subquery_must_be_query(self): lhs = (F("customer_code"), F("company_code")) # If rhs is any non-Query object with an as_sql() function. rhs = In(F("customer_code"), [1, 2, 3]) with self.assertRaisesMessage( ValueError, "'in' subquery lookup of ('customer_code', 'company_code') " "must be a Query object (received 'In')", ): TupleIn(lhs, rhs) def test_tuple_in_subquery_must_have_2_fields(self): lhs = (F("customer_code"), F("company_code")) rhs = Customer.objects.values_list("customer_id").query msg = ( "The QuerySet value for the 'in' lookup must have 2 selected " "fields (received 1)" ) with self.assertRaisesMessage(ValueError, msg): TupleIn(lhs, rhs) def test_tuple_in_subquery(self): customers = Customer.objects.values_list("customer_id", "company") test_cases = ( (self.customer_1, (self.contact_1, self.contact_2, self.contact_5)), (self.customer_2, (self.contact_3,)), (self.customer_3, (self.contact_4,)), (self.customer_4, ()), (self.customer_5, (self.contact_6,)), ) for customer, contacts in test_cases: lhs = (F("customer_code"), F("company_code")) rhs = customers.filter(id=customer.id).query lookup = TupleIn(lhs, rhs) qs = Contact.objects.filter(lookup).order_by("id") with self.subTest(customer=customer.id, query=str(qs.query)): self.assertSequenceEqual(qs, contacts) def test_tuple_in_rhs_must_be_collection_of_tuples_or_lists(self): test_cases = ( (1, 2, 3), ((1, 2), (3, 4), None), ) for rhs in test_cases: with self.subTest(rhs=rhs): with self.assertRaisesMessage( ValueError, "'in' lookup of ('customer_code', 'company_code') " "must be a collection of tuples or lists", ): TupleIn((F("customer_code"), F("company_code")), rhs) def test_tuple_in_rhs_must_have_2_elements_each(self): test_cases = ( ((),), ((1,),), ((1, 2, 3),), ) for rhs in test_cases: with self.subTest(rhs=rhs): with self.assertRaisesMessage( ValueError, "'in' lookup of ('customer_code', 'company_code') " "must have 2 elements each", ): TupleIn((F("customer_code"), F("company_code")), rhs) def test_lt(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, ()), (self.customer_2, (c1, c2, c5)), (self.customer_5, (c1, c2, c3, c5)), (self.customer_3, (c1, c2, c3, c5, c6)), (self.customer_4, (c1, c2, c3, c4, c5, c6)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__lt=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__lt=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleLessThan)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleLessThan(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_lt_subquery(self): with self.assertRaisesMessage( ValueError, "'lt' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__lt=subquery).order_by("id"), () ) def test_lte(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, (c1, c2, c5)), (self.customer_2, (c1, c2, c3, c5)), (self.customer_5, (c1, c2, c3, c5, c6)), (self.customer_3, (c1, c2, c3, c4, c5, c6)), (self.customer_4, (c1, c2, c3, c4, c5, c6)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__lte=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__lte=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleLessThanOrEqual)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleLessThanOrEqual(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_lte_subquery(self): with self.assertRaisesMessage( ValueError, "'lte' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__lte=subquery).order_by("id"), () ) def test_gt(self): test_cases = ( (self.customer_1, (self.contact_3, self.contact_4, self.contact_6)), (self.customer_2, (self.contact_4, self.contact_6)), (self.customer_5, (self.contact_4,)), (self.customer_3, ()), (self.customer_4, ()), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__gt=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__gt=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleGreaterThan)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleGreaterThan(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_gt_subquery(self): with self.assertRaisesMessage( ValueError, "'gt' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__gt=subquery).order_by("id"), () ) def test_gte(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, (c1, c2, c3, c4, c5, c6)), (self.customer_2, (c3, c4, c6)), (self.customer_5, (c4, c6)), (self.customer_3, (c4,)), (self.customer_4, ()), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__gte=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__gte=customer).order_by("pk"), contacts, ) with self.subTest( "filter(TupleGreaterThanOrEqual)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleGreaterThanOrEqual(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_gte_subquery(self): with self.assertRaisesMessage( ValueError, "'gte' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__gte=subquery).order_by("id"), () ) def test_isnull(self): contacts = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) with self.subTest("filter(customer__isnull=True)"): self.assertSequenceEqual( Contact.objects.filter(customer__isnull=True).order_by("id"), (), ) with self.subTest("filter(TupleIsNull(True))"): lhs = (F("customer_code"), F("company_code")) lookup = TupleIsNull(lhs, True) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), (), ) with self.subTest("filter(customer__isnull=False)"): self.assertSequenceEqual( Contact.objects.filter(customer__isnull=False).order_by("id"), contacts, ) with self.subTest("filter(TupleIsNull(False))"): lhs = (F("customer_code"), F("company_code")) lookup = TupleIsNull(lhs, False) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts, ) def test_isnull_subquery(self): with self.assertRaisesMessage( ValueError, "'isnull' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=0)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__isnull=subquery).order_by("id"), () ) def test_lookup_errors(self): m_2_elements = "'%s' lookup of 'customer' must have 2 elements" m_2_elements_each = "'in' lookup of 'customer' must have 2 elements each" test_cases = ( ({"customer": 1}, m_2_elements % "exact"), ({"customer": (1, 2, 3)}, m_2_elements % "exact"), ({"customer__in": (1, 2, 3)}, m_2_elements_each), ({"customer__in": ("foo", "bar")}, m_2_elements_each), ({"customer__gt": 1}, m_2_elements % "gt"), ({"customer__gt": (1, 2, 3)}, m_2_elements % "gt"), ({"customer__gte": 1}, m_2_elements % "gte"), ({"customer__gte": (1, 2, 3)}, m_2_elements % "gte"), ({"customer__lt": 1}, m_2_elements % "lt"), ({"customer__lt": (1, 2, 3)}, m_2_elements % "lt"), ({"customer__lte": 1}, m_2_elements % "lte"), ({"customer__lte": (1, 2, 3)}, m_2_elements % "lte"), ) for kwargs, message in test_cases: with ( self.subTest(kwargs=kwargs), self.assertRaisesMessage(ValueError, message), ): Contact.objects.get(**kwargs) def test_tuple_lookup_names(self): test_cases = ( (TupleExact, "exact"), (TupleGreaterThan, "gt"), (TupleGreaterThanOrEqual, "gte"), (TupleLessThan, "lt"), (TupleLessThanOrEqual, "lte"), (TupleIn, "in"), (TupleIsNull, "isnull"), ) for lookup_class, lookup_name in test_cases: with self.subTest(lookup_name): self.assertEqual(lookup_class.lookup_name, lookup_name) def test_tuple_lookup_rhs_must_be_tuple_or_list(self): test_cases = itertools.product( ( TupleExact, TupleGreaterThan, TupleGreaterThanOrEqual, TupleLessThan, TupleLessThanOrEqual, TupleIn, ), ( 0, 1, None, True, False, {"foo": "bar"}, ), ) for lookup_cls, rhs in test_cases: lookup_name = lookup_cls.lookup_name with self.subTest(lookup_name=lookup_name, rhs=rhs): with self.assertRaisesMessage( ValueError, f"'{lookup_name}' lookup of ('customer_code', 'company_code') " "must be a tuple or a list", ): lookup_cls((F("customer_code"), F("company_code")), rhs) def test_tuple_lookup_rhs_must_have_2_elements(self): test_cases = itertools.product( ( TupleExact, TupleGreaterThan, TupleGreaterThanOrEqual, TupleLessThan, TupleLessThanOrEqual, ), ( [], [1], [1, 2, 3], (), (1,), (1, 2, 3), ), ) for lookup_cls, rhs in test_cases: lookup_name = lookup_cls.lookup_name with self.subTest(lookup_name=lookup_name, rhs=rhs): with self.assertRaisesMessage( ValueError, f"'{lookup_name}' lookup of ('customer_code', 'company_code') " "must have 2 elements", ): lookup_cls((F("customer_code"), F("company_code")), rhs)
TupleLookupsTests
python
doocs__leetcode
solution/3300-3399/3310.Remove Methods From Project/Solution.py
{ "start": 0, "end": 887 }
class ____: def remainingMethods( self, n: int, k: int, invocations: List[List[int]] ) -> List[int]: def dfs(i: int): suspicious[i] = True for j in g[i]: if not suspicious[j]: dfs(j) def dfs2(i: int): vis[i] = True for j in f[i]: if not vis[j]: suspicious[j] = False dfs2(j) f = [[] for _ in range(n)] g = [[] for _ in range(n)] for a, b in invocations: f[a].append(b) f[b].append(a) g[a].append(b) suspicious = [False] * n dfs(k) vis = [False] * n ans = [] for i in range(n): if not suspicious[i] and not vis[i]: dfs2(i) return [i for i in range(n) if not suspicious[i]]
Solution
python
getsentry__sentry
src/sentry/migrations/0973_safe_del_dashboardwidgetsnapshot.py
{ "start": 240, "end": 1509 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0972_commit_comparison_drop_unique"), ] operations = [ SafeDeleteModel( name="DashboardWidgetSnapshot", deletion_action=DeletionAction.DELETE, ) ]
Migration
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_set_output.py
{ "start": 13453, "end": 14024 }
class ____(_SetOutputMixin): def __init__(self, OutputTuple): self.OutputTuple = OutputTuple def transform(self, X, y=None): return self.OutputTuple(X, 2 * X) def test_set_output_named_tuple_out(): """Check that namedtuples are kept by default.""" Output = namedtuple("Output", "X, Y") X = np.asarray([[1, 2, 3]]) est = EstimatorReturnTuple(OutputTuple=Output) X_trans = est.transform(X) assert isinstance(X_trans, Output) assert_array_equal(X_trans.X, X) assert_array_equal(X_trans.Y, 2 * X)
EstimatorReturnTuple
python
wandb__wandb
wandb/vendor/pygments/lexers/c_like.py
{ "start": 3314, "end": 4954 }
class ____(RegexLexer): """ For `Clay <http://claylabs.com/clay/>`_ source. .. versionadded:: 2.0 """ name = 'Clay' filenames = ['*.clay'] aliases = ['clay'] mimetypes = ['text/x-clay'] tokens = { 'root': [ (r'\s', Text), (r'//.*?$', Comment.Singleline), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'\b(public|private|import|as|record|variant|instance' r'|define|overload|default|external|alias' r'|rvalue|ref|forward|inline|noinline|forceinline' r'|enum|var|and|or|not|if|else|goto|return|while' r'|switch|case|break|continue|for|in|true|false|try|catch|throw' r'|finally|onerror|staticassert|eval|when|newtype' r'|__FILE__|__LINE__|__COLUMN__|__ARG__' r')\b', Keyword), (r'[~!%^&*+=|:<>/-]', Operator), (r'[#(){}\[\],;.]', Punctuation), (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex), (r'\d+[LlUu]*', Number.Integer), (r'\b(true|false)\b', Name.Builtin), (r'(?i)[a-z_?][\w?]*', Name), (r'"""', String, 'tdqs'), (r'"', String, 'dqs'), ], 'strings': [ (r'(?i)\\(x[0-9a-f]{2}|.)', String.Escape), (r'.', String), ], 'nl': [ (r'\n', String), ], 'dqs': [ (r'"', String, '#pop'), include('strings'), ], 'tdqs': [ (r'"""', String, '#pop'), include('strings'), include('nl'), ], }
ClayLexer
python
doocs__leetcode
solution/1700-1799/1766.Tree of Coprimes/Solution.py
{ "start": 0, "end": 887 }
class ____: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: def dfs(i, fa, depth): t = k = -1 for v in f[nums[i]]: stk = stks[v] if stk and stk[-1][1] > k: t, k = stk[-1] ans[i] = t for j in g[i]: if j != fa: stks[nums[i]].append((i, depth)) dfs(j, i, depth + 1) stks[nums[i]].pop() g = defaultdict(list) for u, v in edges: g[u].append(v) g[v].append(u) f = defaultdict(list) for i in range(1, 51): for j in range(1, 51): if gcd(i, j) == 1: f[i].append(j) stks = defaultdict(list) ans = [-1] * len(nums) dfs(0, -1, 0) return ans
Solution
python
python-markdown__markdown
markdown/test_tools.py
{ "start": 4070, "end": 4627 }
class ____(dict): """ A `dict` like class for holding keyword arguments. """ pass def _normalize_whitespace(text): """ Normalize whitespace for a string of HTML using `tidylib`. """ output, errors = tidylib.tidy_fragment(text, options={ 'drop_empty_paras': 0, 'fix_backslash': 0, 'fix_bad_comments': 0, 'fix_uri': 0, 'join_styles': 0, 'lower_literals': 0, 'merge_divs': 0, 'output_xhtml': 1, 'quote_ampersand': 0, 'newline': 'LF' }) return output
Kwargs
python
huggingface__transformers
tests/test_configuration_common.py
{ "start": 901, "end": 11998 }
class ____: def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs): self.parent = parent self.config_class = config_class self.has_text_modality = has_text_modality self.inputs_dict = kwargs self.common_properties = common_properties def create_and_test_config_common_properties(self): config = self.config_class(**self.inputs_dict) common_properties = ( ["hidden_size", "num_attention_heads", "num_hidden_layers"] if self.common_properties is None and not self.config_class.sub_configs else self.common_properties ) common_properties = [] if common_properties is None else common_properties # Add common fields for text models if self.has_text_modality: common_properties.extend(["vocab_size"]) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(config, prop), msg=f"`{prop}` does not exist") # Test that config has the common properties as setter for idx, name in enumerate(common_properties): try: setattr(config, name, idx) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(common_properties): try: config = self.config_class(**{name: idx}) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def create_and_test_config_to_json_string(self): config = self.config_class(**self.inputs_dict) obj = json.loads(config.to_json_string()) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], value) def create_and_test_config_to_json_file(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: json_file_path = os.path.join(tmpdirname, "config.json") config_first.to_json_file(json_file_path) config_second = self.config_class.from_json_file(json_file_path) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_from_and_save_pretrained(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(tmpdirname) config_second = self.config_class.from_pretrained(tmpdirname) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) with self.parent.assertRaises(OSError): self.config_class.from_pretrained(f".{tmpdirname}") def create_and_test_config_from_and_save_pretrained_subfolder(self): config_first = self.config_class(**self.inputs_dict) subfolder = "test" with tempfile.TemporaryDirectory() as tmpdirname: sub_tmpdirname = os.path.join(tmpdirname, subfolder) config_first.save_pretrained(sub_tmpdirname) config_second = self.config_class.from_pretrained(tmpdirname, subfolder=subfolder) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_from_and_save_pretrained_composite(self): """ Tests that composite or nested configs can be loaded and saved correctly. In case the config has a sub-config, we should be able to call `sub_config.from_pretrained('general_config_file')` and get a result same as if we loaded the whole config and obtained `config.sub_config` from it. """ config = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: config.save_pretrained(tmpdirname) general_config_loaded = self.config_class.from_pretrained(tmpdirname) general_config_dict = config.to_dict() # Iterate over all sub_configs if there are any and load them with their own classes sub_configs = general_config_loaded.sub_configs for sub_config_key, sub_class in sub_configs.items(): if general_config_dict[sub_config_key] is not None: if sub_class.__name__ == "AutoConfig": sub_class = sub_class.for_model(**general_config_dict[sub_config_key]).__class__ sub_config_loaded = sub_class.from_pretrained(tmpdirname) else: sub_config_loaded = sub_class.from_pretrained(tmpdirname) # Pop `transformers_version`, it never exists when a config is part of a general composite config # Verify that loading with subconfig class results in same dict as if we loaded with general composite config class sub_config_loaded_dict = sub_config_loaded.to_dict() sub_config_loaded_dict.pop("transformers_version", None) general_config_dict[sub_config_key].pop("transformers_version", None) self.parent.assertEqual(sub_config_loaded_dict, general_config_dict[sub_config_key]) # Verify that the loaded config type is same as in the general config type_from_general_config = type(getattr(general_config_loaded, sub_config_key)) self.parent.assertTrue(isinstance(sub_config_loaded, type_from_general_config)) # Now save only the sub-config and load it back to make sure the whole load-save-load pipeline works with tempfile.TemporaryDirectory() as tmpdirname2: sub_config_loaded.save_pretrained(tmpdirname2) sub_config_loaded_2 = sub_class.from_pretrained(tmpdirname2) self.parent.assertEqual(sub_config_loaded.to_dict(), sub_config_loaded_2.to_dict()) def create_and_test_config_from_pretrained_custom_kwargs(self): """ Tests that passing custom kwargs to the `from_pretrained` will overwrite model's saved config values. for composite configs. We should overwrite only the requested keys, keeping all values of the subconfig that are loaded from the checkpoint. """ # Check only composite configs. We can't know which attributes each type of config has so check # only text config because we are sure that all text configs have a `vocab_size` config = self.config_class(**self.inputs_dict) if config.get_text_config() is config or not hasattr(self.parent.model_tester, "get_config"): return # First create a config with non-default values and save it. The reload it back with a new # `vocab_size` and check that all values are loaded from checkpoint and not init from defaults non_default_inputs = self.parent.model_tester.get_config().to_dict() config = self.config_class(**non_default_inputs) original_text_config = config.get_text_config() text_config_key = [key for key in config if getattr(config, key) is original_text_config] # The heuristic is a bit brittle so let's just skip the test if len(text_config_key) != 1: return text_config_key = text_config_key[0] with tempfile.TemporaryDirectory() as tmpdirname: config.save_pretrained(tmpdirname) # Set vocab size to 20 tokens and reload from checkpoint and check if all keys/values are identical except for `vocab_size` config_reloaded = self.config_class.from_pretrained(tmpdirname, **{text_config_key: {"vocab_size": 20}}) original_text_config_dict = original_text_config.to_dict() original_text_config_dict["vocab_size"] = 20 text_config_reloaded_dict = config_reloaded.get_text_config().to_dict() self.parent.assertDictEqual(text_config_reloaded_dict, original_text_config_dict) def create_and_test_config_with_num_labels(self): config = self.config_class(**self.inputs_dict, num_labels=5) self.parent.assertEqual(len(config.id2label), 5) self.parent.assertEqual(len(config.label2id), 5) config.num_labels = 3 self.parent.assertEqual(len(config.id2label), 3) self.parent.assertEqual(len(config.label2id), 3) def check_config_can_be_init_without_params(self): if self.config_class.has_no_defaults_at_init: with self.parent.assertRaises(ValueError): config = self.config_class() else: config = self.config_class() self.parent.assertIsNotNone(config) def check_config_arguments_init(self): if self.config_class.sub_configs: return # TODO: @raushan composite models are not consistent in how they set general params kwargs = copy.deepcopy(config_common_kwargs) config = self.config_class(**kwargs) wrong_values = [] for key, value in config_common_kwargs.items(): if key == "dtype": if not is_torch_available(): continue else: import torch if config.dtype != torch.float16: wrong_values.append(("dtype", config.dtype, torch.float16)) elif getattr(config, key) != value: wrong_values.append((key, getattr(config, key), value)) if len(wrong_values) > 0: errors = "\n".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]) raise ValueError(f"The following keys were not properly set in the config:\n{errors}") def run_common_tests(self): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_from_and_save_pretrained_composite() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init() self.create_and_test_config_from_pretrained_custom_kwargs()
ConfigTester
python
getsentry__sentry
src/sentry/preprod/migrations/0006_add_analysis_file_id_field.py
{ "start": 186, "end": 1530 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("preprod", "0005_add_git_commit"), ] operations = [ migrations.AddField( model_name="preprodartifact", name="analysis_file_id", field=sentry.db.models.fields.bounded.BoundedBigIntegerField(db_index=True, null=True), ), ]
Migration
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py
{ "start": 11996, "end": 12064 }
class ____(AdsInsights): breakdowns = ["region"]
AdsInsightsRegion
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 57357, "end": 57802 }
class ____(WorkQueueCommandAction): """Pauses a Work Queue""" type: Literal["pause-work-queue"] = "pause-work-queue" _action_description: ClassVar[str] = "Pausing work queue" async def command( self, orchestration: "OrchestrationClient", work_queue_id: UUID, triggered_action: "TriggeredAction", ) -> Response: return await orchestration.pause_work_queue(work_queue_id)
PauseWorkQueue
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/cat_test.py
{ "start": 3316, "end": 4433 }
class ____(op_bench.TorchBenchmarkBase): def init(self, sizes, N, dim, device): random.seed(42) inputs = [] gen_sizes = [] if type(sizes) is list and N == -1: gen_sizes = sizes else: for i in range(N): gen_sizes.append( [ old_size() if callable(old_size) else old_size for old_size in sizes ] ) for s in gen_sizes: inputs.append(torch.rand(s, device=device)) result = torch.empty(0, device=device) self.inputs = {"result": result, "inputs": inputs, "dim": dim} self.set_module_name("cat") def forward(self, result: torch.Tensor, inputs: list[torch.Tensor], dim: int): return torch.cat(inputs, dim=dim, out=result) op_bench.generate_pt_test( cat_configs_short + cat_configs_long + cat_configs_multidim + cat_configs_manyinputs + cat_configs_static_runtime, CatBenchmark, ) if __name__ == "__main__": op_bench.benchmark_runner.main()
CatBenchmark
python
pandas-dev__pandas
doc/source/conf.py
{ "start": 19571, "end": 19803 }
class ____(AccessorLevelDocumenter, MethodDocumenter): objtype = "accessormethod" directivetype = "method" # lower than MethodDocumenter so this is not chosen for normal methods priority = 0.6
AccessorMethodDocumenter
python
django-extensions__django-extensions
tests/db/fields/test_uniq_field_mixin.py
{ "start": 346, "end": 5534 }
class ____(TestCase): def setUp(self): class MockField(UniqueFieldMixin): def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.uniq_field = MockField( attname="uniq_field", max_length=255, boolean_attr=True, non_boolean_attr="non_boolean_attr", ) f_dummy = DummyRelationModel.objects.create() s_dummy = SecondDummyRelationModel.objects.create() t_dummy = ThirdDummyRelationModel.objects.create() post = PostWithUniqField.objects.create( uniq_field="test_uniq", common_field="first", another_common_field="second", many_to_one_field=f_dummy, one_to_one_field=s_dummy, ) post.many_to_many_field.add(t_dummy) post.save() ReverseModel.objects.create(post_field=post) self.post = post def tearDown(self): PostWithUniqField.objects.all().delete() DummyRelationModel.objects.all().delete() SecondDummyRelationModel.objects.all().delete() ThirdDummyRelationModel.objects.all().delete() ReverseModel.objects.all().delete() def test_check_is_bool_boolean_attr(self): self.assertIsNone(self.uniq_field.check_is_bool("boolean_attr")) def test_check_is_bool_non_boolean_attr(self): with self.assertRaisesMessage( ValueError, "'non_boolean_attr' argument must be True or False", ): self.uniq_field.check_is_bool("non_boolean_attr") def test__get_fields_returns_list_of_tulpes(self): uniq_mixin_fields = UniqueFieldMixin._get_fields(PostWithUniqField) self.assertIsInstance(uniq_mixin_fields, list) for field in uniq_mixin_fields: self.assertIsInstance(field, tuple) def test__get_fields_returns_correct_fields(self): option_fields = PostWithUniqField._meta.get_fields() uniq_mixin_fields = [ i[0] for i in UniqueFieldMixin._get_fields(PostWithUniqField) ] self.assertEqual(len(option_fields), 9) self.assertEqual(len(uniq_mixin_fields), 7) fields_to_be_excluded_from_uniq_mixin_fields = [ f for f in option_fields if f.is_relation and not f.one_to_one and not (f.many_to_one and f.related_model) ] for field in fields_to_be_excluded_from_uniq_mixin_fields: self.assertNotIn(field, uniq_mixin_fields) def test__get_fields_returns_correct_model(self): post_models = [i[1] for i in UniqueFieldMixin._get_fields(PostWithUniqField)] self.assertTrue(all(model is None for model in post_models)) inherited_post_models = [ i[1] for i in UniqueFieldMixin._get_fields(InheritedFromPostWithUniqField) if i[1] ] self.assertEqual(len(inherited_post_models), 6) self.assertTrue( all(model is PostWithUniqField) for model in inherited_post_models ) def test_get_queryset(self): mocked_get_fields = ((models.CharField, PostWithUniqField),) with ( mock.patch( "django_extensions.db.fields.UniqueFieldMixin._get_fields", return_value=mocked_get_fields, ), mock.patch( "tests.testapp.models.PostWithUniqField._default_manager.all" ) as mocked_qs_all, ): self.uniq_field.get_queryset(PostWithUniqField, models.CharField) mocked_qs_all.assert_called_with() mocked_get_fields = ((models.CharField, None),) with ( mock.patch( "django_extensions.db.fields.UniqueFieldMixin._get_fields", return_value=mocked_get_fields, ), mock.patch( "tests.testapp.models.InheritedFromPostWithUniqField._default_manager.all" ) as mocked_qs_all, ): self.uniq_field.get_queryset( InheritedFromPostWithUniqField, models.CharField ) mocked_qs_all.assert_called_with() def test_find_unique(self): def filter_func(*args, **kwargs): uniq_field = kwargs.get("uniq_field") if uniq_field == "a": return mocked_qs return None mocked_qs = mock.Mock(spec=PostWithUniqField.objects) mocked_qs.filter.side_effect = filter_func mocked_qs.exclude.return_value = mocked_qs field = models.CharField with mock.patch( "django_extensions.db.fields.UniqueFieldMixin.get_queryset", return_value=mocked_qs, ) as get_qs: res = self.uniq_field.find_unique(self.post, field, iter("abcde")) get_qs.assert_called_with(PostWithUniqField, field) mocked_qs.exclude.assert_called_with(pk=self.post.pk) self.assertEqual(res, "b") self.assertTrue(hasattr(self.post, "uniq_field")) self.assertEqual(self.post.uniq_field, "b")
UniqFieldMixinTestCase
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 10864, "end": 10996 }
class ____(sqltypes.JSON.JSONIntIndexType): __visit_name__ = "json_int_index" render_bind_cast = True
AsyncpgJSONIntIndexType
python
python-poetry__poetry
tests/installation/test_executor.py
{ "start": 1570, "end": 54560 }
class ____(BaseChef): _directory_wheels: list[Path] | None = None _sdist_wheels: list[Path] | None = None def set_directory_wheel(self, wheels: Path | list[Path]) -> None: if not isinstance(wheels, list): wheels = [wheels] self._directory_wheels = wheels def set_sdist_wheel(self, wheels: Path | list[Path]) -> None: if not isinstance(wheels, list): wheels = [wheels] self._sdist_wheels = wheels def _prepare_sdist( self, archive: Path, destination: Path | None = None, config_settings: Mapping[str, str | Sequence[str]] | None = None, ) -> Path: if self._sdist_wheels is not None: wheel = self._sdist_wheels.pop(0) self._sdist_wheels.append(wheel) return wheel return super()._prepare_sdist(archive) def _prepare( self, directory: Path, destination: Path, *, editable: bool = False, config_settings: Mapping[str, str | Sequence[str]] | None = None, ) -> Path: if self._directory_wheels is not None: wheel = self._directory_wheels.pop(0) self._directory_wheels.append(wheel) destination.mkdir(parents=True, exist_ok=True) dst_wheel = destination / wheel.name shutil.copyfile(wheel, dst_wheel) return dst_wheel return super()._prepare(directory, destination, editable=editable) @pytest.fixture def env(tmp_path: Path) -> MockEnv: path = tmp_path / ".venv" path.mkdir(parents=True) return MockEnv(path=path, is_venv=True) @pytest.fixture def io() -> BufferedIO: io = BufferedIO() io.output.formatter.set_style("c1_dark", Style("cyan", options=["dark"])) io.output.formatter.set_style("c2_dark", Style("default", options=["bold", "dark"])) io.output.formatter.set_style("success_dark", Style("green", options=["dark"])) io.output.formatter.set_style("warning", Style("yellow")) return io @pytest.fixture def io_decorated() -> BufferedIO: io = BufferedIO(decorated=True) io.output.formatter.set_style("c1", Style("cyan")) io.output.formatter.set_style("success", Style("green")) return io @pytest.fixture def io_not_decorated() -> BufferedIO: io = BufferedIO(decorated=False) return io @pytest.fixture def pool(pypi_repository: PyPiRepository) -> RepositoryPool: pool = RepositoryPool() pypi_repository._fallback = True pool.add_repository(pypi_repository) return pool @pytest.fixture def copy_wheel(tmp_path: Path, fixture_dir: FixtureDirGetter) -> Callable[[], Path]: def _copy_wheel() -> Path: tmp_name = tempfile.mktemp() (tmp_path / tmp_name).mkdir() shutil.copyfile( fixture_dir("distributions") / "demo-0.1.2-py2.py3-none-any.whl", tmp_path / tmp_name / "demo-0.1.2-py2.py3-none-any.whl", ) return tmp_path / tmp_name / "demo-0.1.2-py2.py3-none-any.whl" return _copy_wheel @pytest.fixture def wheel(copy_wheel: Callable[[], Path]) -> Iterator[Path]: archive = copy_wheel() yield archive if archive.exists(): archive.unlink() def test_execute_executes_a_batch_of_operations( mocker: MockerFixture, config: Config, pool: RepositoryPool, io: BufferedIO, tmp_path: Path, env: MockEnv, copy_wheel: Callable[[], Path], fixture_dir: FixtureDirGetter, ) -> None: wheel_install = mocker.patch.object(WheelInstaller, "install") config.merge({"cache-dir": str(tmp_path)}) artifact_cache = ArtifactCache(cache_dir=config.artifacts_cache_directory) prepare_spy = mocker.spy(Chef, "_prepare") chef = Chef(artifact_cache, env, Factory.create_pool(config)) chef.set_directory_wheel([copy_wheel(), copy_wheel()]) chef.set_sdist_wheel(copy_wheel()) io.set_verbosity(Verbosity.VERY_VERBOSE) executor = Executor(env, pool, config, io) executor._chef = chef file_package = Package( "demo", "0.1.0", source_type="file", source_url=(fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl") .resolve() .as_posix(), ) directory_package = Package( "simple-project", "1.2.3", source_type="directory", source_url=fixture_dir("simple_project").resolve().as_posix(), ) git_package = Package( "demo", "0.1.0", source_type="git", source_reference="master", source_url="https://github.com/demo/demo.git", develop=True, ) return_code = executor.execute( [ Install(Package("pytest", "3.5.1")), Uninstall(Package("attrs", "17.4.0")), Update(Package("requests", "2.18.3"), Package("requests", "2.18.4")), Update(Package("pytest", "3.5.1"), Package("pytest", "3.5.0")), Uninstall(Package("clikit", "0.2.3")).skip("Not currently installed"), Install(file_package), Install(directory_package), Install(git_package), ] ) expected = f""" Package operations: 4 installs, 2 updates, 1 removal - Installing pytest (3.5.1) - Removing attrs (17.4.0) - Updating requests (2.18.3 -> 2.18.4) - Downgrading pytest (3.5.1 -> 3.5.0) - Installing demo (0.1.0 {file_package.source_url}) - Installing simple-project (1.2.3 {directory_package.source_url}) - Installing demo (0.1.0 master) """ expected_lines = set(expected.splitlines()) output_lines = set(io.fetch_output().splitlines()) assert output_lines == expected_lines assert wheel_install.call_count == 6 # 3 pip uninstalls: one for the remove operation and two for the update operations assert len(env.executed) == 3 assert return_code == 0 assert prepare_spy.call_count == 2 assert prepare_spy.call_args_list == [ mocker.call( chef, mocker.ANY, destination=mocker.ANY, editable=False, config_settings=None, ), mocker.call( chef, mocker.ANY, destination=mocker.ANY, editable=True, config_settings=None, ), ] def test_execute_build_config_settings_passed( mocker: MockerFixture, config: Config, pool: RepositoryPool, io: BufferedIO, tmp_path: Path, env: MockEnv, copy_wheel: Callable[[], Path], fixture_dir: FixtureDirGetter, ) -> None: wheel_install = mocker.patch.object(WheelInstaller, "install") config_settings_demo = {"CC": "gcc", "--build-option": ["--one", "--two"]} config.merge( { "cache-dir": str(tmp_path), "installer": {"build-config-settings": {"demo": config_settings_demo}}, } ) artifact_cache = ArtifactCache(cache_dir=config.artifacts_cache_directory) prepare_spy = mocker.spy(Chef, "_prepare") chef = Chef(artifact_cache, env, Factory.create_pool(config)) chef.set_directory_wheel([copy_wheel(), copy_wheel()]) chef.set_sdist_wheel(copy_wheel()) executor = Executor(env, pool, config, io) executor._chef = chef directory_package = Package( "simple-project", "1.2.3", source_type="directory", source_url=fixture_dir("simple_project").resolve().as_posix(), ) git_package = Package( "demo", "0.1.0", source_type="git", source_reference="master", source_url="https://github.com/demo/demo.git", develop=True, ) return_code = executor.execute( [ Install(directory_package), Install(git_package), ] ) expected = f""" Package operations: 2 installs, 0 updates, 0 removals - Installing simple-project (1.2.3 {directory_package.source_url}) - Installing demo (0.1.0 master) """ expected_lines = set(expected.splitlines()) output_lines = set(io.fetch_output().splitlines()) assert output_lines == expected_lines assert wheel_install.call_count == 2 assert return_code == 0 assert prepare_spy.call_count == 2 assert prepare_spy.call_args_list == [ mocker.call( chef, mocker.ANY, destination=mocker.ANY, editable=False, config_settings=None, ), mocker.call( chef, mocker.ANY, destination=mocker.ANY, editable=True, config_settings=config_settings_demo, ), ] @pytest.mark.parametrize( "operations, has_warning", [ ( [Install(Package("black", "21.11b0")), Install(Package("pytest", "3.5.1"))], True, ), ( [ Uninstall(Package("black", "21.11b0")), Uninstall(Package("pytest", "3.5.1")), ], False, ), ( [ Update(Package("black", "19.10b0"), Package("black", "21.11b0")), Update(Package("pytest", "3.5.0"), Package("pytest", "3.5.1")), ], True, ), ], ) def test_execute_prints_warning_for_yanked_package( config: Config, pool: RepositoryPool, io: BufferedIO, tmp_path: Path, env: MockEnv, operations: list[Operation], has_warning: bool, ) -> None: config.merge({"cache-dir": str(tmp_path)}) executor = Executor(env, pool, config, io) return_code = executor.execute(operations) expected = ( "Warning: The file chosen for install of black 21.11b0 " "(black-21.11b0-py3-none-any.whl) is yanked. Reason for being yanked: " "Broken regex dependency. Use 21.11b1 instead." ) output = io.fetch_output() error = io.fetch_error() assert return_code == 0, f"\noutput: {output}\nerror: {error}\n" assert "pytest" not in error if has_warning: assert expected in error assert error.count("is yanked") == 1 else: assert expected not in error assert error.count("yanked") == 0 @pytest.mark.skip(reason="https://github.com/python-poetry/poetry/issues/7983") def test_execute_prints_warning_for_invalid_wheels( config: Config, pool: RepositoryPool, io: BufferedIO, tmp_path: Path, env: MockEnv, ) -> None: config.merge({"cache-dir": str(tmp_path)}) executor = Executor(env, pool, config, io) base_url = "https://files.pythonhosted.org/" wheel1 = "demo_invalid_record-0.1.0-py2.py3-none-any.whl" wheel2 = "demo_invalid_record2-0.1.0-py2.py3-none-any.whl" return_code = executor.execute( [ Install( Package( "demo-invalid-record", "0.1.0", source_type="url", source_url=f"{base_url}/{wheel1}", ) ), Install( Package( "demo-invalid-record2", "0.1.0", source_type="url", source_url=f"{base_url}/{wheel2}", ) ), ] ) warning1 = f"""\ <warning>Warning: Validation of the RECORD file of {wheel1} failed.\ Please report to the maintainers of that package so they can fix their build process.\ Details: In .*?{wheel1}, demo/__init__.py is not mentioned in RECORD In .*?{wheel1}, demo_invalid_record-0.1.0.dist-info/WHEEL is not mentioned in RECORD """ warning2 = f"""\ <warning>Warning: Validation of the RECORD file of {wheel2} failed.\ Please report to the maintainers of that package so they can fix their build process.\ Details: In .*?{wheel2}, hash / size of demo_invalid_record2-0.1.0.dist-info/METADATA didn't\ match RECORD """ output = io.fetch_output() error = io.fetch_error() assert return_code == 0, f"\noutput: {output}\nerror: {error}\n" assert re.match(f"{warning1}\n{warning2}", error) or re.match( f"{warning2}\n{warning1}", error ), error def test_execute_shows_skipped_operations_if_verbose( config: Config, pool: RepositoryPool, io: BufferedIO, config_cache_dir: Path, env: MockEnv, ) -> None: config.merge({"cache-dir": config_cache_dir.as_posix()}) executor = Executor(env, pool, config, io) executor.verbose() assert ( executor.execute( [Uninstall(Package("clikit", "0.2.3")).skip("Not currently installed")] ) == 0 ) expected = """ Package operations: 0 installs, 0 updates, 0 removals, 1 skipped - Removing clikit (0.2.3): Skipped for the following reason: Not currently installed """ assert io.fetch_output() == expected assert len(env.executed) == 0 def test_execute_should_show_errors( config: Config, pool: RepositoryPool, mocker: MockerFixture, io: BufferedIO, env: MockEnv, ) -> None: executor = Executor(env, pool, config, io) executor.verbose() mocker.patch.object(executor, "_install", side_effect=Exception("It failed!")) assert executor.execute([Install(Package("clikit", "0.2.3"))]) == 1 expected = """ Package operations: 1 install, 0 updates, 0 removals - Installing clikit (0.2.3) Exception It failed! """ assert expected in io.fetch_output() def test_execute_works_with_ansi_output( config: Config, pool: RepositoryPool, io_decorated: BufferedIO, tmp_path: Path, env: MockEnv, ) -> None: config.merge({"cache-dir": str(tmp_path)}) executor = Executor(env, pool, config, io_decorated) return_code = executor.execute( [ Install(Package("cleo", "1.0.0a5")), ] ) # fmt: off expected = [ "\x1b[39;1mPackage operations\x1b[39;22m: \x1b[34m1\x1b[39m install, \x1b[34m0\x1b[39m updates, \x1b[34m0\x1b[39m removals", "\x1b[34;1m-\x1b[39;22m \x1b[39mInstalling \x1b[39m\x1b[36mcleo\x1b[39m\x1b[39m (\x1b[39m\x1b[39;1m1.0.0a5\x1b[39;22m\x1b[39m)\x1b[39m: \x1b[34mPending...\x1b[39m", "\x1b[34;1m-\x1b[39;22m \x1b[39mInstalling \x1b[39m\x1b[36mcleo\x1b[39m\x1b[39m (\x1b[39m\x1b[39;1m1.0.0a5\x1b[39;22m\x1b[39m)\x1b[39m: \x1b[34mDownloading...\x1b[39m", "\x1b[34;1m-\x1b[39;22m \x1b[39mInstalling \x1b[39m\x1b[36mcleo\x1b[39m\x1b[39m (\x1b[39m\x1b[39;1m1.0.0a5\x1b[39;22m\x1b[39m)\x1b[39m: \x1b[34mInstalling...\x1b[39m", "\x1b[32;1m-\x1b[39;22m \x1b[39mInstalling \x1b[39m\x1b[36mcleo\x1b[39m\x1b[39m (\x1b[39m\x1b[32m1.0.0a5\x1b[39m\x1b[39m)\x1b[39m", # finished ] # fmt: on output = io_decorated.fetch_output() # hint: use print(repr(output)) if you need to debug this for line in expected: assert line in output assert return_code == 0 def test_execute_works_with_no_ansi_output( mocker: MockerFixture, config: Config, pool: RepositoryPool, io_not_decorated: BufferedIO, tmp_path: Path, env: MockEnv, ) -> None: config.merge({"cache-dir": str(tmp_path)}) executor = Executor(env, pool, config, io_not_decorated) return_code = executor.execute( [ Install(Package("cleo", "1.0.0a5")), ] ) expected = """ Package operations: 1 install, 0 updates, 0 removals - Installing cleo (1.0.0a5) """ expected_lines = set(expected.splitlines()) output_lines = set(io_not_decorated.fetch_output().splitlines()) assert output_lines == expected_lines assert return_code == 0 def test_execute_should_show_operation_as_cancelled_on_subprocess_keyboard_interrupt( config: Config, pool: RepositoryPool, mocker: MockerFixture, io: BufferedIO, env: MockEnv, ) -> None: executor = Executor(env, pool, config, io) executor.verbose() # A return code of -2 means KeyboardInterrupt in the pip subprocess mocker.patch.object(executor, "_install", return_value=-2) assert executor.execute([Install(Package("clikit", "0.2.3"))]) == 1 expected = """ Package operations: 1 install, 0 updates, 0 removals - Installing clikit (0.2.3) - Installing clikit (0.2.3): Cancelled """ assert io.fetch_output() == expected def test_execute_should_gracefully_handle_io_error( config: Config, pool: RepositoryPool, mocker: MockerFixture, io: BufferedIO, env: MockEnv, ) -> None: executor = Executor(env, pool, config, io) executor.verbose() original_write_line = executor._io.write_line def write_line(string: str, **kwargs: Any) -> None: # Simulate UnicodeEncodeError string = string.replace("-", "•") string.encode("ascii") original_write_line(string, **kwargs) mocker.patch.object(io, "write_line", side_effect=write_line) assert executor.execute([Install(Package("clikit", "0.2.3"))]) == 1 expected = r""" Package operations: 1 install, 0 updates, 0 removals \s*Unicode\w+Error """ assert re.match(expected, io.fetch_output()) def test_executor_should_delete_incomplete_downloads( config: Config, io: BufferedIO, tmp_path: Path, mocker: MockerFixture, pool: RepositoryPool, env: MockEnv, ) -> None: cached_archive = tmp_path / "tomlkit-0.5.3-py2.py3-none-any.whl" def download_fail(*_: Any) -> None: cached_archive.touch() # broken archive raise Exception("Download error") mocker.patch( "poetry.installation.executor.Executor._download_archive", side_effect=download_fail, ) mocker.patch( "poetry.utils.cache.ArtifactCache._get_cached_archive", return_value=None, ) mocker.patch( "poetry.utils.cache.ArtifactCache.get_cache_directory_for_link", return_value=tmp_path, ) config.merge({"cache-dir": str(tmp_path)}) executor = Executor(env, pool, config, io) with pytest.raises(Exception, match="Download error"): executor._download(Install(Package("tomlkit", "0.5.3"))) assert not cached_archive.exists() def verify_installed_distribution( venv: VirtualEnv, package: Package, url_reference: dict[str, Any] | None = None ) -> None: distributions = list(venv.site_packages.distributions(name=package.name)) assert len(distributions) == 1 distribution = distributions[0] metadata = distribution.metadata assert metadata assert metadata["Name"] == package.name assert metadata["Version"] == package.version.text direct_url_file = distribution._path.joinpath( # type: ignore[attr-defined] "direct_url.json" ) if url_reference is not None: record_file = distribution._path.joinpath( # type: ignore[attr-defined] "RECORD" ) with open(record_file, encoding="utf-8", newline="") as f: reader = csv.reader(f) rows = list(reader) assert all(len(row) == 3 for row in rows) record_entries = {row[0] for row in rows} direct_url_entry = direct_url_file.relative_to(record_file.parent.parent) assert direct_url_file.exists() assert str(direct_url_entry) in record_entries assert json.loads(direct_url_file.read_text(encoding="utf-8")) == url_reference else: assert not direct_url_file.exists() @pytest.mark.parametrize( "package", [ Package("demo", "0.1.0"), # PyPI Package( # private source "demo", "0.1.0", source_type="legacy", source_url="http://localhost:3141/root/pypi/+simple", source_reference="private", ), ], ) def test_executor_should_not_write_pep610_url_references_for_cached_package( package: Package, mocker: MockerFixture, fixture_dir: FixtureDirGetter, tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, ) -> None: link_cached = fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl" package.files = [ { "file": "demo-0.1.0-py2.py3-none-any.whl", "hash": ( "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a" ), } ] mocker.patch( "poetry.installation.executor.Executor._download", return_value=link_cached ) executor = Executor(tmp_venv, pool, config, io) executor.execute([Install(package)]) verify_installed_distribution(tmp_venv, package) assert link_cached.exists(), "cached file should not be deleted" def test_executor_should_write_pep610_url_references_for_wheel_files( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, fixture_dir: FixtureDirGetter, ) -> None: url = (fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl").resolve() package = Package("demo", "0.1.0", source_type="file", source_url=url.as_posix()) # Set package.files so the executor will attempt to hash the package package.files = [ { "file": "demo-0.1.0-py2.py3-none-any.whl", "hash": ( "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a" ), } ] executor = Executor(tmp_venv, pool, config, io) executor.execute([Install(package)]) expected_url_reference = { "archive_info": { "hashes": { "sha256": ( "70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a" ) }, }, "url": url.as_uri(), } verify_installed_distribution(tmp_venv, package, expected_url_reference) assert url.exists(), "source file should not be deleted" def test_executor_should_write_pep610_url_references_for_non_wheel_files( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, fixture_dir: FixtureDirGetter, ) -> None: url = (fixture_dir("distributions") / "demo-0.1.0.tar.gz").resolve() package = Package("demo", "0.1.0", source_type="file", source_url=url.as_posix()) # Set package.files so the executor will attempt to hash the package package.files = [ { "file": "demo-0.1.0.tar.gz", "hash": ( "sha256:9fa123ad707a5c6c944743bf3e11a0e80d86cb518d3cf25320866ca3ef43e2ad" ), } ] executor = Executor(tmp_venv, pool, config, io) executor.execute([Install(package)]) expected_url_reference = { "archive_info": { "hashes": { "sha256": ( "9fa123ad707a5c6c944743bf3e11a0e80d86cb518d3cf25320866ca3ef43e2ad" ) }, }, "url": url.as_uri(), } verify_installed_distribution(tmp_venv, package, expected_url_reference) assert url.exists(), "source file should not be deleted" def test_executor_should_write_pep610_url_references_for_directories( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, fixture_dir: FixtureDirGetter, mocker: MockerFixture, ) -> None: url = (fixture_dir("git") / "github.com" / "demo" / "demo").resolve() package = Package( "demo", "0.1.2", source_type="directory", source_url=url.as_posix() ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) prepare_spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) verify_installed_distribution( tmp_venv, package, {"dir_info": {}, "url": url.as_uri()} ) assert not prepare_spy.spy_return.exists(), "archive not cleaned up" def test_executor_should_write_pep610_url_references_for_editable_directories( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, fixture_dir: FixtureDirGetter, mocker: MockerFixture, ) -> None: url = (fixture_dir("git") / "github.com" / "demo" / "demo").resolve() package = Package( "demo", "0.1.2", source_type="directory", source_url=url.as_posix(), develop=True, ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) prepare_spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) verify_installed_distribution( tmp_venv, package, {"dir_info": {"editable": True}, "url": url.as_uri()} ) assert not prepare_spy.spy_return.exists(), "archive not cleaned up" @pytest.mark.parametrize("is_artifact_cached", [False, True]) def test_executor_should_write_pep610_url_references_for_wheel_urls( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, mocker: MockerFixture, fixture_dir: FixtureDirGetter, is_artifact_cached: bool, ) -> None: if is_artifact_cached: link_cached = fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl" mocker.patch( "poetry.utils.cache.ArtifactCache.get_cached_archive_for_link", return_value=link_cached, ) download_spy = mocker.spy(Executor, "_download_archive") package = Package( "demo", "0.1.0", source_type="url", source_url="https://files.pythonhosted.org/demo-0.1.0-py2.py3-none-any.whl", ) # Set package.files so the executor will attempt to hash the package package.files = [ { "file": "demo-0.1.0-py2.py3-none-any.whl", "hash": ( "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a" ), } ] executor = Executor(tmp_venv, pool, config, io) operation = Install(package) executor.execute([operation]) expected_url_reference = { "archive_info": { "hashes": { "sha256": ( "70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a" ) }, }, "url": package.source_url, } verify_installed_distribution(tmp_venv, package, expected_url_reference) if is_artifact_cached: download_spy.assert_not_called() else: assert package.source_url is not None download_spy.assert_called_once_with( mocker.ANY, operation, package.source_url, dest=mocker.ANY, ) dest = download_spy.call_args.args[3] assert dest.exists(), "cached file should not be deleted" @pytest.mark.parametrize( ( "is_sdist_cached", "is_wheel_cached", "expect_artifact_building", "expect_artifact_download", ), [ (True, False, True, False), (True, True, False, False), (False, False, True, True), (False, True, False, True), ], ) def test_executor_should_write_pep610_url_references_for_non_wheel_urls( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, mocker: MockerFixture, fixture_dir: FixtureDirGetter, is_sdist_cached: bool, is_wheel_cached: bool, expect_artifact_building: bool, expect_artifact_download: bool, ) -> None: built_wheel = fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl" mock_prepare = mocker.patch( "poetry.installation.chef.Chef._prepare", return_value=built_wheel, ) download_spy = mocker.spy(Executor, "_download_archive") if is_sdist_cached or is_wheel_cached: cached_sdist = fixture_dir("distributions") / "demo-0.1.0.tar.gz" cached_wheel = fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl" def mock_get_cached_archive_func( _cache_dir: Path, *, strict: bool, **__: Any ) -> Path | None: if is_wheel_cached and not strict: return cached_wheel if is_sdist_cached: return cached_sdist return None mocker.patch( "poetry.utils.cache.ArtifactCache._get_cached_archive", side_effect=mock_get_cached_archive_func, ) package = Package( "demo", "0.1.0", source_type="url", source_url="https://files.pythonhosted.org/demo-0.1.0.tar.gz", ) # Set package.files so the executor will attempt to hash the package package.files = [ { "file": "demo-0.1.0.tar.gz", "hash": ( "sha256:9fa123ad707a5c6c944743bf3e11a0e80d86cb518d3cf25320866ca3ef43e2ad" ), } ] executor = Executor(tmp_venv, pool, config, io) operation = Install(package) executor.execute([operation]) expected_url_reference = { "archive_info": { "hashes": { "sha256": ( "9fa123ad707a5c6c944743bf3e11a0e80d86cb518d3cf25320866ca3ef43e2ad" ) }, }, "url": package.source_url, } verify_installed_distribution(tmp_venv, package, expected_url_reference) if expect_artifact_building: mock_prepare.assert_called_once() else: mock_prepare.assert_not_called() if expect_artifact_download: assert package.source_url is not None download_spy.assert_called_once_with( mocker.ANY, operation, package.source_url, dest=mocker.ANY ) dest = download_spy.call_args.args[3] assert dest.exists(), "cached file should not be deleted" else: download_spy.assert_not_called() @pytest.mark.parametrize( "source_url,written_source_url", [ ("https://github.com/demo/demo.git", "https://github.com/demo/demo.git"), ("git@github.com:demo/demo.git", "ssh://git@github.com/demo/demo.git"), ], ) @pytest.mark.parametrize("is_artifact_cached", [False, True]) def test_executor_should_write_pep610_url_references_for_git( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, mocker: MockerFixture, fixture_dir: FixtureDirGetter, source_url: str, written_source_url: str, is_artifact_cached: bool, ) -> None: if is_artifact_cached: link_cached = fixture_dir("distributions") / "demo-0.1.2-py2.py3-none-any.whl" mocker.patch( "poetry.utils.cache.ArtifactCache.get_cached_archive_for_git", return_value=link_cached, ) clone_spy = mocker.spy(Git, "clone") source_resolved_reference = "123456" source_url = source_url package = Package( "demo", "0.1.2", source_type="git", source_reference="master", source_resolved_reference=source_resolved_reference, source_url=source_url, ) assert package.source_url == written_source_url chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) prepare_spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) verify_installed_distribution( tmp_venv, package, { "vcs_info": { "vcs": "git", "requested_revision": "master", "commit_id": "123456", }, "url": package.source_url, }, ) if is_artifact_cached: clone_spy.assert_not_called() prepare_spy.assert_not_called() else: clone_spy.assert_called_once_with( url=package.source_url, source_root=mocker.ANY, revision=source_resolved_reference, ) prepare_spy.assert_called_once() assert prepare_spy.spy_return.exists(), "cached file should not be deleted" assert (prepare_spy.spy_return.parent / ".created_from_git_dependency").exists() def test_executor_should_write_pep610_url_references_for_editable_git( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, mocker: MockerFixture, fixture_dir: FixtureDirGetter, ) -> None: source_resolved_reference = "123456" source_url = "https://github.com/demo/demo.git" package = Package( "demo", "0.1.2", source_type="git", source_reference="master", source_resolved_reference=source_resolved_reference, source_url=source_url, develop=True, ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) prepare_spy = mocker.spy(chef, "prepare") cache_spy = mocker.spy(artifact_cache, "get_cached_archive_for_git") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) assert package.source_url is not None verify_installed_distribution( tmp_venv, package, { "dir_info": {"editable": True}, "url": Path(package.source_url).as_uri(), }, ) cache_spy.assert_not_called() prepare_spy.assert_called_once() assert not prepare_spy.spy_return.exists(), "editable git should not be cached" assert not (prepare_spy.spy_return.parent / ".created_from_git_dependency").exists() def test_executor_should_append_subdirectory_for_git( mocker: MockerFixture, tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, ) -> None: package = Package( "demo", "0.1.2", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/demo/subdirectories.git", source_subdirectory="two", ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) archive_arg = spy.call_args[0][0] assert archive_arg == tmp_venv.path / "src/subdirectories/two" def test_executor_should_install_multiple_packages_from_same_git_repository( mocker: MockerFixture, tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, ) -> None: package_a = Package( "package_a", "0.1.2", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/demo/subdirectories.git", source_subdirectory="package_a", ) package_b = Package( "package_b", "0.1.2", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/demo/subdirectories.git", source_subdirectory="package_b", ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package_a), Install(package_b)]) archive_arg = spy.call_args_list[0][0][0] assert archive_arg == tmp_venv.path / "src/subdirectories/package_a" archive_arg = spy.call_args_list[1][0][0] assert archive_arg == tmp_venv.path / "src/subdirectories/package_b" def test_executor_should_install_multiple_packages_from_forked_git_repository( mocker: MockerFixture, tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, ) -> None: package_a = Package( "one", "1.0.0", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/demo/subdirectories.git", source_subdirectory="one", ) package_b = Package( "two", "2.0.0", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/forked_demo/subdirectories.git", source_subdirectory="two", ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) prepare_spy = mocker.spy(chef, "prepare") executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package_a), Install(package_b)]) # Verify that the repo for package_a is not re-used for package_b. # both repos must be cloned serially into separate directories. # If so, executor.prepare() will be called twice. assert prepare_spy.call_count == 2 def test_executor_should_write_pep610_url_references_for_git_with_subdirectories( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, wheel: Path, ) -> None: package = Package( "demo", "0.1.2", source_type="git", source_reference="master", source_resolved_reference="123456", source_url="https://github.com/demo/subdirectories.git", source_subdirectory="two", ) chef = Chef(artifact_cache, tmp_venv, Factory.create_pool(config)) chef.set_directory_wheel(wheel) executor = Executor(tmp_venv, pool, config, io) executor._chef = chef executor.execute([Install(package)]) verify_installed_distribution( tmp_venv, package, { "vcs_info": { "vcs": "git", "requested_revision": "master", "commit_id": "123456", }, "url": package.source_url, "subdirectory": package.source_subdirectory, }, ) @pytest.mark.parametrize( ("max_workers", "cpu_count", "side_effect", "expected_workers"), [ (None, 3, None, 7), (3, 4, None, 3), (8, 3, None, 7), (None, 8, NotImplementedError(), 5), (2, 8, NotImplementedError(), 2), (8, 8, NotImplementedError(), 5), ], ) def test_executor_should_be_initialized_with_correct_workers( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, mocker: MockerFixture, max_workers: int | None, cpu_count: int | None, side_effect: Exception | None, expected_workers: int, ) -> None: config.merge({"installer": {"max-workers": max_workers}}) mocker.patch("os.cpu_count", return_value=cpu_count, side_effect=side_effect) executor = Executor(tmp_venv, pool, config, io) assert executor._max_workers == expected_workers @pytest.mark.parametrize("failing_method", ["build", "get_requires_for_build"]) @pytest.mark.parametrize( "exception", [ CalledProcessError(1, ["pip"], output=b"original error"), Exception("original error"), ], ) @pytest.mark.parametrize("editable", [False, True]) @pytest.mark.parametrize("source_type", ["directory", "git", "git subdirectory"]) def test_build_backend_errors_are_reported_correctly_if_caused_by_subprocess( failing_method: str, exception: Exception, editable: bool, source_type: str, mocker: MockerFixture, config: Config, pool: RepositoryPool, io: BufferedIO, env: MockEnv, fixture_dir: FixtureDirGetter, ) -> None: error = BuildBackendException(exception, description="hide the original error") mocker.patch.object(ProjectBuilder, failing_method, side_effect=error) io.set_verbosity(Verbosity.NORMAL) executor = Executor(env, pool, config, io) package_name = "simple-project" package_version = "1.2.3" source_reference: str | None = None source_sub_directory: str | None = None if source_type == "directory": source_url = fixture_dir("simple_project").resolve().as_posix() source_resolved_reference = None pip_url = path_to_url(source_url) pip_editable_requirement = source_url elif source_type == "git": source_url = "https://github.com/demo/demo.git" source_reference = "v2.0" source_resolved_reference = "12345678" pip_url = f"git+{source_url}@{source_reference}" pip_editable_requirement = f"{pip_url}#egg={package_name}" elif source_type == "git subdirectory": source_type = "git" source_sub_directory = "one" source_url = "https://github.com/demo/subdirectories.git" source_reference = "v2.0" source_resolved_reference = "12345678" pip_base_url = f"git+{source_url}@{source_reference}" pip_url = f"{pip_base_url}#subdirectory={source_sub_directory}" pip_editable_requirement = ( f"{pip_base_url}#egg={package_name}&subdirectory={source_sub_directory}" ) else: raise ValueError(f"Unknown source type: {source_type}") package = Package( package_name, package_version, source_type=source_type, source_url=source_url, source_reference=source_reference, source_resolved_reference=source_resolved_reference, source_subdirectory=source_sub_directory, develop=editable, ) # must not be included in the error message package.python_versions = ">=3.7" return_code = executor.execute([Install(package)]) assert return_code == 1 assert package.source_url is not None if editable: pip_command = "pip wheel --no-cache-dir --use-pep517 --editable" requirement = pip_editable_requirement if source_type == "directory": assert Path(requirement).exists() else: pip_command = "pip wheel --no-cache-dir --use-pep517" requirement = f"{package_name} @ {pip_url}" version_details = package.source_resolved_reference or package.source_url expected_source_string = f"{package_name} ({package_version} {version_details})" expected_pip_command = f'{pip_command} "{requirement}"' expected_output = f""" Package operations: 1 install, 0 updates, 0 removals - Installing {expected_source_string} PEP517 build of a dependency failed hide the original error """ if isinstance(exception, CalledProcessError): expected_output += ( "\n | Command '['pip']' returned non-zero exit status 1." "\n | " "\n | original error" "\n" ) expected_output += f""" Note: This error originates from the build backend, and is likely not a problem \ with poetry but one of the following issues with {expected_source_string} - not supporting PEP 517 builds - not specifying PEP 517 build requirements correctly - the build requirements are incompatible with your operating system or Python version - the build requirements are missing system dependencies (eg: compilers, libraries, headers). You can verify this by running {expected_pip_command}. """ assert io.fetch_output() == expected_output @pytest.mark.parametrize("encoding", ["utf-8", "latin-1"]) @pytest.mark.parametrize("stderr", [None, "Errör on stderr"]) def test_build_backend_errors_are_reported_correctly_if_caused_by_subprocess_encoding( encoding: str, stderr: str | None, mocker: MockerFixture, config: Config, pool: RepositoryPool, io: BufferedIO, env: MockEnv, fixture_dir: FixtureDirGetter, ) -> None: """Test that the output of the subprocess is decoded correctly.""" stdout = "Errör on stdout" error = BuildBackendException( CalledProcessError( 1, ["pip"], output=stdout.encode(encoding), stderr=stderr.encode(encoding) if stderr else None, ) ) mocker.patch.object(ProjectBuilder, "get_requires_for_build", side_effect=error) io.set_verbosity(Verbosity.NORMAL) executor = Executor(env, pool, config, io) directory_package = Package( "simple-project", "1.2.3", source_type="directory", source_url=fixture_dir("simple_project").resolve().as_posix(), ) return_code = executor.execute([Install(directory_package)]) assert return_code == 1 assert (stderr or stdout) in io.fetch_output() def test_build_system_requires_not_available( config: Config, pool: RepositoryPool, io: BufferedIO, env: MockEnv, fixture_dir: FixtureDirGetter, ) -> None: io.set_verbosity(Verbosity.NORMAL) executor = Executor(env, pool, config, io) package_name = "simple-project" package_version = "1.2.3" directory_package = Package( package_name, package_version, source_type="directory", source_url=fixture_dir("build_system_requires_not_available") .resolve() .as_posix(), ) return_code = executor.execute([Install(directory_package)]) assert return_code == 1 package_url = directory_package.source_url expected_start = f"""\ Package operations: 1 install, 0 updates, 0 removals - Installing {package_name} ({package_version} {package_url}) SolveFailureError Because -root- depends on poetry-core (0.999) which doesn't match any versions,\ version solving failed. """ expected_end = "Cannot resolve build-system.requires for simple-project." output = io.fetch_output().strip() assert output.startswith(expected_start) assert output.endswith(expected_end) def test_build_system_requires_install_failure( mocker: MockerFixture, config: Config, pool: RepositoryPool, io: BufferedIO, env: MockEnv, fixture_dir: FixtureDirGetter, ) -> None: mocker.patch("poetry.installation.installer.Installer.run", return_value=1) mocker.patch("cleo.io.buffered_io.BufferedIO.fetch_output", return_value="output") mocker.patch("cleo.io.buffered_io.BufferedIO.fetch_error", return_value="error") io.set_verbosity(Verbosity.NORMAL) executor = Executor(env, pool, config, io) package_name = "simple-project" package_version = "1.2.3" directory_package = Package( package_name, package_version, source_type="directory", source_url=fixture_dir("simple_project").resolve().as_posix(), ) return_code = executor.execute([Install(directory_package)]) assert return_code == 1 package_url = directory_package.source_url expected_start = f"""\ Package operations: 1 install, 0 updates, 0 removals - Installing {package_name} ({package_version} {package_url}) IsolatedBuildInstallError Failed to install poetry-core>=1.1.0a7. \ Output: output \ Error: error """ expected_end = "Cannot install build-system.requires for simple-project." mocker.stopall() # to get real output output = io.fetch_output().strip() assert output.startswith(expected_start) assert output.endswith(expected_end) def test_other_error( config: Config, pool: RepositoryPool, io: BufferedIO, env: MockEnv, fixture_dir: FixtureDirGetter, ) -> None: io.set_verbosity(Verbosity.NORMAL) executor = Executor(env, pool, config, io) package_name = "simple-project" package_version = "1.2.3" directory_package = Package( package_name, package_version, source_type="directory", source_url=fixture_dir("non-existing").resolve().as_posix(), ) return_code = executor.execute([Install(directory_package)]) assert return_code == 1 package_url = directory_package.source_url expected_start = f"""\ Package operations: 1 install, 0 updates, 0 removals - Installing {package_name} ({package_version} {package_url}) FileNotFoundError """ expected_end = "Cannot install simple-project." output = io.fetch_output().strip() assert output.startswith(expected_start) assert output.endswith(expected_end) @pytest.mark.parametrize( "package_files,expected_url_reference", [ ( [ { "file": "demo-0.1.0.tar.gz", "hash": "sha512:766ecf369b6bdf801f6f7bbfe23923cc9793d633a55619472cd3d5763f9154711fbf57c8b6ca74e4a82fa9bd8380af831e7b8668e68e362669fc60b1d81d79ad", }, { "file": "demo-0.1.0.tar.gz", "hash": "md5:d1912c917363a64e127318655f7d1fe7", }, { "file": "demo-0.1.0.whl", "hash": "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a", }, ], { "archive_info": { "hashes": { "sha512": "766ecf369b6bdf801f6f7bbfe23923cc9793d633a55619472cd3d5763f9154711fbf57c8b6ca74e4a82fa9bd8380af831e7b8668e68e362669fc60b1d81d79ad" }, }, }, ), ( [ { "file": "demo-0.1.0.tar.gz", "hash": "md5:d1912c917363a64e127318655f7d1fe7", } ], { "archive_info": { "hashes": {"md5": "d1912c917363a64e127318655f7d1fe7"}, }, }, ), ( [ { "file": "demo-0.1.0.tar.gz", "hash": "sha3_512:196f4af9099185054ed72ca1d4c57707da5d724df0af7c3dfcc0fd018b0e0533908e790a291600c7d196fe4411b4f5f6db45213fe6e5cd5512bf18b2e9eff728", }, { "file": "demo-0.1.0.tar.gz", "hash": "sha512:766ecf369b6bdf801f6f7bbfe23923cc9793d633a55619472cd3d5763f9154711fbf57c8b6ca74e4a82fa9bd8380af831e7b8668e68e362669fc60b1d81d79ad", }, { "file": "demo-0.1.0.tar.gz", "hash": "md5:d1912c917363a64e127318655f7d1fe7", }, { "file": "demo-0.1.0.whl", "hash": "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a", }, ], { "archive_info": { "hashes": { "sha3_512": "196f4af9099185054ed72ca1d4c57707da5d724df0af7c3dfcc0fd018b0e0533908e790a291600c7d196fe4411b4f5f6db45213fe6e5cd5512bf18b2e9eff728" }, }, }, ), ], ) def test_executor_known_hashes( package_files: list[dict[str, str]], expected_url_reference: dict[str, Any], tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, fixture_dir: FixtureDirGetter, ) -> None: package_source_url: Path = ( fixture_dir("distributions") / "demo-0.1.0.tar.gz" ).resolve() package = Package( "demo", "0.1.0", source_type="file", source_url=package_source_url.as_posix() ) package.files = package_files executor = Executor(tmp_venv, pool, config, io) executor.execute([Install(package)]) expected_url_reference["url"] = package_source_url.as_uri() verify_installed_distribution(tmp_venv, package, expected_url_reference) def test_executor_no_supported_hash_types( tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, io: BufferedIO, fixture_dir: FixtureDirGetter, ) -> None: url = (fixture_dir("distributions") / "demo-0.1.0.tar.gz").resolve() package = Package("demo", "0.1.0", source_type="file", source_url=url.as_posix()) # Set package.files so the executor will attempt to hash the package package.files = [ { "file": "demo-0.1.0.tar.gz", "hash": "hash_blah:1234567890abcdefghijklmnopqrstyzwxyz", }, { "file": "demo-0.1.0.whl", "hash": "sha256:70e704135718fffbcbf61ed1fc45933cfd86951a744b681000eaaa75da31f17a", }, ] executor = Executor(tmp_venv, pool, config, io) return_code = executor.execute([Install(package)]) distributions = list(tmp_venv.site_packages.distributions(name=package.name)) assert len(distributions) == 0 output = io.fetch_output() error = io.fetch_error() assert return_code == 1, f"\noutput: {output}\nerror: {error}\n" assert "No usable hash type(s) for demo" in output assert "hash_blah:1234567890abcdefghijklmnopqrstyzwxyz" in output
Chef
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 26802, "end": 27202 }
class ____(PrefectBaseModel, OperatorMixin): """Filter work queues. Only work queues matching all criteria will be returned""" id: Optional[WorkQueueFilterId] = Field( default=None, description="Filter criteria for `WorkQueue.id`" ) name: Optional[WorkQueueFilterName] = Field( default=None, description="Filter criteria for `WorkQueue.name`" )
WorkQueueFilter
python
huggingface__transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
{ "start": 28538, "end": 35685 }
class ____(InstructBlipVideoPreTrainedModel): """ Querying Transformer (Q-Former), used in InstructBlipVideo. Slightly modified from BLIP-2 as it also takes the instruction as input. """ _supports_attention_backend = False # adds position on attn weights before last matmul _supports_flash_attn = False _supports_sdpa = False _supports_flex_attn = False _can_record_outputs = { "hidden_states": InstructBlipVideoQFormerLayer, "attentions": [ OutputRecorder(InstructBlipVideoQFormerMultiHeadAttention, index=1, layer_name=".attention"), ], "cross_attentions": [ OutputRecorder(InstructBlipVideoQFormerMultiHeadAttention, index=1, layer_name=".crossattention"), ], } def __init__(self, config: InstructBlipVideoQFormerConfig): super().__init__(config) self.config = config self.embeddings = InstructBlipVideoQFormerEmbeddings(config) self.encoder = InstructBlipVideoQFormerEncoder(config) self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def get_extended_attention_mask( self, attention_mask: torch.Tensor, input_shape: tuple[int], device: torch.device, has_query: bool = False, ) -> torch.Tensor: """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`tuple[int]`): The shape of the input to the model. device: (`torch.device`): The device of the input to the model. Returns: `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`. """ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: # Provided a padding mask of dimensions [batch_size, seq_length] # - the model is an encoder, so make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError( f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})", ) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask @check_model_inputs() @auto_docstring def forward( self, input_ids: torch.LongTensor, attention_mask: Optional[torch.FloatTensor] = None, position_ids: Optional[torch.LongTensor] = None, query_embeds: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.FloatTensor], BaseModelOutputWithPoolingAndCrossAttentions]: r""" query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Hidden states to be used in the attention computation. If cross-attention, will be used for the query (i.e., key and value will use the encoder_hidden_states). """ if input_ids is None and query_embeds is None: raise ValueError("You have to specify query_embeds when input_ids is None") query_length = query_embeds.shape[1] if query_embeds is not None else 0 embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, query_embeds=query_embeds, ) input_shape = embedding_output.size()[:-1] batch_size, seq_length = input_shape device = embedding_output.device if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length)), device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_hidden_states is not None: if isinstance(encoder_hidden_states, list): encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() else: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if isinstance(encoder_attention_mask, list): encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] elif encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None encoder_outputs: BaseModelOutput = self.encoder( embedding_output, attention_mask=extended_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, query_length=query_length, **kwargs, ) sequence_output = encoder_outputs.last_hidden_state pooled_output = sequence_output[:, 0, :] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, ) @dataclass @auto_docstring( custom_intro=""" Class defining the outputs of [`InstructBlipVideoForConditionalGeneration`]. """ )
InstructBlipVideoQFormerModel
python
readthedocs__readthedocs.org
readthedocs/proxito/exceptions.py
{ "start": 3548, "end": 4177 }
class ____(ContextualizedHttp404): """Raised if a page inside an existing project was not found.""" template_name = "errors/proxito/404/no_project.html" not_found_subject = pgettext_lazy(_not_found_subject_translation_context, "documentation page") def __init__(self, project, **kwargs): """ Raised if a page inside an existing project was not found. :param project: The project in which the file could not be found :param kwargs: Context dictionary of the rendered template """ kwargs["project"] = project super().__init__(**kwargs)
ProjectFilenameHttp404
python
sympy__sympy
sympy/matrices/expressions/special.py
{ "start": 2725, "end": 4128 }
class ____(MatrixExpr): """The Matrix Identity I - multiplicative identity Examples ======== >>> from sympy import Identity, MatrixSymbol >>> A = MatrixSymbol('A', 3, 5) >>> I = Identity(3) >>> I*A A >>> I.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) """ is_Identity = True def __new__(cls, n): n = _sympify(n) cls._check_dim(n) return super().__new__(cls, n) @property def rows(self): return self.args[0] @property def cols(self): return self.args[0] @property def shape(self): return (self.args[0], self.args[0]) @property def is_square(self): return True def _eval_transpose(self): return self def _eval_trace(self): return self.rows def _eval_inverse(self): return self def _eval_as_real_imag(self): return (self, ZeroMatrix(*self.shape)) def _eval_conjugate(self): return self def _eval_adjoint(self): return self def _entry(self, i, j, **kwargs): eq = Eq(i, j) if eq is S.true: return S.One elif eq is S.false: return S.Zero return KroneckerDelta(i, j, (0, self.cols-1)) def _eval_determinant(self): return S.One def _eval_power(self, exp): return self
Identity
python
run-llama__llama_index
llama-index-core/llama_index/core/langchain_helpers/memory_wrapper.py
{ "start": 971, "end": 3602 }
class ____(Memory): """ Langchain memory wrapper (for LlamaIndex). Args: human_prefix (str): Prefix for human input. Defaults to "Human". ai_prefix (str): Prefix for AI output. Defaults to "AI". memory_key (str): Key for memory. Defaults to "history". index (BaseIndex): LlamaIndex instance. query_kwargs (Dict[str, Any]): Keyword arguments for LlamaIndex query. input_key (Optional[str]): Input key. Defaults to None. output_key (Optional[str]): Output key. Defaults to None. """ human_prefix: str = "Human" ai_prefix: str = "AI" memory_key: str = "history" index: BaseIndex query_kwargs: Dict = Field(default_factory=dict) output_key: Optional[str] = None input_key: Optional[str] = None @property def memory_variables(self) -> List[str]: """Return memory variables.""" return [self.memory_key] def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str: if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key return prompt_input_key def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Return key-value pairs given the text input to the chain.""" prompt_input_key = self._get_prompt_input_key(inputs) query_str = inputs[prompt_input_key] # TODO: wrap in prompt # TODO: add option to return the raw text # NOTE: currently it's a hack query_engine = self.index.as_query_engine(**self.query_kwargs) response = query_engine.query(query_str) return {self.memory_key: str(response)} def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save the context of this model run to memory.""" prompt_input_key = self._get_prompt_input_key(inputs) if self.output_key is None: if len(outputs) != 1: raise ValueError(f"One output key expected, got {outputs.keys()}") output_key = next(iter(outputs.keys())) else: output_key = self.output_key human = f"{self.human_prefix}: " + inputs[prompt_input_key] ai = f"{self.ai_prefix}: " + outputs[output_key] doc_text = f"{human}\n{ai}" doc = Document(text=doc_text) self.index.insert(doc) def clear(self) -> None: """Clear memory contents.""" def __repr__(self) -> str: """Return representation.""" return "GPTIndexMemory()"
GPTIndexMemory
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_basic.py
{ "start": 23178, "end": 24673 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): global t1 t1 = Table( "t1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("type", Boolean, nullable=False), ) def test_false_on_sub(self): class Foo: pass class Bar(Foo): pass self.mapper_registry.map_imperatively( Foo, t1, polymorphic_on=t1.c.type, polymorphic_identity=True ) self.mapper_registry.map_imperatively( Bar, inherits=Foo, polymorphic_identity=False ) sess = fixture_session() b1 = Bar() sess.add(b1) sess.flush() assert b1.type is False sess.expunge_all() assert isinstance(sess.query(Foo).one(), Bar) def test_false_on_base(self): class Ding: pass class Bat(Ding): pass self.mapper_registry.map_imperatively( Ding, t1, polymorphic_on=t1.c.type, polymorphic_identity=False ) self.mapper_registry.map_imperatively( Bat, inherits=Ding, polymorphic_identity=True ) sess = fixture_session() d1 = Ding() sess.add(d1) sess.flush() assert d1.type is False sess.expunge_all() assert sess.query(Ding).one() is not None
FalseDiscriminatorTest
python
huggingface__transformers
src/transformers/models/phi3/modeling_phi3.py
{ "start": 16171, "end": 19401 }
class ____(Phi3PreTrainedModel): def __init__(self, config: Phi3Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Phi3RotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask causal_mask = mask_function( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) for decoder_layer in self.layers[: self.config.num_hidden_layers]: hidden_states = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, ) @auto_docstring
Phi3Model
python
numpy__numpy
benchmarks/benchmarks/bench_linalg.py
{ "start": 3479, "end": 7061 }
class ____(Benchmark): param_names = ['dtype'] params = [[np.float32, np.float64]] def setup(self, dtype): self.one_dim_small = np.arange(600, dtype=dtype) self.one_dim = np.arange(3000, dtype=dtype) self.one_dim_big = np.arange(480000, dtype=dtype) self.two_dim_small = np.arange(1200, dtype=dtype).reshape(30, 40) self.two_dim = np.arange(240000, dtype=dtype).reshape(400, 600) self.three_dim_small = np.arange(10000, dtype=dtype).reshape(10, 100, 10) self.three_dim = np.arange(24000, dtype=dtype).reshape(20, 30, 40) # non_contiguous arrays self.non_contiguous_dim1_small = np.arange(1, 80, 2, dtype=dtype) self.non_contiguous_dim1 = np.arange(1, 4000, 2, dtype=dtype) self.non_contiguous_dim2 = np.arange(1, 2400, 2, dtype=dtype).reshape(30, 40) non_contiguous_dim3 = np.arange(1, 48000, 2, dtype=dtype) self.non_contiguous_dim3 = non_contiguous_dim3.reshape(20, 30, 40) # outer(a,b): trigger sum_of_products_contig_stride0_outcontig_two def time_einsum_outer(self, dtype): np.einsum("i,j", self.one_dim, self.one_dim, optimize=True) # multiply(a, b):trigger sum_of_products_contig_two def time_einsum_multiply(self, dtype): np.einsum("..., ...", self.two_dim_small, self.three_dim, optimize=True) # sum and multiply:trigger sum_of_products_contig_stride0_outstride0_two def time_einsum_sum_mul(self, dtype): np.einsum(",i...->", 300, self.three_dim_small, optimize=True) # sum and multiply:trigger sum_of_products_stride0_contig_outstride0_two def time_einsum_sum_mul2(self, dtype): np.einsum("i...,->", self.three_dim_small, 300, optimize=True) # scalar mul: trigger sum_of_products_stride0_contig_outcontig_two def time_einsum_mul(self, dtype): np.einsum("i,->i", self.one_dim_big, 300, optimize=True) # trigger contig_contig_outstride0_two def time_einsum_contig_contig(self, dtype): np.einsum("ji,i->", self.two_dim, self.one_dim_small, optimize=True) # trigger sum_of_products_contig_outstride0_one def time_einsum_contig_outstride0(self, dtype): np.einsum("i->", self.one_dim_big, optimize=True) # outer(a,b): non_contiguous arrays def time_einsum_noncon_outer(self, dtype): np.einsum("i,j", self.non_contiguous_dim1, self.non_contiguous_dim1, optimize=True) # multiply(a, b):non_contiguous arrays def time_einsum_noncon_multiply(self, dtype): np.einsum("..., ...", self.non_contiguous_dim2, self.non_contiguous_dim3, optimize=True) # sum and multiply:non_contiguous arrays def time_einsum_noncon_sum_mul(self, dtype): np.einsum(",i...->", 300, self.non_contiguous_dim3, optimize=True) # sum and multiply:non_contiguous arrays def time_einsum_noncon_sum_mul2(self, dtype): np.einsum("i...,->", self.non_contiguous_dim3, 300, optimize=True) # scalar mul: non_contiguous arrays def time_einsum_noncon_mul(self, dtype): np.einsum("i,->i", self.non_contiguous_dim1, 300, optimize=True) # contig_contig_outstride0_two: non_contiguous arrays def time_einsum_noncon_contig_contig(self, dtype): np.einsum("ji,i->", self.non_contiguous_dim2, self.non_contiguous_dim1_small, optimize=True) # sum_of_products_contig_outstride0_one: non_contiguous arrays def time_einsum_noncon_contig_outstride0(self, dtype): np.einsum("i->", self.non_contiguous_dim1, optimize=True)
Einsum
python
django__django
django/contrib/gis/db/backends/base/adapter.py
{ "start": 0, "end": 592 }
class ____: """ An adaptor for Geometries sent to the MySQL and Oracle database backends. """ def __init__(self, geom): self.wkt = geom.wkt self.srid = geom.srid def __eq__(self, other): return ( isinstance(other, WKTAdapter) and self.wkt == other.wkt and self.srid == other.srid ) def __hash__(self): return hash((self.wkt, self.srid)) def __str__(self): return self.wkt @classmethod def _fix_polygon(cls, poly): # Hook for Oracle. return poly
WKTAdapter
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 1744, "end": 3233 }
class ____(TestCase): def test_single_type(self) -> None: class Schema(Config): option = c.Type(str) conf = self.get_config(Schema, {'option': "Testing"}) assert_type(conf.option, str) self.assertEqual(conf.option, "Testing") def test_multiple_types(self) -> None: class Schema(Config): option = c.Type((list, tuple)) conf = self.get_config(Schema, {'option': [1, 2, 3]}) self.assertEqual(conf.option, [1, 2, 3]) conf = self.get_config(Schema, {'option': (1, 2, 3)}) self.assertEqual(conf.option, (1, 2, 3)) with self.expect_error( option="Expected type: (<class 'list'>, <class 'tuple'>) but received: <class 'dict'>" ): self.get_config(Schema, {'option': {'a': 1}}) def test_length(self) -> None: class Schema(Config): option = c.Type(str, length=7) conf = self.get_config(Schema, {'option': "Testing"}) assert_type(conf.option, str) self.assertEqual(conf.option, "Testing") with self.expect_error( option="Expected type: <class 'str'> with length 7 but received: 'Testing Long' with length 12" ): self.get_config(Schema, {'option': "Testing Long"}) def test_optional_with_default(self) -> None: with self.assertRaisesRegex(ValueError, "doesn't need to be wrapped into Optional"): c.Optional(c.Type(int, default=5))
TypeTest
python
conda__conda
conda/plugins/types.py
{ "start": 12856, "end": 13564 }
class ____(CondaPlugin): """ Return type to use when defining a conda reporter backend plugin hook. For details on how this is used, see: :meth:`~conda.plugins.hookspec.CondaSpecs.conda_reporter_backends`. :param name: name of the reporter backend (e.g., ``email_reporter``) This is how the reporter backend with be references in configuration files. :param description: short description of what the reporter handler does :param renderer: implementation of ``ReporterRendererBase`` that will be used as the reporter renderer """ name: str description: str renderer: type[ReporterRendererBase] @dataclass
CondaReporterBackend
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_step_delegating_executor.py
{ "start": 1090, "end": 13960 }
class ____(StepHandler): # This step handler waits for all processes to exit, because windows tests flake when processes # are left alive when the test ends. Non-test step handlers should not keep their own state in memory. processes = [] launch_step_count = 0 saw_baz_op = False check_step_health_count = 0 terminate_step_count = 0 verify_step_count = 0 @property def name(self): return "TestStepHandler" def launch_step(self, step_handler_context): if step_handler_context.execute_step_args.should_verify_step: TestStepHandler.verify_step_count += 1 if step_handler_context.execute_step_args.step_keys_to_execute[0] == "baz_op": # pyright: ignore[reportOptionalSubscript] TestStepHandler.saw_baz_op = True assert step_handler_context.step_tags["baz_op"] == {"foo": "bar"} TestStepHandler.launch_step_count += 1 print("TestStepHandler Launching Step!") # noqa: T201 TestStepHandler.processes.append( subprocess.Popen(step_handler_context.execute_step_args.get_command_args()) ) return iter(()) def check_step_health(self, step_handler_context) -> CheckStepHealthResult: TestStepHandler.check_step_health_count += 1 return CheckStepHealthResult.healthy() def terminate_step(self, step_handler_context): TestStepHandler.terminate_step_count += 1 raise NotImplementedError() @classmethod def reset(cls): cls.processes = [] cls.launch_step_count = 0 cls.check_step_health_count = 0 cls.terminate_step_count = 0 cls.verify_step_count = 0 @classmethod def wait_for_processes(cls): for p in cls.processes: p.wait(timeout=5) @dg.executor( name="test_step_delegating_executor", requirements=dg.multiple_process_executor_requirements(), config_schema=dg.Permissive(), ) def test_step_delegating_executor(exc_init): return StepDelegatingExecutor( TestStepHandler(), **(merge_dicts({"retries": RetryMode.DISABLED}, exc_init.executor_config)), ) @dg.op def bar_op(_): return "bar" @dg.op(tags={"foo": "bar"}) def baz_op(_, bar): return bar * 2 @dg.job(executor_def=test_step_delegating_executor) def foo_job(): baz_op(bar_op()) bar_op() def test_execute(): TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(foo_job), instance=instance, run_config={"execution": {"config": {}}}, ) TestStepHandler.wait_for_processes() assert any( [ "Starting execution with step handler TestStepHandler" in event.message # pyright: ignore[reportOperatorIssue] for event in result.all_events ] ) assert any(["STEP_START" in event for event in result.all_events]) assert result.success assert TestStepHandler.saw_baz_op assert TestStepHandler.verify_step_count == 0 def test_execute_with_tailer_offset(): TestStepHandler.reset() with dg.instance_for_test() as instance: with environ( { "DAGSTER_EXECUTOR_POP_EVENTS_OFFSET": "100000", "DAGSTER_EXECUTOR_POP_EVENTS_LIMIT": "2", "DAGSTER_STEP_DELEGATING_EXECUTOR_SLEEP_SECONDS": "0.001", } ): result = dg.execute_job( dg.reconstructable(foo_job), instance=instance, run_config={"execution": {"config": {}}}, ) TestStepHandler.wait_for_processes() assert any( [ "Starting execution with step handler TestStepHandler" in event.message # pyright: ignore[reportOperatorIssue] for event in result.all_events ] ) assert any(["STEP_START" in event for event in result.all_events]) assert result.success assert TestStepHandler.saw_baz_op assert TestStepHandler.verify_step_count == 0 def test_skip_execute(): from dagster_tests.execution_tests.engine_tests.test_jobs import define_dynamic_skipping_job TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(define_dynamic_skipping_job), instance=instance, ) TestStepHandler.wait_for_processes() assert result.success def test_dynamic_execute(): from dagster_tests.execution_tests.engine_tests.test_jobs import define_dynamic_job TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(define_dynamic_job), instance=instance, ) TestStepHandler.wait_for_processes() assert result.success assert ( len( [ e for e in result.all_events if e.event_type_value == DagsterEventType.STEP_START.value ] ) == 11 ) def test_skipping(): from dagster_tests.execution_tests.engine_tests.test_jobs import define_skpping_job TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(define_skpping_job), instance=instance, ) TestStepHandler.wait_for_processes() assert result.success def test_execute_intervals(): TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(foo_job), instance=instance, run_config={"execution": {"config": {"check_step_health_interval_seconds": 60}}}, ) TestStepHandler.wait_for_processes() assert result.success assert TestStepHandler.launch_step_count == 3 assert TestStepHandler.terminate_step_count == 0 # pipeline should complete before 60s assert TestStepHandler.check_step_health_count == 0 TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(foo_job), instance=instance, run_config={"execution": {"config": {"check_step_health_interval_seconds": 0}}}, ) TestStepHandler.wait_for_processes() assert result.success assert TestStepHandler.launch_step_count == 3 assert TestStepHandler.terminate_step_count == 0 # every step should get checked at least once # TODO: better way to test this. Skipping for now because if step finishes fast enough the # count could be smaller than 3. # assert TestStepHandler.check_step_health_count >= 3 @dg.op(tags={"database": "tiny"}) def slow_op(_): time.sleep(2) @dg.job(executor_def=test_step_delegating_executor) def three_op_job(): for i in range(3): slow_op.alias(f"slow_op_{i}")() def test_max_concurrent(): TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(three_op_job), instance=instance, run_config={"execution": {"config": {"max_concurrent": 1}}}, ) TestStepHandler.wait_for_processes() assert result.success # test that all the steps run serially, since max_concurrent is 1 active_step = None for event in result.all_events: if event.event_type_value == DagsterEventType.STEP_START.value: assert active_step is None, "A second step started before the first finished!" active_step = event.step_key elif event.event_type_value == DagsterEventType.STEP_SUCCESS.value: assert active_step == event.step_key, ( "A step finished that wasn't supposed to be active!" ) active_step = None def test_tag_concurrency_limits(): TestStepHandler.reset() with dg.instance_for_test() as instance: with dg.execute_job( dg.reconstructable(three_op_job), instance=instance, run_config={ "execution": { "config": { "max_concurrent": 6001, "tag_concurrency_limits": [ {"key": "database", "value": "tiny", "limit": 1} ], } } }, ) as result: TestStepHandler.wait_for_processes() assert result.success # test that all the steps run serially, since database=tiny can only run one at a time active_step = None for event in result.all_events: if event.event_type_value == DagsterEventType.STEP_START.value: assert active_step is None, "A second step started before the first finished!" active_step = event.step_key elif event.event_type_value == DagsterEventType.STEP_SUCCESS.value: assert active_step == event.step_key, ( "A step finished that wasn't supposed to be active!" ) active_step = None @dg.executor( name="test_step_delegating_executor_verify_step", requirements=dg.multiple_process_executor_requirements(), config_schema=dg.Permissive(), ) def test_step_delegating_executor_verify_step(exc_init): return StepDelegatingExecutor( TestStepHandler(), retries=RetryMode.DISABLED, sleep_seconds=exc_init.executor_config.get("sleep_seconds"), check_step_health_interval_seconds=exc_init.executor_config.get( "check_step_health_interval_seconds" ), should_verify_step=True, ) @dg.job(executor_def=test_step_delegating_executor_verify_step) def foo_job_verify_step(): baz_op(bar_op()) bar_op() def test_execute_verify_step(): TestStepHandler.reset() with dg.instance_for_test() as instance: result = dg.execute_job( dg.reconstructable(foo_job_verify_step), instance=instance, run_config={"execution": {"config": {}}}, ) TestStepHandler.wait_for_processes() assert any( [ "Starting execution with step handler TestStepHandler" in event.message # pyright: ignore[reportOperatorIssue] for event in result.all_events ] ) assert result.success assert TestStepHandler.verify_step_count == 3 def test_execute_using_repository_data(): TestStepHandler.reset() with dg.instance_for_test() as instance: recon_repo = ReconstructableRepository.for_module( "dagster_tests.execution_tests.engine_tests.test_step_delegating_executor", fn_name="cacheable_asset_defs", working_directory=os.path.join(os.path.dirname(__file__), "..", "..", ".."), ) recon_job = ReconstructableJob(repository=recon_repo, job_name="all_asset_job") with scoped_definitions_load_context(): with dg.execute_job( recon_job, instance=instance, ) as result: call_counts = instance.run_storage.get_cursor_values( {"compute_cacheable_data_called", "get_definitions_called"} ) assert call_counts.get("compute_cacheable_data_called") == "1" assert call_counts.get("get_definitions_called") == "5" TestStepHandler.wait_for_processes() assert any( [ "Starting execution with step handler TestStepHandler" in (event.message or "") for event in result.all_events ] ) assert result.success parent_run_id = result.run_id with dg.execute_job( recon_job, reexecution_options=dg.ReexecutionOptions(parent_run_id=parent_run_id), instance=instance, ) as result: TestStepHandler.wait_for_processes() assert any( [ "Starting execution with step handler TestStepHandler" in (event.message or "") for event in result.all_events ] ) assert result.success call_counts = instance.run_storage.get_cursor_values( {"compute_cacheable_data_called", "get_definitions_called"} ) assert call_counts.get("compute_cacheable_data_called") == "1" assert call_counts.get("get_definitions_called") == "9"
TestStepHandler
python
PrefectHQ__prefect
src/prefect/settings/models/server/services.py
{ "start": 13936, "end": 15153 }
class ____(ServicesBaseSetting): """ Settings for controlling the pause expiration service """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "services", "pause_expirations") ) enabled: bool = Field( default=True, description=""" Whether or not to start the paused flow run expiration service in the server application. If disabled, paused flows that have timed out will remain in a Paused state until a resume attempt. """, validation_alias=AliasChoices( AliasPath("enabled"), "prefect_server_services_pause_expirations_enabled", "prefect_api_services_pause_expirations_enabled", ), ) loop_seconds: float = Field( default=5, description=""" The pause expiration service will look for runs to mark as failed this often. Defaults to `5`. """, validation_alias=AliasChoices( AliasPath("loop_seconds"), "prefect_server_services_pause_expirations_loop_seconds", "prefect_api_services_pause_expirations_loop_seconds", ), )
ServerServicesPauseExpirationsSettings
python
streamlit__streamlit
lib/streamlit/elements/deck_gl_json_chart.py
{ "start": 7697, "end": 8644 }
class ____: """PydeckSelectionSerde is used to serialize and deserialize the Pydeck selection state.""" def deserialize(self, ui_value: str | None) -> PydeckState: empty_selection_state: PydeckState = { "selection": { "indices": {}, "objects": {}, } } selection_state = ( empty_selection_state if ui_value is None else json.loads(ui_value) ) # We have seen some situations where the ui_value was just an empty # dict, so we want to ensure that it always returns the empty state in # case this happens. if "selection" not in selection_state: selection_state = empty_selection_state return cast("PydeckState", AttributeDictionary(selection_state)) def serialize(self, selection_state: PydeckState) -> str: return json.dumps(selection_state, default=str)
PydeckSelectionSerde
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 18053, "end": 19601 }
class ____(PreTrainedModel): config: Dinov2WithRegistersConfig base_model_prefix = "dinov2_with_registers" main_input_name = "pixel_values" input_modalities = ("image",) supports_gradient_checkpointing = True _no_split_modules = ["Dinov2WithRegistersLayer"] _supports_sdpa = True _supports_flash_attn = True _supports_flex_attn = True _supports_attention_backend = True _can_record_outputs = { "attentions": Dinov2WithRegistersSelfAttention, } @torch.no_grad() def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None: """Initialize the weights""" if isinstance(module, (nn.Linear, nn.Conv2d)): init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_range) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): init.zeros_(module.bias) init.ones_(module.weight) elif isinstance(module, Dinov2WithRegistersEmbeddings): init.trunc_normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range) init.trunc_normal_(module.cls_token, mean=0.0, std=self.config.initializer_range) init.zeros_(module.mask_token) init.zeros_(module.register_tokens) elif isinstance(module, Dinov2WithRegistersLayerScale): # noqa: F821 init.constant_(module.lambda1, self.config.layerscale_value) @auto_docstring
Dinov2WithRegistersPreTrainedModel
python
Pylons__pyramid
tests/test_viewderivers.py
{ "start": 70816, "end": 70982 }
class ____: def __init__(self): self.messages = [] def info(self, msg): self.messages.append(msg) warn = info debug = info
DummyLogger
python
sphinx-doc__sphinx
sphinx/search/sv.py
{ "start": 193, "end": 596 }
class ____(SearchLanguage): lang = 'sv' language_name = 'Swedish' js_stemmer_rawcode = 'swedish-stemmer.js' stopwords = SWEDISH_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('swedish') def stem(self, word: str) -> str: return self.stemmer.stemWord(word.lower())
SearchSwedish
python
rushter__MLAlgorithms
mla/neuralnet/optimizers.py
{ "start": 7549, "end": 8784 }
class ____(Optimizer): def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-8): self.epsilon = epsilon self.beta_2 = beta_2 self.beta_1 = beta_1 self.lr = learning_rate self.t = 1 def update(self, network): for i, layer in enumerate(network.parametric_layers): for n in layer.parameters.keys(): grad = layer.parameters.grad[n] self.ms[i][n] = self.beta_1 * self.ms[i][n] + (1.0 - self.beta_1) * grad self.us[i][n] = np.maximum(self.beta_2 * self.us[i][n], np.abs(grad)) step = ( self.lr / (1 - self.beta_1**self.t) * self.ms[i][n] / (self.us[i][n] + self.epsilon) ) layer.parameters.step(n, -step) self.t += 1 def setup(self, network): self.ms = defaultdict(dict) self.us = defaultdict(dict) for i, layer in enumerate(network.parametric_layers): for n in layer.parameters.keys(): self.ms[i][n] = np.zeros_like(layer.parameters[n]) self.us[i][n] = np.zeros_like(layer.parameters[n])
Adamax
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1120131, "end": 1120706 }
class ____(sgqlc.types.Type, Contribution): """Represents the contribution a user made by committing to a repository. """ __schema__ = github_schema __field_names__ = ("commit_count", "repository") commit_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="commitCount") """How many commits were made on this day to this repository by the user. """ repository = sgqlc.types.Field(sgqlc.types.non_null("Repository"), graphql_name="repository") """The repository the user made a commit in."""
CreatedCommitContribution
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 36227, "end": 37480 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) entry_point: Optional[str] = Field( None, description=( "Named entry point to use, if it does not exist in the metadata of the" " package it executes the function from the package directly using" " `$packageName.$entryPoint()`" ), ) named_parameters: Optional[Dict[str, Any]] = Field( default=None, description=( "Command-line parameters passed to Python wheel task in the form of" ' `["--name=task", "--data=dbfs:/path/to/data.json"]`. Leave it empty if' " `parameters` is not null." ), examples=[{"data": "dbfs:/path/to/data.json", "name": "task"}], ) package_name: Optional[str] = Field( None, description="Name of the package to execute" ) parameters: Optional[List[str]] = Field( default=None, description=( "Command-line parameters passed to Python wheel task. Leave it empty if" " `named_parameters` is not null." ), examples=[["--name=task", "one", "two"]], )
PythonWheelTask
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 37591, "end": 42781 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): def setup_test(self): class MyTypeCompiler(compiler.GenericTypeCompiler): def visit_mytype(self, type_, **kw): return "MYTYPE" def visit_myothertype(self, type_, **kw): return "MYOTHERTYPE" class MyCompiler(compiler.SQLCompiler): def visit_json_getitem_op_binary(self, binary, operator, **kw): return self._generate_generic_binary( binary, " -> ", eager_grouping=True, **kw ) def visit_json_path_getitem_op_binary( self, binary, operator, **kw ): return self._generate_generic_binary( binary, " #> ", eager_grouping=True, **kw ) def visit_getitem_binary(self, binary, operator, **kw): raise NotImplementedError() class MyDialect(default.DefaultDialect): statement_compiler = MyCompiler type_compiler = MyTypeCompiler class MyType(JSON): __visit_name__ = "mytype" operator_classes = OperatorClass.JSON | OperatorClass.MATH self.MyType = MyType self.__dialect__ = MyDialect() def test_setup_getitem(self): col = Column("x", self.MyType()) is_(col[5].type._type_affinity, JSON) is_(col[5]["foo"].type._type_affinity, JSON) is_(col[("a", "b", "c")].type._type_affinity, JSON) @testing.combinations( (lambda col: col["foo"] + " ", "(x -> :x_1) || :param_1"), ( lambda col: col["foo"] + " " + col["bar"], "(x -> :x_1) || :param_1 || (x -> :x_2)", ), ) def test_eager_grouping_flag(self, expr, expected): """test #10479""" col = Column("x", self.MyType()) expr = testing.resolve_lambda(expr, col=col) self.assert_compile(expr, expected) def test_getindex_literal_integer(self): col = Column("x", self.MyType()) self.assert_compile(col[5], "x -> :x_1", checkparams={"x_1": 5}) def test_getindex_literal_string(self): col = Column("x", self.MyType()) self.assert_compile( col["foo"], "x -> :x_1", checkparams={"x_1": "foo"} ) def test_path_getindex_literal(self): col = Column("x", self.MyType()) self.assert_compile( col[("a", "b", 3, 4, "d")], "x #> :x_1", checkparams={"x_1": ("a", "b", 3, 4, "d")}, ) def test_getindex_sqlexpr(self): col = Column("x", self.MyType()) col2 = Column("y", Integer()) self.assert_compile(col[col2], "x -> y", checkparams={}) def test_getindex_sqlexpr_right_grouping(self): col = Column("x", self.MyType()) col2 = Column("y", Integer()) self.assert_compile( col[col2 + 8], "x -> (y + :y_1)", checkparams={"y_1": 8} ) def test_getindex_sqlexpr_left_grouping(self): col = Column("x", self.MyType()) self.assert_compile(col[8] != None, "(x -> :x_1) IS NOT NULL") # noqa def test_getindex_sqlexpr_both_grouping(self): col = Column("x", self.MyType()) col2 = Column("y", Integer()) self.assert_compile( col[col2 + 8] != None, # noqa "(x -> (y + :y_1)) IS NOT NULL", checkparams={"y_1": 8}, ) def test_override_operators(self): special_index_op = operators.custom_op("$$>") class MyOtherType(JSON, TypeEngine): __visit_name__ = "myothertype" class Comparator(TypeEngine.Comparator): def _adapt_expression(self, op, other_comparator): return special_index_op, MyOtherType() comparator_factory = Comparator col = Column("x", MyOtherType()) self.assert_compile(col[5], "x $$> :x_1", checkparams={"x_1": 5}) def _caster_combinations(fn): return testing.combinations( ("integer", Integer), ("boolean", Boolean), ("float", Float), ("string", String), )(fn) @_caster_combinations def test_cast_ops(self, caster, expected_type): expr = Column("x", JSON)["foo"] expr = getattr(expr, "as_%s" % caster)() is_(expr.type._type_affinity, expected_type) @_caster_combinations def test_cast_ops_unsupported_on_non_binary(self, caster, expected_type): expr = Column("x", JSON) meth = getattr(expr, "as_%s" % caster) assert_raises_message( exc.InvalidRequestError, r"The JSON cast operator JSON.as_%s\(\) only works" % caster, meth, ) @_caster_combinations def test_cast_ops_unsupported_on_non_json_binary( self, caster, expected_type ): expr = Column("x", self.MyType) + {"foo": "bar"} meth = getattr(expr, "as_%s" % caster) assert_raises_message( exc.InvalidRequestError, r"The JSON cast operator JSON.as_%s\(\) only works" % caster, meth, )
JSONIndexOpTest
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_add_column_with_notnull_db_default_app/models.py
{ "start": 31, "end": 108 }
class ____(models.Model): field = models.IntegerField(db_default=0)
TestTable
python
huggingface__transformers
tests/cli/test_serve.py
{ "start": 9390, "end": 13939 }
class ____: """ Mixin class for the Completions API tests, to seamlessly replicate tests across the two versions of the API (`generate` and `continuous_batching`). """ @retry def run_server(self, request): with InferenceClient(f"http://localhost:{self.port}") as client: return list(client.chat_completion(**request)) @parameterized.expand( [ ("default_request", {}), ("one_token", {"max_tokens": 1}), ("different_model", {"model": "HuggingFaceTB/SmolLM2-135M-Instruct"}), ( "tool_call", { "tools": [ { "function": { "name": "foo_bar", "parameters": {"type": "object"}, "description": "Foo bar", }, "type": "function", } ] }, ), ] ) def test_requests(self, test_name: str, request_flags: dict): """Tests that the completions app gracefully handles GOOD requests, producing the expected output payloads.""" request = { "model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hello, how are you?"}], "stream": True, # We don't support "stream": False yet "max_tokens": 5, # Small generation by default } request.update(request_flags) all_payloads = self.run_server(request) # If a request is successful, the returned payload needs to follow the schema, which we test here. # NOTE: the output of our server is wrapped by `InferenceClient`, which sends fields even when they # are empty. # Finish reason: the last payload should have a finish reason of "length" or "stop", all others should be empty finish_reasons = [payload.choices[0].finish_reason for payload in all_payloads] self.assertTrue(finish_reasons[-1] in ["length", "stop"]) self.assertTrue(all(reason is None for reason in finish_reasons[:-1])) # Role: the first payload should have a role of "assistant", all others should be empty roles = [payload.choices[0].delta.role for payload in all_payloads] self.assertEqual(roles[0], "assistant") self.assertTrue(all(role is None for role in roles[1:])) # Content: the first and the last payload shouldn't have content (role and finish reason). It may be empty # in some other payload positions, e.g. tool calls. contents = [payload.choices[0].delta.content for payload in all_payloads] self.assertTrue(contents[0] is None and contents[-1] is None) self.assertTrue(any(content is not None for content in contents[1:-1])) # TODO: add "usage" field to output and test it def test_generation_config_in_request(self): """Tests that the generation config is correctly passed into the generation call.""" generation_config = GenerationConfig(do_sample=False, temperature=0.0) request = { "model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hello, how are you?"}], "stream": True, "max_tokens": 10, "extra_body": { "generation_config": generation_config.to_json_string(), }, } all_payloads = self.run_server(request) contents = [payload.choices[0].delta.content for payload in all_payloads] output_text = "".join([text for text in contents if text is not None]) # The generation config sets greedy decoding, so the output is reproducible. By default, `Qwen/Qwen3-0.6B` # sets `do_sample=True` self.assertEqual(output_text, '<think>\nOkay, the user just asked, "') def test_early_return_due_to_length(self): request = { "model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hello, how are you?"}], "stream": True, "max_tokens": 3, } all_payloads = self.run_server(request) last_payload = all_payloads[-1] self.assertTrue(last_payload.choices[0]["finish_reason"] == "length") # TODO: one test for each request flag, to confirm it is working as expected # TODO: speed-based test to confirm that KV cache is working across requests
ServeCompletionsMixin
python
networkx__networkx
networkx/algorithms/tree/tests/test_recognition.py
{ "start": 2214, "end": 4521 }
class ____(TestTreeRecognition): graph = nx.DiGraph multigraph = nx.MultiDiGraph def test_disconnected_graph(): # https://github.com/networkx/networkx/issues/1144 G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)]) assert not nx.is_tree(G) G = nx.DiGraph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)]) assert not nx.is_tree(G) def test_dag_nontree(): G = nx.DiGraph() G.add_edges_from([(0, 1), (0, 2), (1, 2)]) assert not nx.is_tree(G) assert nx.is_directed_acyclic_graph(G) def test_multicycle(): G = nx.MultiDiGraph() G.add_edges_from([(0, 1), (0, 1)]) assert not nx.is_tree(G) assert nx.is_directed_acyclic_graph(G) def test_emptybranch(): G = nx.DiGraph() G.add_nodes_from(range(10)) assert nx.is_branching(G) assert not nx.is_arborescence(G) def test_is_branching_empty_graph_raises(): G = nx.DiGraph() with pytest.raises(nx.NetworkXPointlessConcept, match="G has no nodes."): nx.is_branching(G) def test_path(): G = nx.DiGraph() nx.add_path(G, range(5)) assert nx.is_branching(G) assert nx.is_arborescence(G) def test_notbranching1(): # Acyclic violation. G = nx.MultiDiGraph() G.add_nodes_from(range(10)) G.add_edges_from([(0, 1), (1, 0)]) assert not nx.is_branching(G) assert not nx.is_arborescence(G) def test_notbranching2(): # In-degree violation. G = nx.MultiDiGraph() G.add_nodes_from(range(10)) G.add_edges_from([(0, 1), (0, 2), (3, 2)]) assert not nx.is_branching(G) assert not nx.is_arborescence(G) def test_notarborescence1(): # Not an arborescence due to not spanning. G = nx.MultiDiGraph() G.add_nodes_from(range(10)) G.add_edges_from([(0, 1), (0, 2), (1, 3), (5, 6)]) assert nx.is_branching(G) assert not nx.is_arborescence(G) def test_notarborescence2(): # Not an arborescence due to in-degree violation. G = nx.MultiDiGraph() nx.add_path(G, range(5)) G.add_edge(6, 4) assert not nx.is_branching(G) assert not nx.is_arborescence(G) def test_is_arborescense_empty_graph_raises(): G = nx.DiGraph() with pytest.raises(nx.NetworkXPointlessConcept, match="G has no nodes."): nx.is_arborescence(G)
TestDirectedTreeRecognition
python
walkccc__LeetCode
solutions/2859. Sum of Values at Indices With K Set Bits/2859.py
{ "start": 0, "end": 171 }
class ____: def sumIndicesWithKSetBits(self, nums: list[int], k: int) -> int: return sum(num for i, num in enumerate(nums) if i.bit_count() == k)
Solution
python
django__django
tests/proxy_model_inheritance/models.py
{ "start": 149, "end": 201 }
class ____(ProxyModel): pass
ConcreteModelSubclass
python
eventlet__eventlet
eventlet/support/greendns.py
{ "start": 11371, "end": 35489 }
class ____: """Resolver class which can also use /etc/hosts Initialise with a HostsResolver instance in order for it to also use the hosts file. """ def __init__(self, hosts_resolver=None, filename='/etc/resolv.conf'): """Initialise the resolver proxy :param hosts_resolver: An instance of HostsResolver to use. :param filename: The filename containing the resolver configuration. The default value is correct for both UNIX and Windows, on Windows it will result in the configuration being read from the Windows registry. """ self._hosts = hosts_resolver self._filename = filename # NOTE(dtantsur): we cannot create a resolver here since this code is # executed on eventlet import. In an environment without DNS, creating # a Resolver will fail making eventlet unusable at all. See # https://github.com/eventlet/eventlet/issues/736 for details. self._cached_resolver = None @property def _resolver(self): if self._cached_resolver is None: self.clear() return self._cached_resolver @_resolver.setter def _resolver(self, value): self._cached_resolver = value def clear(self): self._resolver = dns.resolver.Resolver(filename=self._filename) self._resolver.cache = dns.resolver.LRUCache() def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, tcp=False, source=None, raise_on_no_answer=True, _hosts_rdtypes=(dns.rdatatype.A, dns.rdatatype.AAAA), use_network=True): """Query the resolver, using /etc/hosts if enabled. Behavior: 1. if hosts is enabled and contains answer, return it now 2. query nameservers for qname if use_network is True 3. if qname did not contain dots, pretend it was top-level domain, query "foobar." and append to previous result """ result = [None, None, 0] if qname is None: qname = '0.0.0.0' if isinstance(qname, str) or isinstance(qname, bytes): qname = dns.name.from_text(qname, None) def step(fun, *args, **kwargs): try: a = fun(*args, **kwargs) except Exception as e: result[1] = e return False if a.rrset is not None and len(a.rrset): if result[0] is None: result[0] = a else: result[0].rrset.union_update(a.rrset) result[2] += len(a.rrset) return True def end(): if result[0] is not None: if raise_on_no_answer and result[2] == 0: raise dns.resolver.NoAnswer return result[0] if result[1] is not None: if raise_on_no_answer or not isinstance(result[1], dns.resolver.NoAnswer): raise result[1] raise dns.resolver.NXDOMAIN(qnames=(qname,)) if (self._hosts and (rdclass == dns.rdataclass.IN) and (rdtype in _hosts_rdtypes)): if step(self._hosts.query, qname, rdtype, raise_on_no_answer=False): if (result[0] is not None) or (result[1] is not None) or (not use_network): return end() # Main query step(self._resolver.query, qname, rdtype, rdclass, tcp, source, raise_on_no_answer=False) # `resolv.conf` docs say unqualified names must resolve from search (or local) domain. # However, common OS `getaddrinfo()` implementations append trailing dot (e.g. `db -> db.`) # and ask nameservers, as if top-level domain was queried. # This step follows established practice. # https://github.com/nameko/nameko/issues/392 # https://github.com/eventlet/eventlet/issues/363 if len(qname) == 1: step(self._resolver.query, qname.concatenate(dns.name.root), rdtype, rdclass, tcp, source, raise_on_no_answer=False) return end() def getaliases(self, hostname): """Return a list of all the aliases of a given hostname""" if self._hosts: aliases = self._hosts.getaliases(hostname) else: aliases = [] while True: try: ans = self._resolver.query(hostname, dns.rdatatype.CNAME) except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN): break else: aliases.extend(str(rr.target) for rr in ans.rrset) hostname = ans[0].target return aliases resolver = ResolverProxy(hosts_resolver=HostsResolver()) def resolve(name, family=socket.AF_INET, raises=True, _proxy=None, use_network=True): """Resolve a name for a given family using the global resolver proxy. This method is called by the global getaddrinfo() function. If use_network is False, only resolution via hosts file will be performed. Return a dns.resolver.Answer instance. If there is no answer it's rrset will be emtpy. """ if family == socket.AF_INET: rdtype = dns.rdatatype.A elif family == socket.AF_INET6: rdtype = dns.rdatatype.AAAA else: raise socket.gaierror(socket.EAI_FAMILY, 'Address family not supported') if _proxy is None: _proxy = resolver try: try: return _proxy.query(name, rdtype, raise_on_no_answer=raises, use_network=use_network) except dns.resolver.NXDOMAIN: if not raises: return HostsAnswer(dns.name.Name(name), rdtype, dns.rdataclass.IN, None, False) raise except dns.exception.Timeout: _raise_new_error(EAI_EAGAIN_ERROR) except dns.exception.DNSException: _raise_new_error(EAI_NODATA_ERROR) def resolve_cname(host): """Return the canonical name of a hostname""" try: ans = resolver.query(host, dns.rdatatype.CNAME) except dns.resolver.NoAnswer: return host except dns.exception.Timeout: _raise_new_error(EAI_EAGAIN_ERROR) except dns.exception.DNSException: _raise_new_error(EAI_NODATA_ERROR) else: return str(ans[0].target) def getaliases(host): """Return a list of for aliases for the given hostname This method does translate the dnspython exceptions into socket.gaierror exceptions. If no aliases are available an empty list will be returned. """ try: return resolver.getaliases(host) except dns.exception.Timeout: _raise_new_error(EAI_EAGAIN_ERROR) except dns.exception.DNSException: _raise_new_error(EAI_NODATA_ERROR) def _getaddrinfo_lookup(host, family, flags): """Resolve a hostname to a list of addresses Helper function for getaddrinfo. """ if flags & socket.AI_NUMERICHOST: _raise_new_error(EAI_NONAME_ERROR) addrs = [] if family == socket.AF_UNSPEC: err = None for use_network in [False, True]: for qfamily in [socket.AF_INET6, socket.AF_INET]: try: answer = resolve(host, qfamily, False, use_network=use_network) except socket.gaierror as e: if e.errno not in (socket.EAI_AGAIN, EAI_NONAME_ERROR.errno, EAI_NODATA_ERROR.errno): raise err = e else: if answer.rrset: addrs.extend(rr.address for rr in answer.rrset) if addrs: break if err is not None and not addrs: raise err elif family == socket.AF_INET6 and flags & socket.AI_V4MAPPED: answer = resolve(host, socket.AF_INET6, False) if answer.rrset: addrs = [rr.address for rr in answer.rrset] if not addrs or flags & socket.AI_ALL: answer = resolve(host, socket.AF_INET, False) if answer.rrset: addrs = ['::ffff:' + rr.address for rr in answer.rrset] else: answer = resolve(host, family, False) if answer.rrset: addrs = [rr.address for rr in answer.rrset] return str(answer.qname), addrs def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): """Replacement for Python's socket.getaddrinfo This does the A and AAAA lookups asynchronously after which it calls the OS' getaddrinfo(3) using the AI_NUMERICHOST flag. This flag ensures getaddrinfo(3) does not use the network itself and allows us to respect all the other arguments like the native OS. """ if isinstance(host, str): host = host.encode('idna').decode('ascii') elif isinstance(host, bytes): host = host.decode("ascii") if host is not None and not is_ip_addr(host): qname, addrs = _getaddrinfo_lookup(host, family, flags) else: qname = host addrs = [host] aiflags = (flags | socket.AI_NUMERICHOST) & (0xffff ^ socket.AI_CANONNAME) res = [] err = None for addr in addrs: try: ai = socket.getaddrinfo(addr, port, family, type, proto, aiflags) except OSError as e: if flags & socket.AI_ADDRCONFIG: err = e continue raise res.extend(ai) if not res: if err: raise err raise socket.gaierror(socket.EAI_NONAME, 'No address found') if flags & socket.AI_CANONNAME: if not is_ip_addr(qname): qname = resolve_cname(qname).encode('ascii').decode('idna') ai = res[0] res[0] = (ai[0], ai[1], ai[2], qname, ai[4]) return res def gethostbyname(hostname): """Replacement for Python's socket.gethostbyname""" if is_ipv4_addr(hostname): return hostname rrset = resolve(hostname) return rrset[0].address def gethostbyname_ex(hostname): """Replacement for Python's socket.gethostbyname_ex""" if is_ipv4_addr(hostname): return (hostname, [], [hostname]) ans = resolve(hostname) aliases = getaliases(hostname) addrs = [rr.address for rr in ans.rrset] qname = str(ans.qname) if qname[-1] == '.': qname = qname[:-1] return (qname, aliases, addrs) def getnameinfo(sockaddr, flags): """Replacement for Python's socket.getnameinfo. Currently only supports IPv4. """ try: host, port = sockaddr except (ValueError, TypeError): if not isinstance(sockaddr, tuple): del sockaddr # to pass a stdlib test that is # hyper-careful about reference counts raise TypeError('getnameinfo() argument 1 must be a tuple') else: # must be ipv6 sockaddr, pretending we don't know how to resolve it _raise_new_error(EAI_NONAME_ERROR) if (flags & socket.NI_NAMEREQD) and (flags & socket.NI_NUMERICHOST): # Conflicting flags. Punt. _raise_new_error(EAI_NONAME_ERROR) if is_ipv4_addr(host): try: rrset = resolver.query( dns.reversename.from_address(host), dns.rdatatype.PTR) if len(rrset) > 1: raise OSError('sockaddr resolved to multiple addresses') host = rrset[0].target.to_text(omit_final_dot=True) except dns.exception.Timeout: if flags & socket.NI_NAMEREQD: _raise_new_error(EAI_EAGAIN_ERROR) except dns.exception.DNSException: if flags & socket.NI_NAMEREQD: _raise_new_error(EAI_NONAME_ERROR) else: try: rrset = resolver.query(host) if len(rrset) > 1: raise OSError('sockaddr resolved to multiple addresses') if flags & socket.NI_NUMERICHOST: host = rrset[0].address except dns.exception.Timeout: _raise_new_error(EAI_EAGAIN_ERROR) except dns.exception.DNSException: raise socket.gaierror( (socket.EAI_NODATA, 'No address associated with hostname')) if not (flags & socket.NI_NUMERICSERV): proto = (flags & socket.NI_DGRAM) and 'udp' or 'tcp' port = socket.getservbyport(port, proto) return (host, port) def _net_read(sock, count, expiration): """coro friendly replacement for dns.query._net_read Read the specified number of bytes from sock. Keep trying until we either get the desired amount, or we hit EOF. A Timeout exception will be raised if the operation is not completed by the expiration time. """ s = bytearray() while count > 0: try: n = sock.recv(count) except socket.timeout: # Q: Do we also need to catch coro.CoroutineSocketWake and pass? if expiration - time.time() <= 0.0: raise dns.exception.Timeout eventlet.sleep(0.01) continue if n == b'': raise EOFError count = count - len(n) s += n return s def _net_write(sock, data, expiration): """coro friendly replacement for dns.query._net_write Write the specified data to the socket. A Timeout exception will be raised if the operation is not completed by the expiration time. """ current = 0 l = len(data) while current < l: try: current += sock.send(data[current:]) except socket.timeout: # Q: Do we also need to catch coro.CoroutineSocketWake and pass? if expiration - time.time() <= 0.0: raise dns.exception.Timeout # Test if raise_on_truncation is an argument we should handle. # It was newly added in dnspython 2.0 try: dns.message.from_wire("", raise_on_truncation=True) except dns.message.ShortHeader: _handle_raise_on_truncation = True except TypeError: # Argument error, there is no argument "raise_on_truncation" _handle_raise_on_truncation = False def udp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53, af=None, source=None, source_port=0, ignore_unexpected=False, one_rr_per_rrset=False, ignore_trailing=False, raise_on_truncation=False, sock=None, ignore_errors=False): """coro friendly replacement for dns.query.udp Return the response obtained after sending a query via UDP. @param q: the query @type q: dns.message.Message @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param ignore_unexpected: If True, ignore responses from unexpected sources. The default is False. @type ignore_unexpected: bool @param one_rr_per_rrset: If True, put each RR into its own RRset. @type one_rr_per_rrset: bool @param ignore_trailing: If True, ignore trailing junk at end of the received message. @type ignore_trailing: bool @param raise_on_truncation: If True, raise an exception if the TC bit is set. @type raise_on_truncation: bool @param sock: the socket to use for the query. If None, the default, a socket is created. Note that if a socket is provided, it must be a nonblocking datagram socket, and the source and source_port are ignored. @type sock: socket.socket | None @param ignore_errors: if various format errors or response mismatches occur, continue listening. @type ignore_errors: bool""" wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: # Purge any stray zeroes in source address. When doing the tuple comparison # below, we need to always ensure both our target and where we receive replies # from are compared with all zeroes removed so that we don't erroneously fail. # e.g. ('00::1', 53, 0, 0) != ('::1', 53, 0, 0) where_trunc = dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(where)) destination = (where_trunc, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) if sock: s = sock else: s = socket.socket(af, socket.SOCK_DGRAM) s.settimeout(timeout) try: expiration = compute_expiration(dns.query, timeout) if source is not None: s.bind(source) while True: try: s.sendto(wire, destination) break except socket.timeout: # Q: Do we also need to catch coro.CoroutineSocketWake and pass? if expiration - time.time() <= 0.0: raise dns.exception.Timeout eventlet.sleep(0.01) continue tried = False while True: # If we've tried to receive at least once, check to see if our # timer expired if tried and (expiration - time.time() <= 0.0): raise dns.exception.Timeout # Sleep if we are retrying the operation due to a bad source # address or a socket timeout. if tried: eventlet.sleep(0.01) tried = True try: (wire, from_address) = s.recvfrom(65535) except socket.timeout: # Q: Do we also need to catch coro.CoroutineSocketWake and pass? continue if dns.inet.af_for_address(from_address[0]) == dns.inet.AF_INET6: # Purge all possible zeroes for ipv6 to match above logic addr = from_address[0] addr = dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(addr)) from_address = (addr, from_address[1], from_address[2], from_address[3]) if from_address != destination: if ignore_unexpected: continue else: raise dns.query.UnexpectedSource( 'got a response from %s instead of %s' % (from_address, destination)) try: if _handle_raise_on_truncation: r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset, ignore_trailing=ignore_trailing, raise_on_truncation=raise_on_truncation) else: r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset, ignore_trailing=ignore_trailing) if not q.is_response(r): raise dns.query.BadResponse() break except dns.message.Truncated as e: if ignore_errors and not q.is_response(e.message()): continue else: raise except Exception: if ignore_errors: continue else: raise finally: s.close() return r def tcp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53, af=None, source=None, source_port=0, one_rr_per_rrset=False, ignore_trailing=False, sock=None): """coro friendly replacement for dns.query.tcp Return the response obtained after sending a query via TCP. @param q: the query @type q: dns.message.Message object @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @type ignore_unexpected: bool @param one_rr_per_rrset: If True, put each RR into its own RRset. @type one_rr_per_rrset: bool @param ignore_trailing: If True, ignore trailing junk at end of the received message. @type ignore_trailing: bool @param sock: the socket to use for the query. If None, the default, a socket is created. Note that if a socket is provided, it must be a nonblocking datagram socket, and the source and source_port are ignored. @type sock: socket.socket | None""" wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: destination = (where, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) if sock: s = sock else: s = socket.socket(af, socket.SOCK_STREAM) s.settimeout(timeout) try: expiration = compute_expiration(dns.query, timeout) if source is not None: s.bind(source) while True: try: s.connect(destination) break except socket.timeout: # Q: Do we also need to catch coro.CoroutineSocketWake and pass? if expiration - time.time() <= 0.0: raise dns.exception.Timeout eventlet.sleep(0.01) continue l = len(wire) # copying the wire into tcpmsg is inefficient, but lets us # avoid writev() or doing a short write that would get pushed # onto the net tcpmsg = struct.pack("!H", l) + wire _net_write(s, tcpmsg, expiration) ldata = _net_read(s, 2, expiration) (l,) = struct.unpack("!H", ldata) wire = bytes(_net_read(s, l, expiration)) finally: s.close() r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset, ignore_trailing=ignore_trailing) if not q.is_response(r): raise dns.query.BadResponse() return r def reset(): resolver.clear() # Install our coro-friendly replacements for the tcp and udp query methods. dns.query.tcp = tcp dns.query.udp = udp
ResolverProxy
python
getsentry__sentry
tests/sentry/integrations/slack/webhooks/commands/__init__.py
{ "start": 834, "end": 3885 }
class ____(APITestCase, TestCase): endpoint = "sentry-integration-slack-commands" method = "post" def setUp(self) -> None: super().setUp() self.slack_id = "UXXXXXXX1" self.external_id = "new-slack-id" self.channel_name = "my-channel" self.channel_id = "my-channel_id" self.response_url = "http://example.slack.com/response_url" self.integration = install_slack(self.organization, self.external_id) with assume_test_silo_mode(SiloMode.CONTROL): self.idp = self.create_identity_provider( type=EXTERNAL_PROVIDERS[ExternalProviders.SLACK], external_id=self.external_id, config={}, ) self.login_as(self.user) def send_slack_message(self, command: str, **kwargs: Any) -> dict[str, str]: response = self.get_slack_response( { "text": command, "team_id": self.external_id, "user_id": self.slack_id, "channel_id": self.channel_id, **kwargs, } ) return orjson.loads(response.content) def link_user(self) -> None: return link_user(user=self.user, idp=self.idp, slack_id=self.slack_id) def link_team(self, team: Team | None = None) -> None: return link_team( team=team or self.team, integration=self.integration, channel_name=self.channel_name, channel_id=self.channel_id, ) def get_slack_response( self, payload: Mapping[str, str], status_code: int | None = None ) -> HttpResponse: """Shadow get_success_response but with a non-JSON payload.""" data = urlencode(payload).encode("utf-8") response = self.client.post( reverse(self.endpoint), content_type="application/x-www-form-urlencoded", data=data, **set_signing_secret(options.get("slack.signing-secret"), data), ) assert response.status_code == (status_code or status.HTTP_200_OK) return response @pytest.fixture(autouse=True) def mock_webhook_send(self) -> Generator[None]: with patch( "slack_sdk.webhook.WebhookClient.send", return_value=WebhookResponse( url="", body='{"ok": true}', headers={}, status_code=200, ), ) as self.mock_webhook: yield @pytest.fixture(autouse=True) def mock_chat_postMessage(self) -> Generator[None]: with patch( "slack_sdk.web.WebClient.chat_postMessage", return_value=SlackResponse( client=None, http_verb="POST", api_url="https://slack.com/api/chat.postMessage", req_args={}, data={"ok": True}, headers={}, status_code=200, ), ) as self.mock_post: yield
SlackCommandsTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/cloud_storage_compute_log_manager.py
{ "start": 7662, "end": 11105 }
class ____: def __init__(self, manager): self._manager = manager self._subscriptions = defaultdict(list) self._shutdown_event = None self._polling_thread = None def _log_key(self, subscription: CapturedLogSubscription) -> Sequence[str]: return subscription.log_key def _watch_key(self, log_key: Sequence[str]) -> str: return json.dumps(log_key) def _start_polling_thread(self) -> None: if self._polling_thread: return self._shutdown_event = threading.Event() self._polling_thread = threading.Thread( target=self._poll, args=[self._shutdown_event], name="polling-compute-log-subscription", daemon=True, ) self._polling_thread.start() def _stop_polling_thread(self) -> None: if not self._polling_thread: return old_shutdown_event = self._shutdown_event old_shutdown_event.set() # set to signal to the old thread to die # type: ignore self._polling_thread = None self._shutdown_event = None def add_subscription(self, subscription: CapturedLogSubscription) -> None: if not self._polling_thread: self._start_polling_thread() if self.is_complete(subscription): subscription.fetch() subscription.complete() else: log_key = self._log_key(subscription) watch_key = self._watch_key(log_key) self._subscriptions[watch_key].append(subscription) def is_complete(self, subscription: CapturedLogSubscription) -> bool: return self._manager.is_capture_complete(subscription.log_key) def remove_subscription(self, subscription: CapturedLogSubscription) -> None: log_key = self._log_key(subscription) watch_key = self._watch_key(log_key) if subscription in self._subscriptions[watch_key]: self._subscriptions[watch_key].remove(subscription) if len(self._subscriptions[watch_key]) == 0: del self._subscriptions[watch_key] subscription.complete() if not len(self._subscriptions) and self._polling_thread: self._stop_polling_thread() def remove_all_subscriptions(self, log_key: Sequence[str]) -> None: watch_key = self._watch_key(log_key) for subscription in self._subscriptions.pop(watch_key, []): subscription.complete() if not len(self._subscriptions) and self._polling_thread: self._stop_polling_thread() def notify_subscriptions(self, log_key: Sequence[str]) -> None: watch_key = self._watch_key(log_key) for subscription in self._subscriptions[watch_key]: subscription.fetch() def _poll(self, shutdown_event: threading.Event) -> None: while True: if shutdown_event.is_set(): return # need to do something smarter here that keeps track of updates for subscriptions in self._subscriptions.values(): for subscription in subscriptions: if shutdown_event.is_set(): return subscription.fetch() time.sleep(SUBSCRIPTION_POLLING_INTERVAL) def dispose(self) -> None: if self._shutdown_event: self._shutdown_event.set()
PollingComputeLogSubscriptionManager
python
davidhalter__jedi
sith.py
{ "start": 1697, "end": 2224 }
class ____(object): _files = None @staticmethod def fetch(file_path): if not os.path.isdir(file_path): yield file_path return for root, dirnames, filenames in os.walk(file_path): for name in filenames: if name.endswith('.py'): yield os.path.join(root, name) @classmethod def files(cls, file_path): if cls._files is None: cls._files = list(cls.fetch(file_path)) return cls._files
SourceFinder
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 29228, "end": 29808 }
class ____: def __init__(self, reason: str = "") -> None: self.reason = reason def __call__(self, fn, *args, **kwargs): @functools.wraps(fn) def wrapper(test_self): if config.cpp_wrapper: raise unittest.SkipTest(f"cpp wrapper bug to be fixed: {self.reason}") return fn(test_self, *args, **kwargs) return wrapper def is_dynamic_shape_enabled(): # What's the best way to decide this? return not torch._dynamo.config.assume_static_by_default @instantiate_parametrized_tests
skip_if_cpp_wrapper
python
tiangolo__fastapi
tests/test_serialize_response_dataclass.py
{ "start": 199, "end": 4998 }
class ____: name: str date: datetime price: Optional[float] = None owner_ids: Optional[List[int]] = None @app.get("/items/valid", response_model=Item) def get_valid(): return {"name": "valid", "date": datetime(2021, 7, 26), "price": 1.0} @app.get("/items/object", response_model=Item) def get_object(): return Item( name="object", date=datetime(2021, 7, 26), price=1.0, owner_ids=[1, 2, 3] ) @app.get("/items/coerce", response_model=Item) def get_coerce(): return {"name": "coerce", "date": datetime(2021, 7, 26).isoformat(), "price": "1.0"} @app.get("/items/validlist", response_model=List[Item]) def get_validlist(): return [ {"name": "foo", "date": datetime(2021, 7, 26)}, {"name": "bar", "date": datetime(2021, 7, 26), "price": 1.0}, { "name": "baz", "date": datetime(2021, 7, 26), "price": 2.0, "owner_ids": [1, 2, 3], }, ] @app.get("/items/objectlist", response_model=List[Item]) def get_objectlist(): return [ Item(name="foo", date=datetime(2021, 7, 26)), Item(name="bar", date=datetime(2021, 7, 26), price=1.0), Item(name="baz", date=datetime(2021, 7, 26), price=2.0, owner_ids=[1, 2, 3]), ] @app.get("/items/no-response-model/object") def get_no_response_model_object(): return Item( name="object", date=datetime(2021, 7, 26), price=1.0, owner_ids=[1, 2, 3] ) @app.get("/items/no-response-model/objectlist") def get_no_response_model_objectlist(): return [ Item(name="foo", date=datetime(2021, 7, 26)), Item(name="bar", date=datetime(2021, 7, 26), price=1.0), Item(name="baz", date=datetime(2021, 7, 26), price=2.0, owner_ids=[1, 2, 3]), ] client = TestClient(app) def test_valid(): response = client.get("/items/valid") response.raise_for_status() assert response.json() == { "name": "valid", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": None, } def test_object(): response = client.get("/items/object") response.raise_for_status() assert response.json() == { "name": "object", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": [1, 2, 3], } def test_coerce(): response = client.get("/items/coerce") response.raise_for_status() assert response.json() == { "name": "coerce", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": None, } def test_validlist(): response = client.get("/items/validlist") response.raise_for_status() assert response.json() == [ { "name": "foo", "date": datetime(2021, 7, 26).isoformat(), "price": None, "owner_ids": None, }, { "name": "bar", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": None, }, { "name": "baz", "date": datetime(2021, 7, 26).isoformat(), "price": 2.0, "owner_ids": [1, 2, 3], }, ] def test_objectlist(): response = client.get("/items/objectlist") response.raise_for_status() assert response.json() == [ { "name": "foo", "date": datetime(2021, 7, 26).isoformat(), "price": None, "owner_ids": None, }, { "name": "bar", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": None, }, { "name": "baz", "date": datetime(2021, 7, 26).isoformat(), "price": 2.0, "owner_ids": [1, 2, 3], }, ] def test_no_response_model_object(): response = client.get("/items/no-response-model/object") response.raise_for_status() assert response.json() == { "name": "object", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": [1, 2, 3], } def test_no_response_model_objectlist(): response = client.get("/items/no-response-model/objectlist") response.raise_for_status() assert response.json() == [ { "name": "foo", "date": datetime(2021, 7, 26).isoformat(), "price": None, "owner_ids": None, }, { "name": "bar", "date": datetime(2021, 7, 26).isoformat(), "price": 1.0, "owner_ids": None, }, { "name": "baz", "date": datetime(2021, 7, 26).isoformat(), "price": 2.0, "owner_ids": [1, 2, 3], }, ]
Item
python
oauthlib__oauthlib
tests/oauth2/rfc6749/endpoints/test_resource_owner_association.py
{ "start": 370, "end": 4311 }
class ____(TestCase): auth_uri = 'http://example.com/path?client_id=abc' token_uri = 'http://example.com/path' def set_client(self, request): request.client = mock.MagicMock() request.client.client_id = 'mocked' return True def set_user(self, client_id, code, client, request): request.user = 'test' return True def set_user_from_username(self, username, password, client, request): request.user = 'test' return True def set_user_from_credentials(self, request): request.user = 'test' request.client = mock.MagicMock() request.client.client_id = 'mocked' return True def inspect_client(self, request, refresh_token=False): if not request.user: raise ValueError() return 'abc' def setUp(self): self.validator = mock.MagicMock(spec=RequestValidator) self.validator.get_default_redirect_uri.return_value = 'http://i.b./path' self.validator.get_code_challenge.return_value = None self.validator.authenticate_client.side_effect = self.set_client self.web = WebApplicationServer(self.validator, token_generator=self.inspect_client) self.mobile = MobileApplicationServer(self.validator, token_generator=self.inspect_client) self.legacy = LegacyApplicationServer(self.validator, token_generator=self.inspect_client) self.backend = BackendApplicationServer(self.validator, token_generator=self.inspect_client) def test_web_application(self): # TODO: code generator + intercept test h, _, s = self.web.create_authorization_response( self.auth_uri + '&response_type=code', credentials={'user': 'test'}, scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) code = get_query_credentials(h['Location'])['code'][0] self.assertRaises(ValueError, self.web.create_token_response, self.token_uri, body='grant_type=authorization_code&code=%s' % code) self.validator.validate_code.side_effect = self.set_user _, body, _ = self.web.create_token_response(self.token_uri, body='grant_type=authorization_code&code=%s' % code) self.assertEqual(json.loads(body)['access_token'], 'abc') def test_mobile_application(self): self.assertRaises(ValueError, self.mobile.create_authorization_response, self.auth_uri + '&response_type=token') h, _, s = self.mobile.create_authorization_response( self.auth_uri + '&response_type=token', credentials={'user': 'test'}, scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertEqual(get_fragment_credentials(h['Location'])['access_token'][0], 'abc') def test_legacy_application(self): body = 'grant_type=password&username=abc&password=secret' self.assertRaises(ValueError, self.legacy.create_token_response, self.token_uri, body=body) self.validator.validate_user.side_effect = self.set_user_from_username _, body, _ = self.legacy.create_token_response( self.token_uri, body=body) self.assertEqual(json.loads(body)['access_token'], 'abc') def test_backend_application(self): body = 'grant_type=client_credentials' self.assertRaises(ValueError, self.backend.create_token_response, self.token_uri, body=body) self.validator.authenticate_client.side_effect = self.set_user_from_credentials _, body, _ = self.backend.create_token_response( self.token_uri, body=body) self.assertEqual(json.loads(body)['access_token'], 'abc')
ResourceOwnerAssociationTest
python
python-openxml__python-docx
src/docx/enum/section.py
{ "start": 888, "end": 1474 }
class ____(BaseXmlEnum): """Alias: **WD_ORIENT** Specifies the page layout orientation. Example:: from docx.enum.section import WD_ORIENT section = document.sections[-1] section.orientation = WD_ORIENT.LANDSCAPE MS API name: `WdOrientation` MS API URL: http://msdn.microsoft.com/en-us/library/office/ff837902.aspx """ PORTRAIT = (0, "portrait", "Portrait orientation.") """Portrait orientation.""" LANDSCAPE = (1, "landscape", "Landscape orientation.") """Landscape orientation.""" WD_ORIENT = WD_ORIENTATION
WD_ORIENTATION
python
pytorch__pytorch
test/dynamo/test_utils.py
{ "start": 36792, "end": 39752 }
class ____(TestCase): """ Test for parsing inductor config for logging in CompilationMetrics. """ class TestObject: def __init__(self, a, b): self.a = a self.b = b def test_inductor_config_jsonify(self): """ Sanity check if the actual inductor config is parsed correctly """ inductor_config_json = utils._scrubbed_inductor_config_for_logging() self.assertTrue(isinstance(inductor_config_json, str)) self.assertIn('trace"', inductor_config_json) @mock.patch("torch._dynamo.utils.torch._inductor.config") def test_inductor_config_parsing_non_conforming_items(self, mocked_inductor_config): """ Test if the inductor config is parsed correctly when the config is - None - not a dict - not json serializable - complex unserializable objects """ obj = TestCase test_mock_config = { "some": {"name": obj, "some": True}, "data": {"name": obj, "some": True}, "list": [ {"name": obj, "some": True}, {"name": obj, "some": True}, ], "object": { "name": obj, "some": True, "data": {"name": obj, "some": True}, }, } expected = ( """{"data": {"name": "Value is not JSON serializable", "some": true}, """ """"list": [{"name": "Value is not JSON serializable", "some": true}, """ """{"name": "Value is not JSON serializable", "some": true}], """ """"object": {"data": {"name": "Value is not JSON serializable", "some": true}, """ """"name": "Value is not JSON serializable", "some": true}, """ """"some": {"name": "Value is not JSON serializable", "some": true}}""" ) mocked_inductor_config.get_config_copy.return_value = test_mock_config inductor_config_json = utils._scrubbed_inductor_config_for_logging() self.assertEqual(inductor_config_json, expected) expected = "{}" mocked_inductor_config.get_config_copy.return_value = {obj: obj} inductor_config_json = utils._scrubbed_inductor_config_for_logging() self.assertEqual(inductor_config_json, expected) expected = "Inductor Config is not JSON serializable" mocked_inductor_config.get_config_copy.return_value = obj inductor_config_json = utils._scrubbed_inductor_config_for_logging() self.assertEqual(inductor_config_json, expected) expected = None mocked_inductor_config.get_config_copy.return_value = None inductor_config_json = utils._scrubbed_inductor_config_for_logging() self.assertEqual(inductor_config_json, expected) if __name__ == "__main__": from torch._dynamo.test_case import run_tests run_tests()
TestInductorConfigParsingForLogging
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/sourceforge.py
{ "start": 199, "end": 919 }
class ____(PackageBase): sourceforge_mirror_path: Optional[str] = None base_mirrors = [ "https://prdownloads.sourceforge.net/", "https://freefr.dl.sourceforge.net/", "https://netcologne.dl.sourceforge.net/", "https://pilotfiber.dl.sourceforge.net/", "https://downloads.sourceforge.net/", "http://kent.dl.sourceforge.net/sourceforge/", ] @property def urls(self): if self.sourceforge_mirror_path is None: raise AttributeError(f"{self.__class__.__name__}: `sourceforge_mirror_path` missing") return [ join_url(m, self.sourceforge_mirror_path, resolve_href=True) for m in self.base_mirrors ]
SourceforgePackage
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/config_migrations.py
{ "start": 3684, "end": 3815 }
class ____(MigrateStringToArray): migrate_from_key: str = "repository" migrate_to_key: str = "repositories"
MigrateRepository
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 38846, "end": 38989 }
class ____(CPythonOrderedDictTests): module = c_coll class OrderedDict(c_coll.OrderedDict): pass
CPythonOrderedDictSubclassTests
python
huggingface__transformers
src/transformers/models/mamba/modeling_mamba.py
{ "start": 6280, "end": 21609 }
class ____(nn.Module): """ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4, and is why Mamba is called **selective** state spaces) """ def __init__(self, config: MambaConfig, layer_idx: int): super().__init__() self.config = config self.hidden_size = config.hidden_size self.ssm_state_size = config.state_size self.conv_kernel_size = config.conv_kernel self.intermediate_size = config.intermediate_size self.time_step_rank = int(config.time_step_rank) self.layer_idx = layer_idx self.use_conv_bias = config.use_conv_bias self.conv1d = nn.Conv1d( in_channels=self.intermediate_size, out_channels=self.intermediate_size, bias=config.use_conv_bias, kernel_size=config.conv_kernel, groups=self.intermediate_size, padding=config.conv_kernel - 1, ) self.activation = config.hidden_act self.act = ACT2FN[config.hidden_act] self.use_mambapy = config.use_mambapy # projection of the input hidden states self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=config.use_bias) # selective projection used to make dt, B and C input dependent self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False) # time step projection (discretization) self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True) # S4D real initialization. These are not discretized! # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :] A = A.expand(self.intermediate_size, -1).contiguous() self.A_log = nn.Parameter(torch.log(A)) self.D = nn.Parameter(torch.ones(self.intermediate_size)) self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias) self.use_bias = config.use_bias self.warn_slow_implementation() def warn_slow_implementation(self): causal_conv1d = lazy_load_kernel("causal-conv1d") causal_conv1d_update, causal_conv1d_fn = ( (causal_conv1d.causal_conv1d_update, causal_conv1d.causal_conv1d_fn) if causal_conv1d is not None else (None, None) ) is_fast_path_available = all( (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn) ) if not is_fast_path_available: if self.use_mambapy: if is_mambapy_available(): logger.warning_once( "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`" " is None. Falling back to the mamba.py backend. To install follow https://github.com/state-spaces/mamba/#installation for mamba-ssm and" " install the kernels library using `pip install kernels` or https://github.com/Dao-AILab/causal-conv1d for causal-conv1d" ) else: raise ImportError( "use_mambapy is set to True but the mambapy package is not installed. To install it follow https://github.com/alxndrTL/mamba.py." ) else: logger.warning_once( "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`" " is None. Falling back to the sequential implementation of Mamba, as use_mambapy is set to False. To install follow https://github.com/state-spaces/mamba/#installation for mamba-ssm and" " install the kernels library using `pip install kernels` or https://github.com/Dao-AILab/causal-conv1d for causal-conv1d. For the mamba.py backend, follow https://github.com/alxndrTL/mamba.py." ) def cuda_kernels_forward( self, hidden_states: torch.Tensor, cache_params: Optional[MambaCache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, ): # 1. Gated MLP's linear projection projected_states = self.in_proj(hidden_states).transpose(1, 2) if self.training and cache_params is None: # Doesn't support outputting the states -> used for training contextualized_states = mamba_inner_fn( projected_states, self.conv1d.weight, self.conv1d.bias if self.use_conv_bias else None, self.x_proj.weight, self.dt_proj.weight, self.out_proj.weight, self.out_proj.bias.float() if self.use_bias else None, -torch.exp(self.A_log.float()), None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) else: causal_conv1d = lazy_load_kernel("causal-conv1d") causal_conv1d_update, causal_conv1d_fn = ( (causal_conv1d.causal_conv1d_update, causal_conv1d.causal_conv1d_fn) if causal_conv1d is not None else (None, None) ) hidden_states, gate = projected_states.chunk(2, dim=1) if attention_mask is not None: hidden_states = hidden_states * attention_mask.unsqueeze(1) # 2. Convolution sequence transformation conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2)) if cache_params is not None and cache_position[0] > 0: hidden_states = causal_conv1d_update( hidden_states.squeeze(-1), cache_params.conv_states[self.layer_idx], conv_weights, self.conv1d.bias, self.activation, ) hidden_states = hidden_states.unsqueeze(-1) else: if cache_params is not None: conv_states = nn.functional.pad( hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0) ) cache_params.update_conv_state(self.layer_idx, conv_states, cache_position) hidden_states = causal_conv1d_fn( hidden_states, conv_weights, self.conv1d.bias, activation=self.activation ) if attention_mask is not None: hidden_states = hidden_states * attention_mask.unsqueeze(1) # 3. State Space Model sequence transformation # 3.a. input varying initialization of time_step, B and C ssm_parameters = self.x_proj(hidden_states.transpose(1, 2)) time_step, B, C = torch.split( ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1 ) discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2) A = -torch.exp(self.A_log.float()) # 3.c perform the recurrence y ← SSM(A, B, C)(x) time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None if cache_params is not None and cache_position[0] > 0: scan_outputs = selective_state_update( cache_params.ssm_states[self.layer_idx], hidden_states[..., 0], discrete_time_step[..., 0], A, B[:, 0], C[:, 0], self.D, gate[..., 0], time_proj_bias, dt_softplus=True, ).unsqueeze(-1) else: scan_outputs, ssm_state = selective_scan_fn( hidden_states, discrete_time_step, A, B.transpose(1, 2), C.transpose(1, 2), self.D.float(), gate, time_proj_bias, delta_softplus=True, return_last_state=True, ) if ssm_state is not None and cache_params is not None: cache_params.update_ssm_state(self.layer_idx, ssm_state) # 4. Final linear projection contextualized_states = self.out_proj(scan_outputs.transpose(1, 2)) return contextualized_states # fmt: off def slow_forward(self, input_states, cache_params: Optional[MambaCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor] = None): batch_size, seq_len, _ = input_states.shape dtype = input_states.dtype # 1. Gated MLP's linear projection projected_states = self.in_proj(input_states).transpose(1, 2) # [batch, 2 * intermediate_size, seq_len] hidden_states, gate = projected_states.chunk(2, dim=1) if attention_mask is not None: hidden_states = hidden_states * attention_mask.unsqueeze(1) # 2. Convolution sequence transformation if cache_params is not None: ssm_state = cache_params.ssm_states[self.layer_idx].clone() ssm_state = ssm_state.to(hidden_states.device) # use `cache_position.shape[0]` to check whether we are in prefill # stage, it's equivalent to check `cache_position[0] == 0`, which # breaks dynamo fullgraph constraints if cache_position.shape[0] == self.conv_kernel_size: conv_state = nn.functional.pad( hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0) ) cache_params.update_conv_state(self.layer_idx, conv_state, cache_position) hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len] else: conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position) conv_state = conv_state.to(self.conv1d.weight.device) hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1) if self.use_conv_bias: hidden_states += self.conv1d.bias hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1) # [batch, intermediate_size, 1] : decoding else: ssm_state = torch.zeros( (batch_size, self.intermediate_size, self.ssm_state_size), device=hidden_states.device, dtype=dtype ) hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len] if attention_mask is not None: hidden_states = hidden_states * attention_mask.unsqueeze(1) # 3. State Space Model sequence transformation # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2] ssm_parameters = self.x_proj(hidden_states.transpose(1, 2)) time_step, B, C = torch.split( ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1 ) discrete_time_step = self.dt_proj(time_step) # [batch, seq_len, intermediate_size] discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2) # [batch, intermediate_size, seq_len] # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM) A = -torch.exp(self.A_log.float()) # [intermediate_size, ssm_state_size] discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None]) # [batch, intermediate_size, seq_len, ssm_state_size] discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float() # [batch, intermediate_size, seq_len, ssm_state_size] deltaB_u = discrete_B * hidden_states[:, :, :, None].float() # 3.c perform the recurrence y ← SSM(A, B, C)(x) if self.use_mambapy and self.training and cache_params is None: hs = pscan(discrete_A.transpose(1, 2), deltaB_u.transpose(1, 2)) # [batch, seq_len, intermediate_size, ssm_state_size] scan_output = (hs @ C.unsqueeze(-1)).squeeze(3).transpose(1, 2) # [batch, intermediate_size, seq_len] scan_output = scan_output + hidden_states * self.D[None, :, None] scan_output = scan_output * self.act(gate) else: scan_outputs = [] for i in range(seq_len): ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :] # [batch, intermediate_size, ssm_state] scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1)) # [batch, intermediate_size, 1] scan_outputs.append(scan_output[:, :, 0]) scan_output = torch.stack(scan_outputs, dim=-1) # [batch, intermediate_size, seq_len] scan_output = scan_output + (hidden_states * self.D[None, :, None]) scan_output = (scan_output * self.act(gate)) if cache_params is not None: cache_params.ssm_states[self.layer_idx].copy_(ssm_state) # 4. Final linear projection contextualized_states = self.out_proj(scan_output.transpose(1, 2)) # [batch, seq_len, hidden_size] return contextualized_states # fmt: on def forward( self, hidden_states, cache_params: Optional[MambaCache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, ): causal_conv1d = lazy_load_kernel("causal-conv1d") causal_conv1d_update, causal_conv1d_fn = ( (causal_conv1d.causal_conv1d_update, causal_conv1d.causal_conv1d_fn) if causal_conv1d is not None else (None, None) ) is_fast_path_available = all( (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn) ) if is_fast_path_available and "cuda" in self.x_proj.weight.device.type and not is_torchdynamo_compiling(): return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask) return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask)
MambaMixer
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_run.py
{ "start": 3111, "end": 11879 }
class ____: def test_template_fields(self): operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=OVERRIDES ) _assert_common_template_fields(operator.template_fields) assert "job_name" in operator.template_fields assert "overrides" in operator.template_fields assert "polling_period_seconds" in operator.template_fields assert "timeout_seconds" in operator.template_fields @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_success(self, hook_mock): hook_mock.return_value.get_job.return_value = JOB hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 3, 0) operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME ) operator.execute(context=mock.MagicMock()) hook_mock.return_value.get_job.assert_called_once_with( job_name=mock.ANY, region=REGION, project_id=PROJECT_ID ) hook_mock.return_value.execute_job.assert_called_once_with( job_name=JOB_NAME, region=REGION, project_id=PROJECT_ID, overrides=None ) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_fail_one_failed_task(self, hook_mock): hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 2, 1) operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME ) with pytest.raises(AirflowException) as exception: operator.execute(context=mock.MagicMock()) assert "Some tasks failed execution" in str(exception.value) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_fail_all_failed_tasks(self, hook_mock): hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 0, 3) operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME ) with pytest.raises(AirflowException) as exception: operator.execute(context=mock.MagicMock()) assert "Some tasks failed execution" in str(exception.value) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_fail_incomplete_failed_tasks(self, hook_mock): hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 2, 0) operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME ) with pytest.raises(AirflowException) as exception: operator.execute(context=mock.MagicMock()) assert "Not all tasks finished execution" in str(exception.value) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_fail_incomplete_succeeded_tasks(self, hook_mock): hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 0, 2) operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME ) with pytest.raises(AirflowException) as exception: operator.execute(context=mock.MagicMock()) assert "Not all tasks finished execution" in str(exception.value) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_deferrable(self, hook_mock): operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, deferrable=True ) with pytest.raises(TaskDeferred): operator.execute(mock.MagicMock()) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_deferrable_execute_complete_method_timeout(self, hook_mock): operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, deferrable=True ) event = {"status": RunJobStatus.TIMEOUT.value, "job_name": JOB_NAME} with pytest.raises(AirflowException) as e: operator.execute_complete(mock.MagicMock(), event) assert "Operation timed out" in str(e.value) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_deferrable_execute_complete_method_fail(self, hook_mock): operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, deferrable=True ) error_code = 10 error_message = "error message" event = { "status": RunJobStatus.FAIL.value, "operation_error_code": error_code, "operation_error_message": error_message, "job_name": JOB_NAME, } with pytest.raises(AirflowException) as e: operator.execute_complete(mock.MagicMock(), event) assert f"Operation failed with error code [{error_code}] and error message [{error_message}]" in str( e.value ) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_deferrable_execute_complete_method_success(self, hook_mock): hook_mock.return_value.get_job.return_value = JOB operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, deferrable=True ) event = {"status": RunJobStatus.SUCCESS.value, "job_name": JOB_NAME} result = operator.execute_complete(mock.MagicMock(), event) hook_mock.return_value.get_job.assert_called_once_with( job_name=mock.ANY, region=REGION, project_id=PROJECT_ID ) assert result["name"] == JOB_NAME @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_overrides(self, hook_mock): hook_mock.return_value.get_job.return_value = JOB hook_mock.return_value.execute_job.return_value = self._mock_operation(3, 3, 0) overrides = { "container_overrides": [{"args": ["python", "main.py"]}], "task_count": 1, "timeout": "60s", } operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=overrides ) operator.execute(context=mock.MagicMock()) hook_mock.return_value.get_job.assert_called_once_with( job_name=mock.ANY, region=REGION, project_id=PROJECT_ID ) hook_mock.return_value.execute_job.assert_called_once_with( job_name=JOB_NAME, region=REGION, project_id=PROJECT_ID, overrides=overrides ) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_overrides_with_invalid_task_count(self, hook_mock): overrides = { "container_overrides": [{"args": ["python", "main.py"]}], "task_count": -1, "timeout": "60s", } operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=overrides ) with pytest.raises(AirflowException): operator.execute(context=mock.MagicMock()) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_overrides_with_invalid_timeout(self, hook_mock): overrides = { "container_overrides": [{"args": ["python", "main.py"]}], "task_count": 1, "timeout": "60", } operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=overrides ) with pytest.raises(AirflowException): operator.execute(context=mock.MagicMock()) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execute_overrides_with_invalid_container_args(self, hook_mock): overrides = { "container_overrides": [{"name": "job", "args": "python main.py"}], "task_count": 1, "timeout": "60s", } operator = CloudRunExecuteJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=overrides ) with pytest.raises(AirflowException): operator.execute(context=mock.MagicMock()) def _mock_operation(self, task_count, succeeded_count, failed_count): operation = mock.MagicMock() operation.result.return_value = self._mock_execution(task_count, succeeded_count, failed_count) return operation def _mock_execution(self, task_count, succeeded_count, failed_count): execution = mock.MagicMock() execution.task_count = task_count execution.succeeded_count = succeeded_count execution.failed_count = failed_count return execution
TestCloudRunExecuteJobOperator
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py
{ "start": 10119, "end": 11255 }
class ____(Benchmark): r""" Hosaki objective function. This class defines the Hosaki [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Hosaki}}(x) = \left ( 1 - 8 x_1 + 7 x_1^2 - \frac{7}{3} x_1^3 + \frac{1}{4} x_1^4 \right ) x_2^2 e^{-x_1} with :math:`x_i \in [0, 10]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = -2.3458115` for :math:`x = [4, 2]`. .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = ([0., 5.], [0., 6.]) self.custom_bounds = [(0, 5), (0, 5)] self.global_optimum = [[4, 2]] self.fglob = -2.3458115 def fun(self, x, *args): self.nfev += 1 val = (1 - 8 * x[0] + 7 * x[0] ** 2 - 7 / 3. * x[0] ** 3 + 0.25 * x[0] ** 4) return val * x[1] ** 2 * exp(-x[1])
Hosaki
python
bokeh__bokeh
src/bokeh/document/callbacks.py
{ "start": 2686, "end": 17040 }
class ____: ''' Manage and provide access to all of the models that belong to a Bokeh Document. The set of "all models" means specifically all the models reachable from references form a Document's roots. ''' _document: weakref.ReferenceType[Document] _change_callbacks: dict[Any, DocumentChangeCallback] _event_callbacks: dict[str, list[EventCallback]] _js_event_callbacks: dict[str, list[JSEventCallback]] _message_callbacks: dict[str, list[MessageCallback]] _session_destroyed_callbacks: set[SessionDestroyedCallback] _session_callbacks: set[SessionCallback] _subscribed_models: dict[str, set[weakref.ReferenceType[Model]]] _hold: HoldPolicyType | None = None _held_events: list[DocumentChangedEvent] def __init__(self, document: Document): ''' Args: document (Document): A Document to manage models for A weak reference to the Document will be retained ''' self._document = weakref.ref(document) self._change_callbacks = {} self._event_callbacks = defaultdict(list) self._js_event_callbacks = defaultdict(list) self._message_callbacks = defaultdict(list) self._session_destroyed_callbacks = set() self._session_callbacks = set() self._subscribed_models = defaultdict(set) self._hold = None self._held_events = [] self.on_message("bokeh_event", self.trigger_event) @property def session_callbacks(self) -> list[SessionCallback]: ''' A list of all the session callbacks for this document. ''' return list(self._session_callbacks) @property def session_destroyed_callbacks(self) -> set[SessionDestroyedCallback]: ''' A list of all the on_session_destroyed callbacks for this document. ''' return self._session_destroyed_callbacks @session_destroyed_callbacks.setter def session_destroyed_callbacks(self, callbacks: set[SessionDestroyedCallback]) -> None: self._session_destroyed_callbacks = callbacks def add_session_callback(self, callback_obj: SessionCallback, callback: Callback, one_shot: bool) -> SessionCallback: ''' Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added ''' doc = self._document() if doc is None: raise RuntimeError("Attempting to add session callback to already-destroyed Document") actual_callback: Callback if one_shot: @wraps(callback) def remove_then_invoke() -> None: if callback_obj in self._session_callbacks: self.remove_session_callback(callback_obj) return callback() actual_callback = remove_then_invoke else: actual_callback = callback callback_obj._callback = _wrap_with_curdoc(doc, actual_callback) self._session_callbacks.add(callback_obj) # emit event so the session is notified of the new callback self.trigger_on_change(SessionCallbackAdded(doc, callback_obj)) return callback_obj def destroy(self) -> None: ''' Clean up references to the Documents models ''' self._change_callbacks.clear() del self._change_callbacks self._event_callbacks.clear() del self._event_callbacks self._js_event_callbacks.clear() del self._js_event_callbacks self._message_callbacks.clear() del self._message_callbacks def hold(self, policy: HoldPolicyType = "combine") -> None: if self._hold is not None and self._hold != policy: log.warning(f"hold already active with '{self._hold}', ignoring '{policy}'") return if policy not in HoldPolicy: raise ValueError(f"Unknown hold policy {policy}") self._hold = policy @property def hold_value(self) -> HoldPolicyType | None: return self._hold def notify_change(self, model: Model, attr: str, old: Any, new: Any, hint: DocumentPatchedEvent | None = None, setter: Setter | None = None, callback_invoker: Invoker | None = None) -> None: ''' Called by Model when it changes ''' doc = self._document() if doc is None: return # if name changes, need to update by-name index if attr == 'name': doc.models.update_name(model, old, new) event: DocumentPatchedEvent if hint is None: new = model.lookup(attr).get_value(model) event = ModelChangedEvent(doc, model, attr, new, setter, callback_invoker) else: assert hint.callback_invoker is None hint.callback_invoker = callback_invoker if hint.setter is None: hint.setter = setter event = hint self.trigger_on_change(event) def notify_event(self, model: Model, event: ModelEvent, callback_invoker: Invoker) -> None: ''' ''' doc = self._document() if doc is None: return # TODO (bev): use internal event here to dispatch, rather than hard-coding invocation here invoke_with_curdoc(doc, callback_invoker) def on_change(self, *callbacks: DocumentChangeCallback) -> None: ''' Provide callbacks to invoke if the document or any Model reachable from its roots changes. ''' for callback in callbacks: if callback in self._change_callbacks: continue _check_callback(callback, ('event',)) self._change_callbacks[callback] = callback def on_change_dispatch_to(self, receiver: Any) -> None: if receiver not in self._change_callbacks: self._change_callbacks[receiver] = lambda event: event.dispatch(receiver) def on_event(self, event: str | type[Event], *callbacks: EventCallback) -> None: ''' Provide callbacks to invoke if a bokeh event is received. ''' self._on_event(event, *callbacks) def js_on_event(self, event: str | type[Event], *callbacks: JSEventCallback) -> None: ''' Provide JS callbacks to invoke if a bokeh event is received. ''' self._on_event(event, *callbacks) def _on_event(self, event: str | type[Event], *callbacks: EventCallback | JSEventCallback) -> None: if not isinstance(event, str) and issubclass(event, Event): event = event.event_name if event not in _CONCRETE_EVENT_CLASSES: raise ValueError(f"Unknown event {event}") if not issubclass(_CONCRETE_EVENT_CLASSES[event], DocumentEvent): raise ValueError("Document.on_event may only be used to subscribe " "to events of type DocumentEvent. To subscribe " "to a ModelEvent use the Model.on_event method.") for callback in callbacks: if isinstance(callback, JSEventCallback): self._js_event_callbacks[event].append(callback) else: _check_callback(callback, ('event',), what='Event callback') self._event_callbacks[event].append(callback) def on_message(self, msg_type: str, *callbacks: MessageCallback) -> None: self._message_callbacks[msg_type].extend(callbacks) def on_session_destroyed(self, *callbacks: SessionDestroyedCallback) -> None: ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback) def remove_on_change(self, *callbacks: Any) -> None: ''' Remove a callback added earlier with ``on_change``. Raises: KeyError, if the callback was never added ''' for callback in callbacks: del self._change_callbacks[callback] def remove_on_message(self, msg_type: str, callback: MessageCallback) -> None: ''' ''' message_callbacks = self._message_callbacks.get(msg_type, None) if message_callbacks is not None and callback in message_callbacks: message_callbacks.remove(callback) def remove_session_callback(self, callback_obj: SessionCallback) -> None: ''' Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added ''' try: callback_objs = [callback_obj] self._session_callbacks.remove(callback_obj) except KeyError: raise ValueError("callback already ran or was already removed, cannot be removed again") doc = self._document() if doc is None: return # emit event so the session is notified and can remove the callback for callback_obj in callback_objs: self.trigger_on_change(SessionCallbackRemoved(doc, callback_obj)) def subscribe(self, key: str, model: Model) -> None: self._subscribed_models[key].add(weakref.ref(model)) def event_callbacks_for_event_name(self, event_name: str) -> tuple[EventCallback, ...]: ''' Return a tuple containing all current event callbacks for the given event name. Args: event_name (str) : the event name to look up callbacks for ''' return tuple(self._event_callbacks.get(event_name, [])) def change_callbacks(self) -> tuple[DocumentChangeCallback, ...]: ''' Return a tuple containing all current change callbacks. ''' return tuple(self._change_callbacks.values()) def send_event(self, event: Event) -> None: ''' Send a bokeh/model/UI event to the client. ''' document = self._document() if document is not None: self.trigger_on_change(MessageSentEvent(document, "bokeh_event", event)) def trigger_event(self, event: Event) -> None: # This is fairly gorpy, we are not being careful with model vs doc events, etc. if isinstance(event, ModelEvent): subscribed = self._subscribed_models[event.event_name].copy() for model_ref in subscribed: model = model_ref() if model: model._trigger_event(event) for cb in self.event_callbacks_for_event_name(event.event_name): cb(event) def trigger_on_change(self, event: DocumentChangedEvent) -> None: doc = self._document() if doc is None: return if self._hold == "collect": self._held_events.append(event) return elif self._hold == "combine": _combine_document_events(event, self._held_events) return if event.callback_invoker is not None: invoke_with_curdoc(doc, event.callback_invoker) def invoke_callbacks() -> None: for cb in self.change_callbacks(): cb(event) invoke_with_curdoc(doc, invoke_callbacks) def unhold(self) -> None: ''' Turn off any active document hold and apply any collected events. Returns: None ''' # no-op if we are already no holding if self._hold is None: return self._hold = None events = list(self._held_events) self._held_events = [] for event in events: self.trigger_on_change(event) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- def invoke_with_curdoc(doc: Document, f: Callable[[], None]) -> None: from ..io.doc import patch_curdoc curdoc: Document|UnlockedDocumentProxy = UnlockedDocumentProxy(doc) if getattr(f, "nolock", False) else doc with patch_curdoc(curdoc): return f() #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- def _combine_document_events(new_event: DocumentChangedEvent, old_events: list[DocumentChangedEvent]) -> None: ''' Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, the function will return immediately. Otherwise, ``new_event`` will be appended to ``old_events``. Args: new_event (DocumentChangedEvent) : The new event to attempt to combine old_events (list[DocumentChangedEvent]) A list of previous events to attempt to combine new_event with **This is an "out" parameter**. The values it contains will be modified in-place. Returns: None ''' for event in reversed(old_events): if event.combine(new_event): return # no combination was possible old_events.append(new_event) def _wrap_with_curdoc(doc: Document, f: Callable[..., Any]) -> Callable[..., Any]: @wraps(f) def wrapper(*args: Any, **kwargs: Any) -> None: @wraps(f) def invoke() -> Any: return f(*args, **kwargs) return invoke_with_curdoc(doc, invoke) return wrapper #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
DocumentCallbackManager
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 289584, "end": 289945 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("EnterpriseAdministratorInvitation", graphql_name="node")
EnterpriseAdministratorInvitationEdge
python
django__django
django/core/serializers/xml_serializer.py
{ "start": 17645, "end": 18171 }
class ____(DefusedXmlException): """Entity definition is forbidden.""" def __init__(self, name, value, base, sysid, pubid, notation_name): super().__init__() self.name = name self.value = value self.base = base self.sysid = sysid self.pubid = pubid self.notation_name = notation_name def __str__(self): tpl = "EntitiesForbidden(name='{}', system_id={!r}, public_id={!r})" return tpl.format(self.name, self.sysid, self.pubid)
EntitiesForbidden
python
numba__numba
numba/core/typed_passes.py
{ "start": 7034, "end": 7176 }
class ____(BaseTypeInference): _name = "nopython_type_inference" @register_pass(mutates_CFG=True, analysis_only=False)
NopythonTypeInference
python
kamyu104__LeetCode-Solutions
Python/find-smallest-common-element-in-all-rows.py
{ "start": 491, "end": 895 }
class ____(object): def smallestCommonElement(self, mat): """ :type mat: List[List[int]] :rtype: int """ # assumed value is unique in each row counter = collections.Counter() for row in mat: for c in row: counter[c] += 1 if counter[c] == len(mat): return c return -1
Solution2
python
huggingface__transformers
tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py
{ "start": 18951, "end": 101497 }
class ____(unittest.TestCase): def _get_dummy_input_ids(self): # fmt: off ids = torch.tensor( [[685, 560, 630, 193, 836, 764, 708, 360, 10, 724, 278, 755, 805, 600, 71, 473, 601, 397, 315, 706, 487, 552, 88, 175, 601, 850, 678, 538, 846, 73, 778, 917, 116, 977, 756, 710, 1023, 848, 432, 449, 851, 100, 985, 178, 756, 798, 660, 148, 911, 424, 289, 962, 266, 698, 640, 545, 544, 715, 245, 152, 676, 511, 460, 883, 184, 29, 803, 129, 129, 933, 54, 902, 551, 489, 757, 274, 336, 389, 618, 43, 443, 544, 889, 258, 322, 1000, 938, 58, 292, 871, 120, 780, 431, 83, 92, 897, 399, 612, 566, 909, 634, 939, 85, 204, 325, 775, 965, 48, 640, 1013, 132, 973, 869, 181, 1001, 847, 144, 661, 228, 955, 792, 720, 910, 374, 854, 561, 306, 582, 170, 676, 449, 96, 198, 607, 257, 882, 691, 293, 931, 817, 862, 388, 611, 555, 974, 369, 1000, 918, 202, 384, 513, 907, 371, 556, 955, 384, 24, 700, 131, 378, 99, 575, 932, 735, 124, 964, 595, 943, 740, 149, 210, 563, 412, 783, 42, 59, 706, 37, 779, 87, 44, 873, 12, 771, 308, 81, 33, 183, 129, 807, 276, 175, 555, 372, 185, 445, 489, 590, 287, 281, 638, 771, 516, 95, 227, 876, 270, 881, 297, 329, 20, 608, 841, 411, 451, 249, 181, 324, 1005, 830, 783, 865, 261, 964, 750, 140, 1021, 599, 462, 890, 622, 844, 697, 529, 153, 926, 150, 111, 26, 465, 957, 890, 887, 118, 446, 596, 674, 873, 929, 229, 508, 764, 122, 327, 470, 288, 526, 840, 697, 153, 592, 42, 275, 553, 439, 208, 780, 167, 112, 350, 1018, 130, 736, 887, 813, 217, 382, 25, 68, 979, 1008, 772, 235, 717, 999, 292, 727, 1023, 702, 710, 728, 556, 33, 12, 617, 213, 139, 695, 1004, 422, 638, 669, 624, 489, 771, 540, 980, 218, 664, 822, 308, 175, 149, 950, 542, 580, 548, 808, 394, 74, 298, 920, 900, 815, 731, 947, 877, 772, 800, 778, 395, 540, 430, 200, 424, 62, 342, 866, 45, 803, 931, 89, 34, 646, 233, 768, 37, 769, 460, 291, 198, 895, 950, 255, 81, 447, 137, 190, 130, 210, 369, 292, 377, 348, 169, 885, 805, 177, 538, 324, 872, 509, 804, 115, 799, 30, 754, 290, 147, 274, 222, 341, 510, 515, 70, 358, 909, 557, 886, 766, 323, 624, 92, 342, 424, 552, 972, 663, 415, 658, 711, 968, 275, 861, 44, 84, 434, 810, 94, 175, 406, 202, 858, 499, 481, 988, 330, 541, 1004, 210, 618, 955, 897, 983, 576, 17, 107, 165, 607, 537, 629, 192, 196, 308, 137, 953, 860, 94, 892, 751, 88, 161, 148, 585, 456, 88, 14, 315, 594, 121, 885, 952, 833, 716, 733, 933, 282, 801, 427, 783, 471, 285, 277, 979, 325, 535, 228, 891, 596, 648, 969, 574, 654, 518, 257, 137, 208, 464, 950, 140, 5, 424, 349, 942, 283, 587, 821, 1007, 434, 220, 820, 740, 874, 787, 374, 291, 564, 671, 438, 827, 940, 824, 509, 1021, 787, 942, 856, 450, 327, 491, 54, 817, 95, 60, 337, 667, 637, 164, 571, 946, 107, 202, 301, 782, 890, 839, 551, 680, 649, 14, 1017, 904, 721, 1017, 535, 505, 848, 986, 777, 740, 775, 210, 456, 469, 474, 963, 573, 401, 57, 883, 750, 664, 281, 5, 613, 1005, 306, 344, 543, 567, 154, 789, 354, 358, 698, 408, 412, 30, 930, 372, 822, 632, 948, 855, 503, 8, 618, 1010, 138, 695, 897, 852, 377, 933, 722, 149, 886, 1009, 260, 127, 811, 578, 533, 805, 325, 977, 113, 944, 651, 238, 361, 991, 860, 556, 64, 928, 917, 455, 266, 445, 604, 624, 420, 340, 845, 275, 370, 843, 227, 226, 940, 644, 909, 229, 827, 898, 370, 129, 808, 25, 699, 293, 356, 838, 135, 4, 227, 890, 681, 445, 418, 285, 837, 27, 737, 249, 366, 948, 202, 438, 198, 930, 648, 638, 607, 73, 247, 853, 136, 708, 214, 476, 621, 324, 103, 853, 328, 596, 224, 257, 646, 348, 108, 927, 970, 980, 520, 150, 998, 477, 393, 684, 559, 1, 361, 692, 551, 90, 75, 500, 739, 636, 344, 97, 852, 283, 719, 33, 116, 455, 866, 429, 828, 826, 691, 174, 746, 133, 442, 94, 348, 402, 420, 707, 405, 942, 186, 976, 376, 677, 874, 703, 517, 498, 499, 206, 415, 366, 856, 739, 420, 586, 219, 952, 539, 375, 23, 461, 720, 355, 603, 52, 999, 815, 721, 574, 445, 816, 1019, 105, 641, 395, 972, 910, 328, 607, 519, 686, 246, 415, 528, 170, 167, 310, 940, 595, 392, 221, 834, 682, 835, 115, 861, 335, 742, 220, 247, 101, 416, 222, 179, 509, 175, 606, 627, 674, 781, 737, 746, 849, 67, 457, 1012, 126, 139, 625, 731, 156, 697, 121, 322, 449, 710, 857, 291, 976, 4, 701, 239, 678, 172, 724, 857, 583, 661, 903, 797, 628, 903, 835, 605, 989, 615, 870, 380, 710, 110, 330, 101, 695, 846, 918, 508, 672, 594, 36, 238, 244, 251, 393, 767, 282, 22, 430, 230, 983, 401, 154, 1007, 120, 678, 896, 386, 390, 711, 397, 347, 587, 1020, 951, 79, 831, 585, 200, 814, 134, 560, 700, 171, 452, 139, 755, 314, 476, 346, 388, 126, 719, 851, 198, 699, 901, 18, 710, 448, 351, 665, 644, 326, 425, 165, 571, 178, 440, 665, 674, 915, 866, 463, 754, 136, 950, 748, 47, 497, 1013, 640, 930, 338, 158, 525, 631, 815, 887, 289, 803, 116, 600, 637, 410, 175, 499, 876, 565, 1002, 623, 577, 333, 887, 586, 147, 773, 776, 644, 49, 77, 294, 117, 494, 561, 110, 979, 180, 562, 72, 859, 434, 1007, 286, 516, 75, 597, 491, 322, 888, 533, 209, 43, 499, 29, 411, 856, 181, 305, 963, 615, 778, 259, 373, 877, 746, 858, 381, 886, 613, 91, 69, 618, 523, 13, 617, 226, 422, 168, 929, 379, 290, 923, 100, 218, 307, 345, 211, 789, 735, 669, 585, 275, 410, 921, 552, 235, 636, 285, 665, 659, 708, 173, 724, 302, 823, 1, 139, 708, 903, 732, 868, 442, 967, 916, 163, 51, 243, 871]], # noqa: E231 dtype=torch.long, device=torch_device, ) # fmt: on return ids def _get_dummy_target_ids(self): # fmt: off ids = torch.tensor( [[13, 6, 1, 4, 12, 4, 8, 10, 4, 6, 3, 5, 8, 7, 9, 9]], # noqa: E231 dtype=torch.long, device=torch_device, ) # fmt: on return ids def test_inference_block_sparse(self): model = BigBirdPegasusForConditionalGeneration.from_pretrained( MODEL_ID, attention_type="block_sparse", block_size=16, num_random_blocks=3 ) model.to(torch_device) input_ids = self._get_dummy_input_ids() target_ids = self._get_dummy_target_ids() outputs = model(input_ids, labels=target_ids) prediction_logits = outputs.logits self.assertEqual(prediction_logits.shape, torch.Size((1, 16, 96103))) # fmt: off expected_prediction_logits_slice = torch.tensor( [[1.5118, 5.5227, 4.8125, 1.7603, 8.1704, 3.996, 4.8118, 6.7806, 2.2297, 6.9834, 3.1906, 0.103, 7.1515, 6.3679, 3.1896, 6.3054, 3.9741, 6.3772, 5.0042, -0.6338, 6.7868, 0.592, 0.5363, 1.87, -0.331, -2.4518, 1.8263, 3.1899], [1.5702, 5.8135, 4.6675, 2.3674, 8.9828, 3.7913, 5.4027, 7.6567, 1.9007, 7.3706, 3.8824, 0.0247, 7.6094, 6.6985, 3.2826, 7.0094, 3.8713, 5.6555, 5.0439, -0.3519, 7.1525, 0.4062, -0.2419, 2.2194, -0.6447, -2.9614, 2.0713, 3.248], [1.4527, 5.6003, 4.5381, 2.6382, 9.2809, 3.2969, 5.6811, 8.4011, 1.6909, 7.4937, 4.3185, -0.0878, 7.61, 6.6822, 3.4753, 7.3962, 3.5336, 4.9216, 4.943, -0.2043, 7.3326, 0.2199, -0.6016, 2.4367, -0.7043, -3.0689, 2.3215, 3.0611], [1.1084, 5.6308, 4.4886, 2.717, 9.4103, 3.0733, 5.5825, 8.4325, 1.3075, 7.5495, 4.4782, -0.1092, 7.8115, 6.6285, 3.5311, 7.6853, 3.509, 4.4994, 4.9224, -0.1384, 7.3069, -0.0473, -0.8578, 2.4632, -0.5249, -3.4627, 2.2671, 2.8818]], # noqa: E231 device=torch_device, ) # fmt: on torch.testing.assert_close( prediction_logits[0, 4:8, 128:156], expected_prediction_logits_slice, rtol=1e-4, atol=1e-4 ) def test_inference_full_attn(self): model = BigBirdPegasusForConditionalGeneration.from_pretrained(MODEL_ID, attention_type="original_full") model.to(torch_device) input_ids = self._get_dummy_input_ids() target_ids = self._get_dummy_target_ids() outputs = model(input_ids, labels=target_ids) prediction_logits = outputs.logits self.assertEqual(prediction_logits.shape, torch.Size((1, 16, 96103))) # fmt: off expected_prediction_logits_slice = torch.tensor( [[1.3418, 5.8304, 6.5662, 2.0448, 8.7702, 4.6579, 4.9947, 6.429, 2.4296, 7.9431, 4.217, 0.0672, 7.334, 5.1966, 2.9603, 6.0814, 4.6756, 7.5522, 5.076, 0.213, 6.6638, 0.6577, 0.244, 2.1221, 0.7531, -2.4076, 1.8731, 3.5594], [1.5525, 6.0524, 6.309, 2.6245, 9.229, 4.5213, 5.0913, 7.0622, 1.7992, 8.0962, 4.7994, -0.0248, 7.7168, 5.5878, 3.0883, 6.5248, 4.7895, 6.9974, 4.8787, 0.5445, 6.6686, 0.0102, -0.1659, 2.6195, 0.7389, -2.8956, 1.9928, 3.3777], [1.6407, 6.2104, 6.0331, 2.8076, 9.4074, 3.9772, 5.0574, 7.5316, 1.4201, 8.3035, 5.0212, -0.1031, 7.553, 5.5023, 3.1427, 6.7674, 4.4409, 6.457, 4.525, 0.728, 6.5422, -0.6234, -0.4726, 2.7486, 0.6985, -3.0804, 1.9669, 3.2365], [1.5065, 6.1271, 5.8296, 2.8405, 9.5649, 3.6834, 5.1214, 7.546, 0.9758, 8.3335, 5.1952, -0.1395, 7.4348, 5.6893, 3.2942, 7.0356, 4.1665, 5.9695, 4.3898, 0.8931, 6.3988, -0.8957, -0.7522, 2.8924, 0.6498, -3.4358, 1.8654, 2.9735]], # noqa: E231 device=torch_device, ) # fmt: on torch.testing.assert_close( prediction_logits[0, 4:8, 128:156], expected_prediction_logits_slice, rtol=1e-4, atol=1e-4 ) def test_seq_to_seq_generation(self): MODEL_ID = "google/bigbird-pegasus-large-arxiv" model = BigBirdPegasusForConditionalGeneration.from_pretrained(MODEL_ID).to(torch_device) tokenizer = PegasusTokenizer.from_pretrained(MODEL_ID) ARTICLE_LEP = r"""the lep experiments at the resonance of @xmath1-boson have tested the standard model ( sm ) at quantum level , measuring the @xmath1-decay into fermion pairs with an accuracy of one part in ten thousands . the good agreement of the lep data with the sm predictions have severely constrained the behavior of new physics at the @xmath1-pole . taking these achievements into account one can imagine that the physics of @xmath1-boson will again play the central role in the frontier of particle physics if the next generation @xmath1 factory comes true with the generated @xmath1 events several orders of magnitude higher than that of the lep . this factory can be realized in the gigaz option of the international linear collider ( ilc)@xcite . the ilc is a proposed electron - positron collider with tunable energy ranging from @xmath12 to @xmath13 and polarized beams in its first phase , and the gigaz option corresponds to its operation on top of the resonance of @xmath1 boson by adding a bypass to its main beam line . given the high luminosity , @xmath14 , and the cross section at the resonance of @xmath1 boson , @xmath15 , about @xmath16 @xmath1 events can be generated in an operational year of @xmath17 of gigaz , which implies that the expected sensitivity to the branching ratio of @xmath1-decay can be improved from @xmath18 at the lep to @xmath19 at the gigaz@xcite . in light of this , the @xmath1-boson properties , especially its exotic or rare decays which are widely believed to be sensitive to new physics , should be investigated comprehensively to evaluate their potential in probing new physics . among the rare @xmath1-decays , the flavor changing ( fc ) processes were most extensively studied to explore the flavor texture in new physics @xcite , and it was found that , although these processes are severely suppressed in the sm , their branching ratios in new physics models can be greatly enhanced to @xmath19 for lepton flavor violation decays @xcite and @xmath20 for quark flavor violation decays @xcite . besides the fc processes , the @xmath1-decay into light higgs boson(s ) is another type of rare process that was widely studied , e.g. the decay @xmath21 ( @xmath22 ) with the particle @xmath0 denoting a light higgs boson was studied in @xcite , the decay @xmath23 was studied in the two higgs doublet model ( 2hdm)@xcite and the minimal supersymmetric standard model ( mssm)@xcite , and the decay @xmath4 was studied in a model independent way @xcite , in 2hdm@xcite and also in mssm@xcite . these studies indicate that , in contrast with the kinematic forbidden of these decays in the sm , the rates of these decays can be as large as @xmath18 in new physics models , which lie within the expected sensitivity of the gigaz . in this work , we extend the previous studies of these decays to some new models and investigate these decays altogether . we are motivated by some recent studies on the singlet extension of the mssm , such as the next - to - minimal supersymmetric standard model ( nmssm ) @xcite and the nearly minimal supersymmetric standard model ( nmssm ) @xcite , where a light cp - odd higgs boson @xmath0 with singlet - dominant component may naturally arise from the spontaneous breaking of some approximate global symmetry like @xmath24 or peccei - quuin symmetry @xcite . these non - minimal supersymmetric models can not only avoid the @xmath25-problem , but also alleviate the little hierarchy by having such a light higgs boson @xmath0 @xcite . we are also motivated by that , with the latest experiments , the properties of the light higgs boson are more stringently constrained than before . so it is worth updating the previous studies . so far there is no model - independent lower bound on the lightest higgs boson mass . in the sm , it must be heavier than @xmath26 gev , obtained from the null observation of the higgs boson at lep experiments . however , due to the more complex structure of the higgs sector in the extensions of the sm , this lower bound can be significantly relaxed according to recent studies , e.g. , for the cp - odd higgs boson @xmath0 we have @xmath27 gev in the nmssm @xcite , @xmath28 gev in the nmssm @xcite , and @xmath29 gev in the lepton - specific 2hdm ( l2hdm ) @xcite . with such a light cp - odd higgs boson , the z - decay into one or more @xmath0 is open up . noting that the decay @xmath30 is forbidden due to bose symmetry , we in this work study the rare @xmath1-decays @xmath6 ( @xmath22 ) , @xmath31 and @xmath4 in a comparative way for four models , namely the type - ii 2hdm@xcite , the l2hdm @xcite , the nmssm and the nmssm . in our study , we examine carefully the constraints on the light @xmath0 from many latest experimental results . this work is organized as follows . in sec . ii we briefly describe the four new physics models . in sec . iii we present the calculations of the rare @xmath1-decays . in sec . iv we list the constraints on the four new physics models . in sec . v we show the numerical results for the branching ratios of the rare @xmath1-decays in various models . finally , the conclusion is given in sec . as the most economical way , the sm utilizes one higgs doublet to break the electroweak symmetry . as a result , the sm predicts only one physical higgs boson with its properties totally determined by two free parameters . in new physics models , the higgs sector is usually extended by adding higgs doublets and/or singlets , and consequently , more physical higgs bosons are predicted along with more free parameters involved in . the general 2hdm contains two @xmath32 doublet higgs fields @xmath33 and @xmath34 , and with the assumption of cp - conserving , its scalar potential can be parameterized as@xcite : @xmath35,\end{aligned}\ ] ] where @xmath36 ( @xmath37 ) are free dimensionless parameters , and @xmath38 ( @xmath39 ) are the parameters with mass dimension . after the electroweak symmetry breaking , the spectrum of this higgs sector includes three massless goldstone modes , which become the longitudinal modes of @xmath40 and @xmath1 bosons , and five massive physical states : two cp - even higgs bosons @xmath41 and @xmath42 , one neutral cp - odd higgs particle @xmath0 and a pair of charged higgs bosons @xmath43 . noting the constraint @xmath44 with @xmath45 and @xmath46 denoting the vacuum expectation values ( vev ) of @xmath33 and @xmath34 respectively , we choose @xmath47 as the input parameters with @xmath48 , and @xmath49 being the mixing angle that diagonalizes the mass matrix of the cp - even higgs fields . the difference between the type - ii 2hdm and the l2hdm comes from the yukawa coupling of the higgs bosons to quark / lepton . in the type - ii 2hdm , one higgs doublet @xmath34 generates the masses of up - type quarks and the other doublet @xmath33 generates the masses of down - type quarks and charged leptons ; while in the l2hdm one higgs doublet @xmath33 couples only to leptons and the other doublet @xmath34 couples only to quarks . so the yukawa interactions of @xmath0 to fermions in these two models are given by @xcite @xmath50 with @xmath51 denoting generation index . obviously , in the type - ii 2hdm the @xmath52 coupling and the @xmath53 coupling can be simultaneously enhanced by @xmath54 , while in the l2hdm only the @xmath53 coupling is enhanced by @xmath55 . the structures of the nmssm and the nmssm are described by their superpotentials and corresponding soft - breaking terms , which are given by @xcite @xmath56 where @xmath57 is the superpotential of the mssm without the @xmath25 term , @xmath58 and @xmath59 are higgs doublet and singlet superfields with @xmath60 and @xmath61 being their scalar component respectively , @xmath62 , @xmath63 , @xmath64 , @xmath65 , @xmath66 and @xmath67 are soft breaking parameters , and @xmath68 and @xmath69 are coefficients of the higgs self interactions . with the superpotentials and the soft - breaking terms , one can get the higgs potentials of the nmssm and the nmssm respectively . like the 2hdm , the higgs bosons with same cp property will mix and the mass eigenstates are obtained by diagonalizing the corresponding mass matrices : @xmath70 where the fields on the right hands of the equations are component fields of @xmath71 , @xmath72 and @xmath61 defined by @xmath73 @xmath74 and @xmath75 are respectively the cp - even and cp - odd neutral higgs bosons , @xmath76 and @xmath77 are goldstone bosons eaten by @xmath1 and @xmath78 , and @xmath79 is the charged higgs boson . so both the nmssm and nmssm predict three cp - even higgs bosons , two cp - odd higgs bosons and one pair of charged higgs bosons . in general , the lighter cp - odd higgs @xmath0 in these model is the mixture of the singlet field @xmath80 and the doublet field combination , @xmath81 , i.e. @xmath82 and its couplings to down - type quarks are then proportional to @xmath83 . so for singlet dominated @xmath0 , @xmath84 is small and the couplings are suppressed . as a comparison , the interactions of @xmath0 with the squarks are given by@xcite @xmath85 i.e. the interaction does not vanish when @xmath86 approaches zero . just like the 2hdm where we use the vevs of the higgs fields as fundamental parameters , we choose @xmath68 , @xmath69 , @xmath87 , @xmath88 , @xmath66 and @xmath89 as input parameters for the nmssm@xcite and @xmath68 , @xmath54 , @xmath88 , @xmath65 , @xmath90 and @xmath91 as input parameters for the nmssm@xcite . about the nmssm and the nmssm , three points should be noted . the first is for the two models , there is no explicit @xmath92term , and the effective @xmath25 parameter ( @xmath93 ) is generated when the scalar component of @xmath59 develops a vev . the second is , the nmssm is actually same as the nmssm with @xmath94@xcite , because the tadpole terms @xmath95 and its soft breaking term @xmath96 in the nmssm do not induce any interactions , except for the tree - level higgs boson masses and the minimization conditions . and the last is despite of the similarities , the nmssm has its own peculiarity , which comes from its neutralino sector . in the basis @xmath97 , its neutralino mass matrix is given by @xcite @xmath98 where @xmath99 and @xmath100 are @xmath101 and @xmath102 gaugino masses respectively , @xmath103 , @xmath104 , @xmath105 and @xmath106 . after diagonalizing this matrix one can get the mass eigenstate of the lightest neutralino @xmath107 with mass taking the following form @xcite @xmath108 this expression implies that @xmath107 must be lighter than about @xmath109 gev for @xmath110 ( from lower bound on chargnio mass ) and @xmath111 ( perturbativity bound ) . like the other supersymmetric models , @xmath107 as the lightest sparticle acts as the dark matter in the universe , but due to its singlino - dominated nature , it is difficult to annihilate sufficiently to get the correct density in the current universe . so the relic density of @xmath107 plays a crucial way in selecting the model parameters . for example , as shown in @xcite , for @xmath112 , there is no way to get the correct relic density , and for the other cases , @xmath107 mainly annihilates by exchanging @xmath1 boson for @xmath113 , or by exchanging a light cp - odd higgs boson @xmath0 with mass satisfying the relation @xmath114 for @xmath115 . for the annihilation , @xmath54 and @xmath25 are required to be less than 10 and @xmath116 respectively because through eq.([mass - exp ] ) a large @xmath87 or @xmath25 will suppress @xmath117 to make the annihilation more difficult . the properties of the lightest cp - odd higgs boson @xmath0 , such as its mass and couplings , are also limited tightly since @xmath0 plays an important role in @xmath107 annihilation . the phenomenology of the nmssm is also rather special , and this was discussed in detail in @xcite . in the type - ii 2hdm , l2hdm , nmssm and nmssm , the rare @xmath1-decays @xmath118 ( @xmath22 ) , @xmath3 and @xmath4 may proceed by the feynman diagrams shown in fig.[fig1 ] , fig.[fig2 ] and fig.[fig3 ] respectively . for these diagrams , the intermediate state @xmath119 represents all possible cp - even higgs bosons in the corresponding model , i.e. @xmath41 and @xmath42 in type - ii 2hdm and l2hdm and @xmath41 , @xmath42 and @xmath120 in nmssm and nmssm . in order to take into account the possible resonance effects of @xmath119 in fig.[fig1](c ) for @xmath2 and fig.[fig3 ] ( a ) for @xmath11 , we have calculated all the decay modes of @xmath119 and properly included the width effect in its propagator . as to the decay @xmath121 , two points should be noted . one is , unlike the decays @xmath6 and @xmath11 , this process proceeds only through loops mediated by quarks / leptons in the type - ii 2hdm and l2hdm , and additionally by sparticles in the nmssm and nmssm . so in most cases its rate should be much smaller than the other two . the other is due to cp - invariance , loops mediated by squarks / sleptons give no contribution to the decay@xcite . in actual calculation , this is reflected by the fact that the coupling coefficient of @xmath122 differs from that of @xmath123 by a minus sign ( see eq.([asqsq ] ) ) , and as a result , the squark - mediated contributions to @xmath121 are completely canceled out . with regard to the rare decay @xmath11 , we have more explanations . in the lowest order , this decay proceeds by the diagram shown in fig.[fig3 ] ( a ) , and hence one may think that , as a rough estimate , it is enough to only consider the contributions from fig.[fig3](a ) . however , we note that in some cases of the type - ii 2hdm and l2hdm , due to the cancelation of the contributions from different @xmath119 in fig.[fig3 ] ( a ) and also due to the potentially largeness of @xmath124 couplings ( i.e. larger than the electroweak scale @xmath125 ) , the radiative correction from the higgs - mediated loops may dominate over the tree level contribution even when the tree level prediction of the rate , @xmath126 , exceeds @xmath20 . on the other hand , we find the contribution from quark / lepton - mediated loops can be safely neglected if @xmath127 in the type - ii 2hdm and the l2hdm . in the nmssm and the nmssm , besides the corrections from the higgs- and quark / lepton - mediated loops , loops involving sparticles such as squarks , charginos and neutralinos can also contribute to the decay . we numerically checked that the contributions from squarks and charginos can be safely neglected if @xmath127 . we also calculated part of potentially large neutralino correction ( note that there are totally about @xmath128 diagrams for such correction ! ) and found they can be neglected too . since considering all the radiative corrections will make our numerical calculation rather slow , we only include the most important correction , namely that from higgs - mediated loops , in presenting our results for the four models . one can intuitively understand the relative smallness of the sparticle contribution to @xmath11 as follows . first consider the squark contribution which is induced by the @xmath129 interaction ( @xmath130 denotes the squark in chirality state ) and the @xmath131 interaction through box diagrams . because the @xmath132 interaction conserves the chirality of the squarks while the @xmath133 interaction violates the chirality , to get non - zero contribution to @xmath11 from the squark loops , at least four chiral flippings are needed , with three of them provided by @xmath131 interaction and the rest provided by the left - right squark mixing . this means that , if one calculates the amplitude in the chirality basis with the mass insertion method , the amplitude is suppressed by the mixing factor @xmath134 with @xmath135 being the off diagonal element in squark mass matrix . next consider the chargino / neutralino contributions . since for a light @xmath0 , its doublet component , parameterized by @xmath84 in eq.([mixing ] ) , is usually small , the couplings of @xmath0 with the sparticles will never be tremendously large@xcite . so the chargino / neutralino contributions are not important too . in our calculation of the decays , we work in the mass eigenstates of sparticles instead of in the chirality basis . for the type - ii 2hdm and the l2hdm , we consider the following constraints @xcite : * theoretical constraints on @xmath136 from perturbativity , unitarity and requirements that the scalar potential is finit at large field values and contains no flat directions @xcite , which imply that @xmath137 * the constraints from the lep search for neutral higgs bosons . we compute the signals from the higgs - strahlung production @xmath138 ( @xmath139 ) with @xmath140 @xcite and from the associated production @xmath141 with @xmath142 @xcite , and compare them with the corresponding lep data which have been inputted into our code . we also consider the constraints from @xmath138 by looking for a peak of @xmath143 recoil mass distribution of @xmath1-boson @xcite and the constraint of @xmath144 mev when @xmath145 @xcite . + these constraints limit the quantities such as @xmath146 \times br ( h_i \to \bar{b } b ) $ ] on the @xmath147 plane with the the subscript @xmath148 denoting the coupling coefficient of the @xmath149 interaction . they also impose a model - dependent lower bound on @xmath150 , e.g. , @xmath151 for the type - ii 2hdm ( from our scan results ) , @xmath152 for the l2hdm@xcite , and @xmath153 for the nmssm @xcite . these bounds are significantly lower than that of the sm , i.e. @xmath154 , partially because in new physics models , unconventional decay modes of @xmath155 such as @xmath156 are open up . as to the nmssm , another specific reason for allowing a significantly lighter cp - even higgs boson is that the boson may be singlet - dominated in this model . + with regard to the lightest cp - odd higgs boson @xmath0 , we checked that there is no lower bound on its mass so long as the @xmath157 interaction is weak or @xmath155 is sufficiently heavy . * the constraints from the lep search for a light higgs boson via the yukawa process @xmath158 with @xmath22 and @xmath61 denoting a scalar @xcite . these constraints can limit the @xmath159 coupling versus @xmath160 in new physics models . * the constraints from the cleo - iii limit on @xmath161 and the latest babar limits on @xmath162 . these constraints will put very tight constraints on the @xmath163 coupling for @xmath164 . in our analysis , we use the results of fig.8 in the second paper of @xcite to excluded the unfavored points . * the constraints from @xmath165 couplings . since the higgs sector can give sizable higher order corrections to @xmath165 couplings , we calculate them to one loop level and require the corrected @xmath165 couplings to lie within the @xmath166 range of their fitted value . the sm predictions for the couplings at @xmath1-pole are given by @xmath167 and @xmath168 @xcite , and the fitted values are given by @xmath169 and @xmath170 , respectively@xcite . we adopt the formula in @xcite to the 2hdm in our calculation . * the constraints from @xmath171 leptonic decay . we require the new physics correction to the branching ratio @xmath172 to be in the range of @xmath173 @xcite . we use the formula in @xcite in our calculation . + about the constraints ( 5 ) and ( 6 ) , two points should be noted . one is all higgs bosons are involved in the constraints by entering the self energy of @xmath171 lepton , the @xmath174 vertex correction or the @xmath175 vertex correction , and also the box diagrams for @xmath176@xcite . since the yukawa couplings of the higgs bosons to @xmath171 lepton get enhanced by @xmath54 and so do the corrections , @xmath54 must be upper bounded for given spectrum of the higgs sector . generally speaking , the lighter @xmath0 is , the more tightly @xmath54 is limited@xcite . the other point is in the type - ii 2hdm , @xmath177 , b - physics observables as well as @xmath178 decays discussed above can constraint the model in a tighter way than the constraints ( 5 ) and ( 6 ) since the yukawa couplings of @xmath171 lepton and @xmath179 quark are simultaneously enhanced by @xmath54 . but for the l2hdm , because only the yukawa couplings of @xmath171 lepton get enhanced ( see eq.[yukawa ] ) , the constraints ( 5 ) and ( 6 ) are more important in limiting @xmath54 . * indirect constraints from the precision electroweak observables such as @xmath180 , @xmath181 and @xmath182 , or their combinations @xmath183 @xcite . we require @xmath184 to be compatible with the lep / sld data at @xmath185 confidence level@xcite . we also require new physics prediction of @xmath186 is within the @xmath187 range of its experimental value . the latest results for @xmath188 are @xmath189 ( measured value ) and @xmath190 ( sm prediction ) for @xmath191 gev @xcite . in our code , we adopt the formula for these observables presented in @xcite to the type - ii 2hdm and the l2hdm respectively . + in calculating @xmath180 , @xmath181 and @xmath182 , we note that these observables get dominant contributions from the self energies of the gauge bosons @xmath1 , @xmath192 and @xmath193 . since there is no @xmath194 coupling or @xmath195 coupling , @xmath0 must be associated with the other higgs bosons to contribute to the self energies . so by the uv convergence of these quantities , one can infer that , for the case of a light @xmath0 and @xmath196 , these quantities depend on the spectrum of the higgs sector in a way like @xmath197 at leading order , which implies that a light @xmath0 can still survive the constraints from the precision electroweak observables given the splitting between @xmath150 and @xmath198 is moderate@xcite . * the constraints from b physics observables such as the branching ratios for @xmath199 , @xmath200 and @xmath201 , and the mass differences @xmath202 and @xmath203 . we require their theoretical predications to agree with the corresponding experimental values at @xmath187 level . + in the type - ii 2hdm and the l2hdm , only the charged higgs boson contributes to these observables by loops , so one can expect that @xmath198 versus @xmath54 is to be limited . combined analysis of the limits in the type - ii 2hdm has been done by the ckmfitter group , and the lower bound of @xmath204 as a function of @xmath87 was given in fig.11 of @xcite . this analysis indicates that @xmath198 must be heavier than @xmath205 at @xmath185 c.l . regardless the value of @xmath54 . in this work , we use the results of fig.11 in @xcite to exclude the unfavored points . as for the l2hdm , b physics actually can not put any constraints@xcite because in this model the couplings of the charged higgs boson to quarks are proportional to @xmath206 and in the case of large @xmath54 which we are interested in , they are suppressed . in our analysis of the l2hdm , we impose the lep bound on @xmath198 , i.e. @xmath207@xcite . * the constraints from the muon anomalous magnetic moment @xmath208 . now both the theoretical prediction and the experimental measured value of @xmath208 have reached a remarkable precision , but a significant deviation still exists : @xmath209 @xcite . in the 2hdm , @xmath208 gets additional contributions from the one - loop diagrams induced by the higgs bosons and also from the two - loop barr - zee diagrams mediated by @xmath0 and @xmath155@xcite . if the higgs bosons are much heavier than @xmath25 lepton mass , the contributions from the barr - zee diagrams are more important , and to efficiently alleviate the discrepancy of @xmath208 , one needs a light @xmath0 along with its enhanced couplings to @xmath25 lepton and also to heavy fermions such as bottom quark and @xmath171 lepton to push up the effects of the barr - zee diagram@xcite . the cp - even higgs bosons are usually preferred to be heavy since their contributions to @xmath208 are negative . + in the type - ii 2hdm , because @xmath54 is tightly constrained by the process @xmath210 at the lep@xcite and the @xmath178 decay@xcite , the barr - zee diagram contribution is insufficient to enhance @xmath208 to @xmath187 range around its measured value@xcite . so in our analysis , we require the type - ii 2hdm to explain @xmath208 at @xmath211 level . while for the l2hdm , @xmath54 is less constrained compared with the type - ii 2hdm , and the barr - zee diagram involving the @xmath171-loop is capable to push up greatly the theoretical prediction of @xmath208@xcite . therefore , we require the l2hdm to explain the discrepancy at @xmath187 level . + unlike the other constraints discussed above , the @xmath208 constraint will put a two - sided bound on @xmath54 since on the one hand , it needs a large @xmath54 to enhance the barr - zee contribution , but on the other hand , too large @xmath54 will result in an unacceptable large @xmath208 . * since this paper concentrates on a light @xmath0 , the decay @xmath212 is open up with a possible large decay width . we require the width of any higgs boson to be smaller than its mass to avoid a too fat higgs boson@xcite . we checked that for the scenario characterized by @xmath213 , the coefficient of @xmath214 interaction is usually larger than the electroweak scale @xmath125 , and consequently a large decay width is resulted . for the nmssm and nmssm , the above constraints become more complicated because in these models , not only more higgs bosons are involved in , but also sparticles enter the constraints . so it is not easy to understand some of the constraints intuitively . take the process @xmath199 as an example . in the supersymmetric models , besides the charged higgs contribution , chargino loops , gluino loops as well as neutralino loops also contribute to the process@xcite , and depending on the susy parameters , any of these contributions may become dominated over or be canceled by other contributions . as a result , although the charged higgs affects the process in the same way as that in the type - ii 2hdm , charged higgs as light as @xmath215 is still allowed even for @xmath216@xcite . since among the constraints , @xmath208 is rather peculiar in that it needs new physics to explain the discrepancy between @xmath217 and @xmath218 , we discuss more about its dependence on susy parameters . in the nmssm and the nmssm , @xmath208 receives contributions from higgs loops and neutralino / chargino loops . for the higgs contribution , it is quite similar to that of the type - ii 2hdm except that more higgs bosons are involved in@xcite . for the neutralino / chargino contribution , in the light bino limit ( i.e. @xmath219 ) , it can be approximated by@xcite @xmath220 for @xmath221 with @xmath222 being smuon mass . so combining the two contributions together , one can learn that a light @xmath0 along with large @xmath54 and/or light smuon with moderate @xmath87 are favored to dilute the discrepancy . because more parameters are involved in the constraints on the supersymmetric models , we consider following additional constraints to further limit their parameters : * direct bounds on sparticle masses from the lep1 , the lep2 and the tevatron experiments @xcite . * the lep1 bound on invisible z decay @xmath223 ; the lep2 bound on neutralino production @xmath224 and @xmath225@xcite . * dark matter constraints from the wmap relic density 0.0975 @xmath226 0.1213 @xcite . note that among the above constraints , the constraint ( 2 ) on higgs sector and the constraint ( c ) on neutralino sector are very important . this is because in the supersymmetric models , the sm - like higgs is upper bounded by about @xmath227 at tree level and by about @xmath228 at loop level , and that the relic density restricts the lsp annihilation cross section in a certain narrow range . in our analysis of the nmssm , we calculate the constraints ( 3 ) and ( 5 - 7 ) by ourselves and utilize the code nmssmtools @xcite to implement the rest constraints . we also extend nmssmtools to the nmssm to implement the constraints . for the extension , the most difficult thing we faced is how to adapt the code micromegas@xcite to the nmssm case . we solve this problem by noting the following facts : * as we mentioned before , the nmssm is actually same as the nmssm with the trilinear singlet term setting to zero . so we can utilize the model file of the nmssm as the input of the micromegas and set @xmath229 . * since in the nmssm , the lsp is too light to annihilate into higgs pairs , there is no need to reconstruct the effective higgs potential to calculate precisely the annihilation channel @xmath230 with @xmath61 denoting any of higgs bosons@xcite . we thank the authors of the nmssmtools for helpful discussion on this issue when we finish such extension@xcite . with the above constraints , we perform four independent random scans over the parameter space of the type - ii 2hdm , the l2hdm , the nmssm and the nmssm respectively . we vary the parameters in following ranges : @xmath231 for the type - ii 2hdm , @xmath232 for the l2hdm , @xmath233 for the nmssm , and @xmath234 for the nmssm . in performing the scans , we note that for the nmssm and the nmssm , some constraints also rely on the gaugino masses and the soft breaking parameters in the squark sector and the slepton sector . since these parameters affect little on the properties of @xmath0 , we fix them to reduce the number of free parameters in our scan . for the squark sector , we adopt the @xmath235 scenario which assumes that the soft mass parameters for the third generation squarks are degenerate : @xmath236 800 gev , and that the trilinear couplings of the third generation squarks are also degenerate , @xmath237 with @xmath238 . for the slepton sector , we assume all the soft - breaking masses and trilinear parameters to be 100 gev . this setting is necessary for the nmssm since this model is difficult to explain the muon anomalous moment at @xmath239 level for heavy sleptons@xcite . finally , we assume the grand unification relation @xmath240 for the gaugino masses with @xmath241 being fine structure constants of the different gauge group . with large number of random points in the scans , we finally get about @xmath242 , @xmath243 , @xmath244 and @xmath242 samples for the type - ii 2hdm , the l2hdm , the nmssm and the nmssm respectively which survive the constraints and satisfy @xmath245 . analyzing the properties of the @xmath0 indicates that for most of the surviving points in the nmssm and the nmssm , its dominant component is the singlet field ( numerically speaking , @xmath246 ) so that its couplings to the sm fermions are suppressed@xcite . our analysis also indicates that the main decay products of @xmath0 are @xmath247 for the l2hdm@xcite , @xmath248 ( dominant ) and @xmath247 ( subdominant ) for the type - ii 2hdm , the nmssm and the nmssm , and in some rare cases , neutralino pairs in the nmssm@xcite . in fig.[fig4 ] , we project the surviving samples on the @xmath249 plane . this figure shows that the allowed range of @xmath54 is from @xmath250 to @xmath251 in the type - ii 2hdm , and from @xmath252 to @xmath253 in the l2hdm . just as we introduced before , the lower bounds of @xmath254 come from the fact that we require the models to explain the muon anomalous moment , while the upper bound is due to we have imposed the constraint from the lep process @xmath255 , which have limited the upper reach of the @xmath256 coupling for light @xmath61 @xcite(for the dependence of @xmath256 coupling on @xmath54 , see sec . this figure also indicates that for the nmssm and the nmssm , @xmath54 is upper bounded by @xmath257 . for the nmssm , this is because large @xmath87 can suppress the dark matter mass to make its annihilation difficult ( see @xcite and also sec . ii ) , but for the nmssm , this is because we choose a light slepton mass so that large @xmath54 can enhance @xmath208 too significantly to be experimentally unacceptable . we checked that for the slepton mass as heavy as @xmath258 , @xmath259 is still allowed for the nmssm . in fig.[fig5 ] and fig.[fig6 ] , we show the branching ratios of @xmath260 and @xmath261 respectively . fig.[fig5 ] indicates , among the four models , the type - ii 2hdm predicts the largest ratio for @xmath260 with its value varying from @xmath262 to @xmath263 . the underlying reason is in the type - ii 2hdm , the @xmath264 coupling is enhanced by @xmath54 ( see fig.[fig4 ] ) , while in the other three model , the coupling is suppressed either by @xmath265 or by the singlet component of the @xmath0 . fig.[fig6 ] shows that the l2hdm predicts the largest rate for @xmath266 with its value reaching @xmath5 in optimum case , and for the other three models , the ratio of @xmath261 is at least about one order smaller than that of @xmath267 . this feature can be easily understood from the @xmath268 coupling introduced in sect . we emphasize that , if the nature prefers a light @xmath0 , @xmath260 and/or @xmath269 in the type - ii 2hdm and the l2hdm will be observable at the gigaz . then by the rates of the two decays , one can determine whether the type - ii 2hdm or the l2hdm is the right theory . on the other hand , if both decays are observed with small rates or fail to be observed , the singlet extensions of the mssm are favored . in fig.[fig7 ] , we show the rate of @xmath3 as the function of @xmath270 . this figure indicates that the branching ratio of @xmath121 can reach @xmath271 , @xmath272 , @xmath273 and @xmath274 for the optimal cases of the type - ii 2hdm , the l2hdm , the nmssm and the nmssm respectively , which implies that the decay @xmath121 will never be observable at the gigaz if the studied model is chosen by nature . the reason for the smallness is , as we pointed out before , that the decay @xmath121 proceeds only at loop level . comparing the optimum cases of the type - ii 2hdm , the nmssm and the nmssm shown in fig.5 - 7 , one may find that the relation @xmath275 holds for any of the decays . this is because the decays are all induced by the yukawa couplings with similar structure for the models . in the supersymmetric models , the large singlet component of the light @xmath0 is to suppress the yukawa couplings , and the @xmath0 in the nmssm has more singlet component than that in the nmssm . next we consider the decay @xmath11 , which , unlike the above decays , depends on the higgs self interactions . in fig.[fig8 ] we plot its rate as a function of @xmath270 and this figure indicates that the @xmath276 may be the largest among the ratios of the exotic @xmath1 decays , reaching @xmath277 in the optimum cases of the type - ii 2hdm , the l2hdm and the nmssm . the underlying reason is , in some cases , the intermediate state @xmath119 in fig.[fig3 ] ( a ) may be on - shell . in fact , we find this is one of the main differences between the nmssm and the nmssm , that is , in the nmssm , @xmath119 in fig.[fig3 ] ( a ) may be on - shell ( corresponds to the points with large @xmath278 ) while in the nmssm , this seems impossible . so we conclude that the decay @xmath11 may serve as an alternative channel to test new physics models , especially it may be used to distinguish the nmssm from the nmssm if the supersymmetry is found at the lhc and the @xmath11 is observed at the gigaz with large rate . before we end our discussion , we note that in the nmssm , the higgs boson @xmath0 may be lighter than @xmath279 without conflicting with low energy data from @xmath178 decays and the other observables ( see fig.[fig4]-[fig8 ] ) . in this case , @xmath0 is axion - like as pointed out in @xcite . we checked that , among the rare @xmath1 decays discussed in this paper , the largest branching ratio comes from @xmath280 which can reach @xmath281 . since in this case , the decay product of @xmath0 is highly collinear muon pair , detecting the decay @xmath280 may need some knowledge about detectors , which is beyond our discussion . in this paper , we studied the rare @xmath1-decays @xmath2 ( @xmath7 ) , @xmath282 and @xmath4 in the type - ii 2hdm , lepton - specific 2hdm , nmssm and nmssm , which predict a light cp - odd higgs boson @xmath0 . in the parameter space allowed by current experiments , the branching ratio can be as large as @xmath5 for @xmath118 , @xmath8 for @xmath3 and @xmath9 for @xmath4 , which implies that the decays @xmath2 and @xmath283 may be accessible at the gigaz option . since different models predict different size of branching ratios , these decays can be used to distinguish different model through the measurement of these rare decays . this work was supported in part by hastit under grant no . 2009hastit004 , by the national natural science foundation of china ( nnsfc ) under grant nos . 10821504 , 10725526 , 10635030 , 10775039 , 11075045 and by the project of knowledge innovation program ( pkip ) of chinese academy of sciences under grant no . . for some reviews , see , e.g. , m. a. perez , g. tavares - velasco and j. j. toscano , int . j. mod . a * 19 * , 159 ( 2004 ) ; j. m. yang , arxiv:1006.2594 . j. i. illana , m. masip , 67 , 035004 ( 2003 ) ; j. cao , z. xiong , j. m. yang , 32 , 245 ( 2004 ) . d. atwood _ et al_. , 66 , 093005 ( 2002 ) . j. kalinowski , and s. pokorski , 219 , 116 ( 1989 ) ; a. djouadi , p. m. zerwas and j. zunft , 259 , 175 ( 1991 ) ; a. djouadi , j. kalinowski , and p. m. zerwas , z. phys . c * 54 * , 255 ( 1992 ) . m. krawczyk , _ et al . _ , 19 , 463 ( 2001 ) ; 8 , 495 ( 1999 ) . j. f. gunion , g. gamberini and s. f. novaes , 38 , 3481 ( 1988 ) ; thomas j. weiler and tzu - chiang yuan , 318 , 337 ( 1989 ) ; a. djouadi , _ et al . _ , 1 , 163 ( 1998)[hep - ph/9701342 ] . d. chang and w. y. keung , phys . lett . * 77 * , 3732 ( 1996 ) . e. keith and e. ma , 57 , 2017 ( 1998 ) ; m. a. perez , g. tavares - velasco and j. j. toscano , int . j. mod.phys . a * 19 * , 159 ( 2004 ) . f. larios , g. tavares - velasco and c. p. yuan , 64 , 055004 ( 2001 ) ; 66 , 075006 ( 2002 ) . a. djouadi , _ et al . _ , 10 , 27 ( 1999 ) [ hep - ph/9903229 ] . for a detailed introduction of the nmssm , see f. franke and h. fraas , int . j. mod . a * 12 * ( 1997 ) 479 ; for a recent review of the nmssm , see for example , u. ellwanger , c. hugonie , and a. m. teixeira , arxiv : 0910.1785 . see , e.g. , j. r. ellis , j. f. gunion , h. e. haber , l. roszkowski and f. zwirner , phys . rev . d * 39 * ( 1989 ) 844 ; m. drees , int . j. mod . phys . a * 4 * ( 1989 ) 3635 ; u. ellwanger , m. rausch de traubenberg and c. a. savoy , phys . b * 315 * ( 1993 ) 331 ; nucl . b * 492 * ( 1997 ) 21 ; d.j . miller , r. nevzorov , p.m. zerwas , 681 , 3 ( 2004 ) . c. panagiotakopoulos , k. tamvakis , 446 , 224 ( 1999 ) ; 469 , 145 ( 1999 ) ; c. panagiotakopoulos , a. pilaftsis , 63 , 055003 ( 2001 ) ; a. dedes , _ et al . _ , 63 , 055009 ( 2001 ) ; a. menon , _ et al . _ , 70 , 035005 ( 2004 ) ; v. barger , _ et al . _ , 630 , 85 ( 2005 ) . c. balazs , _ et al . _ , 0706 , 066 ( 2007 ) . b. a. dobrescu , k. t. matchev , 0009 , 031 ( 2000 ) ; a. arhrib , k. cheung , t. j. hou , k. w. song , hep - ph/0611211 ; 0703 , 073 ( 2007 ) ; x. g. he , j. tandean , and g. valencia , 98 , 081802 ( 2007 ) ; 0806 , 002 ( 2008 ) ; f. domingo _ et al_. , 0901 , 061 ( 2009 ) ; gudrun hiller , 70 , 034018 ( 2004 ) ; r. dermisek , and john f. gunion , 75 , 075019 ( 2007 ) ; 79 , 055014 ( 2009 ) ; 81 , 055001 ( 2010 ) ; r. dermisek , john f. gunion , and b. mcelrath , 76 , 051105 ( 2007 ) ; z. heng , _ et al_. , 77 , 095012 ( 2008 ) ; a. belyaev _ et al_. , 81 , 075021 ( 2010 ) ; d. das and u. ellwanger , arxiv:1007.1151 [ hep - ph ] . s. andreas , o. lebedev , s. ramos - sanchez and a. ringwald , arxiv:1005.3978 [ hep - ph ] . j. f. gunion , jhep * 0908 * , 032 ( 2009 ) ; r. dermisek and j. f. gunion , phys . rev . d * 81 * , 075003 ( 2010 ) . r. dermisek and j. f. gunion , phys . lett . * 95 * , 041801 ( 2005 ) ; phys . d * 73 * , 111701 ( 2006 ) . j. cao , h. e. logan , j. m. yang , 79 , 091701 ( 2009 ) . j. cao , p. wan , l. wu , j. m. yang , 80 , 071701 ( 2009 ) . j. f. gunion and h. e. haber , 67 , 075019 ( 2003 ) . r. m. barnett , _ et al . _ , phys . b * 136 * , 191 ( 1984 ) ; r. m. barnett , g. senjanovic and d. wyler , phys . d * 30 * , 1529 ( 1984 ) ; y. grossman , nucl . b * 426 * , 355 ( 1994 ) . h. s. goh , l. j. hall and p. kumar , jhep * 0905 * , 097 ( 2009 ) ; a. g. akeroyd and w. j. stirling , nucl . b * 447 * , 3 ( 1995 ) ; a. g. akeroyd , phys . b * 377 * , 95 ( 1996 ) ; h. e. logan and d. maclennan , phys . rev . d * 79 * , 115022 ( 2009 ) ; m. aoki , _ et al . _ , arxiv:0902.4665 [ hep - ph ] . v. barger , p. langacker , h. s. lee and g. shaughnessy , phys . d * 73 * , 115010 ( 2006 ) . s. hesselbach , _ et . _ , arxiv:0810.0511v2 [ hep - ph ] . de vivie and p. janot [ aleph collaboration ] , pa13 - 027 contribution to the international conference on high energy physics , warsaw , poland , 2531 july 1996 ; j. kurowska , o. grajek and p. zalewski [ delphi collaboration ] , cern - open-99 - 385 . [ aleph collaboration and delphi collaboration and l3 collaboration ] , phys . rept . * 427 * , 257 ( 2006 ) . j. cao and j. m. yang , jhep * 0812 * , 006 ( 2008 ) . m. krawczyk and d. temes , eur . j. c * 44 * , 435 ( 2005 ) . g. altarelli and r. barbieri , 253 , 161 ( 1991 ) ; m. e. peskin , t. takeuchi , 46 , 381 ( 1992 ) . c. amsler , _ et al . _ , ( particle data group ) , 667 , 1 ( 2008 ) . o. deschamps , s. descotes - genon , s. monteil , v. niess , s. tjampens and v. tisserand , arxiv:0907.5135 [ hep - ph ] . s. su and b. thomas , phys . d * 79 * , 095014 ( 2009 ) . g. abbiendi , _ et al . _ , eur . phys . j. c * 32 * , 453 ( 2004 ) . m. davier , _ et al . _ , 66 , 1 ( 2010 ) . k. cheung , _ et al . _ , phys . d * 64 * , 111301 ( 2001 ) . k. cheung and o. c. w. kong , phys . d * 68 * , 053003 ( 2003 ) . t. besmer , c. greub , t.hurth , 609 , 359 ( 2001 ) ; f. borzumati , _ et al . _ , 62 , 075005(2000 ) . j. cao , k. i. hikasa , w. wang , j. m. yang and l. x. yu , phys . d * 82 * , 051701 ( 2010 ) [ arxiv:1006.4811 [ hep - ph ] ] . j. f. gunion , _ et . d * 73 * , 015011 ( 2006 ) . martin and j. d. wells , phys . d * 64 * , 035003 ( 2001 ) . j. abdallah _ et al . _ , eur . j. c * 31 * , 421 ( 2004 ) ; g. abbiendi _ et al . _ , eur . j. c * 35 * , 1 ( 2004 ) . j. dunkley _ et al . _ [ wmap collaboration ] , astrophys . j. suppl . * 180 * , 306 ( 2009 ) [ arxiv:0803.0586 [ astro - ph ] ] . u. ellwanger _ et al . _ , 02 , 066 ( 2005 ) . g. belanger , f. boudjema , a. pukhov and a. semenov , comput . commun . * 174 * , 577 ( 2006 ) ; comput . phys . commun . * 176 * , 367 ( 2007 ) . g. belanger , f. boudjema , c. hugonie , a. pukhov and a. semenov , jcap * 0509 * , 001 ( 2005 ) .""" ARTICLE_MAGNET = r"""it is well known that the classical magnetoresistance ( mr ) in metals or semiconductors with a closed free electron fermi surface increases quadratically with increasing magnetic field @xmath2 for @xmath3 and saturates when @xmath4 . here @xmath5 is the zero - magnetic - field mobility . hence , the extraordinarily high and linear mr ( lmr ) , which breaks this familiar rule , has been gaining much attention as soon as its discovery . in the past decade , this unexpected lmr has been reported in silver chalcogenide,@xcite indium antimonide,@xcite silicon,@xcite mnas - gaas composite material,@xcite and graphene.@xcite kapitza s linear law@xcite indicates that the metal shows a magnetoresistance linear in perpendicular magnetic field when it has an open fermi surface and a mean free path longer than the electronic larmor radius . recently , another two models , irrespective of the open fermi surface , have been constructed to provide possible mechanisms for the lmr phenomenon . abrikosov suggested a quantum - limit origin of lmr for the homogenous system with a gapless linear energy spectrum.@xcite his model requires that landau levels are well formed and the carrier concentration is small that all electrons occupy only the lowest landau band . alternatively , parish and littlewood developed a classical model without involving linear spectrum.@xcite ignoring the concrete microscopic mechanism , they attributed this unusual mr to the mobility fluctuations in a strongly inhomogenous system . topological insulators@xcite ( tis ) are novel materials with a full energy gap in bulk , while there are gapless surface states . due to its unique band structure with only one helical dirac cone and linear energy dispersion,@xcite the surface states of the ti bi@xmath0se@xmath1 become an excellent platform for the study of quantum - limit lmr . the recent experiment in this flat surface system , however , reported that a large positive mr , which becomes very linear above a characteristic field of @xmath6@xmath7@xmath8 t , was observed even in an opposite situation where the carrier sheet density is high that electrons occupy more than one landau levels.@xcite moreover , they found that raising temperature to room temperature almost has no influence on the observed lmr . it is striking that this observation is in conflict with abrikosov s model and also with the classical parish - littlewood model . so far a reliable theoretical scheme capable of explaining this novel experiment has still been lacking . in this paper , we generalize the balance - equation approach@xcite to a system modeling the surface states of a three - dimensional ti to investigate the two - dimensional magnetotransport in it . we find that a positive , nonsaturating and dominantly linear magnetoresistance can appear within quite wide magnetic - field range in the ti surface state having a positive and finite effective g - factor . this linear magnetoresistance shows up in the system of high carrier concentration and low mobility when electrons are in extended states and spread over many smeared landau levels , and persists up to room temperature , providing a possible mechanism for the recently observed linear magnetoresistance in topological insulator bi@xmath0se@xmath1 nanoribbons.@xcite we consider the surface state of a bi@xmath0se@xmath1-type large bulk gap ti in the @xmath9-@xmath10 plane under the influence of a uniform magnetic field @xmath11 applied along the @xmath12 direction.@xcite following the experimental observation,@xcite we assume that the fermi energy locates in the gap of the bulk band and above the dirac point , i.e. the surface carriers are electrons . further , the separations of the fermi energy from the bottom of bulk band and dirac point are much larger than the highest temperature ( @xmath13 ) considered in this work . hence , the contribution from the bulk band to the magnetotransport is negligible . these electrons , scattered by randomly distributed impurities and by phonons , are driven by a uniform in - plane electric field @xmath14 in the topological surface . the hamiltonian of this many - electron and phonon system consists of an electron part @xmath15 , a phonon part @xmath16 , and electron - impurity and electron - phonon interactions @xmath17 and @xmath18 : @xmath19 here , the electron hamiltonian is taken in the form @xmath20 , \ ] ] in which @xmath21 , @xmath22 , @xmath23 and @xmath24 , stand , respectively , for the canonical momentum , coordinate , momentum and spin operators of the @xmath25th electron having charge @xmath26 , @xmath27 is the vector potential of the perpendicular magnetic field @xmath28 in the landau gauge , @xmath29 is the fermi velocity , @xmath30 is the effective g - factor of the surface electron , and @xmath31 is the bohr magneton with @xmath32 the free electron mass . the sum index @xmath25 in eq.([helectron ] ) goes over all electrons of total number @xmath33 in the surface state of unit area . in the frame work of balance equation approach,@xcite the two - dimensional center - of - mass ( c.m . ) momentum and coordinate @xmath34 and @xmath35 , and the relative - electron momenta and coordinates @xmath36 and @xmath37 are introduced to write the hamiltonian @xmath15 into the sum of a single - particle c.m . part @xmath38 and a many - particle relative - electron part @xmath39 : @xmath40 , with @xmath41.\end{aligned}\ ] ] in this , @xmath42 is the canonical momentum of the center - of - mass and @xmath43 is the canonical momentum for the @xmath25th relative electron . here we have also introduced c.m . spin operators @xmath44 and @xmath45 . the commutation relations between the c.m . spin operators @xmath46 and @xmath47 and the spin operators @xmath48 , @xmath49 and @xmath50 of the @xmath25th electron are of order of @xmath51 : @xmath52= n^{-1}2\,{\rm i}\,\varepsi lon_{\beta_1\beta_2\beta_3}\sigma_j^{\beta_3}$ ] with @xmath53 . therefore , for a macroscopic large @xmath33 system , the c.m . part @xmath38 actually commutes with the relative - electron part @xmath54 in the hamiltonian , i.e. the c.m . motion and the relative motion of electrons are truly separated from each other . the couplings between the two emerge only through the electron impurity and electron phonon interactions . furthermore , the electric field @xmath55 shows up only in @xmath38 . and , in view of @xmath56={\rm i}\delta_{\alpha \beta}(\delta_{ij}-1/n)\simeq { \rm i}\delta_{\alpha\beta}\delta_{ij}$ ] , i.e. the relative - electron momenta and coordinates can be treated as canonical conjugate variables , the relative - motion part @xmath54 is just the hamiltonian of @xmath33 electrons in the surface state of ti in the magnetic field without the presence of the electric field . in terms of the c.m . coordinate @xmath57 and the relative electron density operator @xmath58 , the electron impurity and electron phonon interactions can be written as@xcite @xmath59 here @xmath60 and @xmath61 are respectively the impurity potential ( an impurity at randomly distributed position @xmath62 ) and electron phonon coupling matrix element in the plane - wave representation , and @xmath63 with @xmath64 and @xmath65 being the creation and annihilation operators for a phonon of wavevector @xmath66 in branch @xmath67 having frequency @xmath68 . velocity ( operator ) @xmath69 is the time variation of its coordinate : @xmath70= v_{\rm f}(\sigma_{\rm c}^y\ , \hat{i}-\sigma_{\rm c}^x\ , \hat{j})$ ] . to derive a force - balance equation for steady state transport we consider the heisenberg equation for the rate of change of the c.m . canonical momentum @xmath71 : @xmath72= - n e({\bm v}\times { \bm b})- n e{\bm e}+{\bm { f}}_{\rm i}+{\bm { f}}_{\rm p},\ ] ] in which the frictional forces @xmath73 and @xmath74 share the same expressions as given in ref .. the statistical average of the operator equation can be determined to linear order in the electron impurity and electron phonon interactions @xmath17 and @xmath18 with the initial density matrix @xmath75 at temperature @xmath76 when the in - plane electric field @xmath77 is not strong . for steady - transport states we have @xmath78 , leading to a force - balance equation of the form @xmath79 here @xmath80 , the statistically averaged velocity of the moving center - of - mass , is identified as the average rate of change of its position , i.e. the drift velocity of the electron system driven by the electric field @xmath77 , and @xmath81 and @xmath82 are frictional forces experienced by the center - of - mass due to impurity and phonon scatterings : @xmath83,\label{fp}\end{aligned}\ ] ] in which @xmath84 is the bose distribution function , @xmath85 , and @xmath86 stands for the imaginary part of the fourier spectrum of the relative - electron density correlation function defined by @xmath87\big\rangle_{0},\ ] ] where @xmath88 and @xmath89 denotes the statistical averaging over the initial density matrix @xmath90.@xcite the force - balance equation describes the steady - state two - dimensional magnetotransport in the surface state of a ti . note that the frictional forces @xmath81 and @xmath82 are in the opposite direction of the drift velocity @xmath91 and their magnitudes are functions of @xmath92 only . with the drift velocity @xmath93 in the @xmath9 direction , the force - balance equation eq . yields a transverse resistivity @xmath94 , and a longitudinal resistivity @xmath95 . the linear one is in the form @xmath96 for calculating the electron density correlation function @xmath97 we proceed in the landau representation.@xcite the landau levels of the single - particle hamiltonian @xmath98 of the relative - electron system in the absence of electric field are composed of a positive `` @xmath99 '' and a negative `` @xmath100 '' branch@xcite @xmath101 with @xmath102 and @xmath103 , and a zero ( @xmath104 ) level @xmath105 the corresponding landau wave functions are @xmath106 and @xmath107 for @xmath108 ; and @xmath109 for @xmath104 . here @xmath110 is the wavevector of the system along @xmath9 direction ; @xmath111 with @xmath112 ; and @xmath113 is the harmonic oscillator eigenfunction with @xmath114 being the hermite polynomial , @xmath115 , and @xmath116 . each landau level contains @xmath117 electron states for system of unit surface area . the positive branch @xmath118 and the @xmath104 level @xmath119 of the above energy spectra are indeed quite close to those of the surface states in the bulk gap of bi@xmath0se@xmath1-family materials derived from microscopic band calculation.@xcite the landau levels are broadened due to impurity , phonon and electron - electron scatterings . we model the imaginary part of the retarded green s function , or the density - of - states , of the broadened landau level @xmath120 ( written for `` + ' ' -branch and @xmath104 levels ) , using a gaussian - type form:@xcite @xmath121,\ ] ] with a half - width @xmath122 of the form:@xcite @xmath123^{1/2}$ ] . here @xmath124 is the single - particle lifetime and @xmath125 is the cyclotron frequency of linear - energy - dispersion system with @xmath126 being the zero - temperature fermi level . using a semi - empirical parameter @xmath127 to relate @xmath124 with the transport scattering time @xmath128 , and expressing @xmath129 with the zero - field mobility @xmath5 at finite temperature,@xcite we can write the landau - level broadening as @xmath130^{1/2}.\ ] ] in the present study we consider the case of @xmath120-doping , i.e. the fermi level is high enough above the energy zero of the dirac cone in the range of `` + ' ' -branch levels and the states of `` @xmath100''-branch levels are completely filled , that they are irrelevant to electron transport . special attention has to be paid to the @xmath104 level , since , depending on the direction of exchange potential the effective g - factor of a ti surface state , @xmath30 , can be positive , zero or negative.@xcite the sign and magnitude of the effective g - factor determines how many states of the zero level should be included in or excluded from the available states for electron occupation in the case of @xmath120-doping at a magnetic field . ( i ) if @xmath131 , the @xmath104 level center is exactly at @xmath132 and the system is electron - hole symmetric . the total number of negative energy states ( including the states of the lower half of the @xmath104 level and states of the @xmath100"-branch levels ) and that of positive energy states ( including the states of the upper half of the @xmath104 level and states of the @xmath99"-branch levels ) do not change when changing magnetic field . therefore , the lower - half negative energy states of this level are always filled and the upper - half positive - energy states of it are available for the occupation of particles which are counted as electrons participating in transport in the case of @xmath120-doping . ( ii ) for a finite positive @xmath133 , the @xmath104 level @xmath134 moves downward to negative energy and its distance to the nearest @xmath100"-branch level is @xmath135 closer than to the nearest + " -branch level at finite magnetic field strength @xmath2 . this is equivalent to the opening of an increasingly enlarged ( with increasing @xmath2 ) energy gap between the + " -branch states and the states of the zero - level and the @xmath100"-branch levels . the opening of a sufficient energy gap implies that with increasing magnetic field the states in the + " -branch levels would no longer shrink into the zero - level , and thus the @xmath104 level should be completely excluded from the conduction band , i.e. only particles occupying the + " -branch states are counted as electrons participating in transport in the case of @xmath120-doping , when the magnetic field @xmath2 gets larger than a certain value ( depending on the magnitude of @xmath30 ) . ( iii ) for a finite negative @xmath136 , the @xmath104 level @xmath134 moves upward to positive energy and an increasingly enlarged energy gap will be opened between the states of the zero - level and the + " -branch and the states of @xmath100"-branch levels , and particles occupying the @xmath104 level and + " -branch states are electrons participating in transport when the magnetic field @xmath2 gets larger than a certain value . as a result , the experimentally accessible sheet density @xmath33 of electrons participating in transport is related to the fermi energy @xmath137 by the following equation valid at finite @xmath30 for the magnetic field @xmath2 larger than a certain value : @xmath138 in which @xmath139 + 1\}^{-1}$ ] is the fermi distribution function at temperature @xmath76 and the summation index @xmath120 goes over @xmath140 for @xmath133 , or @xmath141 for @xmath136 . in the case of @xmath131 , @xmath142\ ] ] valid for arbitrary magnetic field , in which @xmath143 . the imaginary part of relative - electron density correlation function in the presence of a magnetic field , @xmath86 , can be expressed in the landau representation as@xcite @xmath144 in which the transform factor @xmath145 ^ 2,\end{aligned}\ ] ] with @xmath146 , @xmath147 , @xmath148 , and @xmath149 being associated laguerre polynomials . the landau - representation correlation function @xmath150 in eq.([piqw ] ) can be constructed with the imaginary part of the retarded green s function @xmath151 , or the density - of - states , of the @xmath120th landau level as@xcite @xmath152\nonumber\\ & \hspace{1.2cm}\times{\rm im}g_n(\epsilon+\omega){\rm im}g_{n'}(\epsilon).\end{aligned}\ ] ] the summation indices @xmath120 and @xmath153 in eq.([piqw ] ) are taken over @xmath140 for @xmath133 , or @xmath154 for @xmath136 . in the case of @xmath131 , eq.([piqw ] ) still works and the summation indices @xmath120 and @xmath153 go over @xmath154 but with @xmath155 replaced by @xmath156 in eq.([p2nn ] ) . numerical calculations are performed for the magnetoresistivity @xmath157 of surface state in a uniform ti bi@xmath0se@xmath1 . at zero temperature the elastic scattering contributing to the resistivity is modeled by a coulomb potential due to charged impurities:@xcite @xmath158 with @xmath159 being the impurity density , which is determined by the zero - magnetic - field mobility @xmath5 . at temperatures higher than @xmath160,@xcite phonon scatterings play increasingly important role and the dominant inelastic contribution comes from optical phonons . for this polar material , the scattering by optical phonons via the deformation potential can be neglected . hence , we take account of inelastic scattering from optical phonons via frhlich coupling : @xmath161 . in the numerical calculation we use the following parameters:@xcite fermi velocity @xmath162 , static dielectric constant @xmath163 , optical dielectric constant @xmath164 , and phonon energy @xmath165 . the broadening parameter is taken to be @xmath166 . as a function of the magnetic field @xmath2 having different effective g - factors : @xmath167 and @xmath168 for a ti surface system with electron sheet density @xmath169 in the cases of zero - magnetic - field mobility @xmath170 ( a ) and @xmath171 ( b ) . several integer - number positions of filling factor @xmath172 are marked in ( b).,scaledwidth=40.0% ] fig.[diffg ] shows the calculated magnetoresistivity @xmath157 versus the magnetic field strength @xmath2 for a ti surface system with electron sheet density @xmath169 but having different effective g - factors : @xmath167 and @xmath168 for two values of zero - magnetic - field mobility @xmath170 and @xmath171 , representing different degree of landau - level broadening . in the case without zeeman splitting ( @xmath131 ) the resistivity @xmath157 exhibits almost no change with changing magnetic field up to 10 t , except the shubnikov - de haas ( sdh ) oscillation showing up in the case of @xmath171 . this kind of magnetoresistance behavior was indeed seen experimentally in the electron - hole symmetrical massless system of single - layer graphene.@xcite in the case of a positive g - factor , @xmath173 , the magnetoresistivity increases linearly with increasing magnetic field ; while for a negative g - factor , @xmath174 , the magnetoresistivity decreases linearly with increasing magnetic field . is shown as a function of the magnetic field @xmath2 for different values of zero - magnetic - field mobility : ( a ) @xmath175 , ( b ) @xmath176 , ( c ) @xmath177 , ( d ) @xmath178 , ( e ) @xmath179 , and ( f ) @xmath180 . the inset of ( a ) illustrates the same for a larger magnetic - field range @xmath181 . the filling factor @xmath182 is plotted versus the magnetic field in ( f ) ; and several integer - number positions of @xmath182 are also marked in ( d ) and ( e ) . here the surface electron density @xmath169 and the lattice temperature @xmath183.,scaledwidth=47.0% ] in the following we will give more detailed examination on the linearly increasing magnetoresistance in the positive @xmath30 case . fig.[rhob ] shows the calculated resistivity @xmath157 versus the magnetic field strength @xmath2 at lattice temperature @xmath183 for system of carrier sheet density @xmath169 and @xmath173 , having different zero - field mobility @xmath184 and @xmath180 . all resistivity curves for mobility @xmath185 exhibit clear linearity in the magnetic - field range and appear no tendency of saturation at the highest field shown in the figure . especially , for the case @xmath170 , the linear behavior extends even up to the magnetic field of @xmath186 , as illustrated in the inset of fig.[rhob](a ) . this feature contradicts the classical mr which saturates at sufficiently large magnetic field @xmath187 . note that here we only present the calculated @xmath157 for magnetic field @xmath2 larger than @xmath188 t , for which a sufficient energy gap @xmath135 is assumed to open that with further increase of the magnetic field the states in the `` + ' ' -branch levels no longer shrink into the zero level and thus it should be excluded from the conduction band . this is of course not true for very weak magnetic field . when @xmath189 the energy gap @xmath190 , the situation becomes similar to the case of @xmath131 : the whole upper half of the zero - level states are available to electron occupation and we should have a flat resistivity @xmath157 when changing magnetic field . with increasing @xmath2 the portion of the zero - level states available to conduction electrons decreases until the magnetic field reaches @xmath191 . as a result the resistivity @xmath157 should exhibit a crossover from a flat changing at small @xmath2 to positively linear increasing at @xmath192 . this is just the behavior observed in the ti bi@xmath0se@xmath1.@xcite note that in the case of @xmath170 , the broadened landau - level widths are always larger than the neighboring level interval : @xmath193 , which requires @xmath194 ^ 2 $ ] , even for the lowest landau level @xmath195 , i.e. the whole landau - level spectrum is smeared . with increasing the zero - field mobility the magnitude of resistivity @xmath157 decreases , and when the broadened landau - level width becomes smaller than the neighboring level interval , @xmath196 , a weak sdh oscillation begin to occur around the linearly - dependent average value of @xmath157 at higher portion of the magnetic field range , as seen in fig.[rhob](c ) , ( d ) and ( e ) for @xmath197 and @xmath198 . on the other hand , in the case of large mobility , e.g. @xmath199 , where the broadened landau - level widths @xmath200 are much smaller than the neighboring level interval even for level index @xmath120 as large as @xmath201 , the magnetoresistivity shows pronounced sdh oscillation and the linear - dependent behavior disappears , before the appearance of quantum hall effect,@xcite as shown in fig.[rhob](f ) . abrikosov s model for the lmr requires the applied magnetic field large enough to reach the quantum limit at which all the carriers are within the lowest landau level,@xcite while it is obvious that more than one landau levels are occupied in the experimental samples in the field range in which the linear and non - saturating magnetoresistivity was observed.@xcite for the given electron surface density @xmath202 , the number of occupied landau levels , or the filling factor @xmath172 , at different magnetic fields is shown in fig.[rhob](f ) , as well as in the fig.[rhob](d ) and ( e ) , where the integer - number positions of @xmath203 , i.e. filling up to entire @xmath182 landau levels , coincide with the minima of the density - of - states or the dips of sdh oscillation . this is in contrast with @xmath131 case , where the integer number of @xmath203 , which implies a filling up to the center position of the @xmath182th landau levels , locates at a peak of sdh oscillation , as shown in fig.[diffg]b . the observed sdh oscillations in the bi@xmath0se@xmath1 nanoribbon exhibiting nonsaturating surface lmr in the experiment@xcite favor the former case : a finite positive effective @xmath133 . is plotted as a function of the surface electron density @xmath33 at magnetic field @xmath204 : ( a ) at different values of zero - field mobility @xmath5 , and ( b ) at different values of zero - field conductivity @xmath205.,scaledwidth=40.0% ] at various lattice temperatures . here the zero - magnetic - field mobility at zero temperature is @xmath206.,scaledwidth=35.0% ] next , we examine the density - dependence of the linear magnetoresistivity . to compare with abrikosov s quantum magnetoresistance which suggests a @xmath207 behavior,@xcite we show the calculated @xmath208 for above lmr versus the carrier sheet density @xmath33 in fig.[rhon ] at fixed magnetic field @xmath209 t . the mobility is taken respectively to be @xmath210 and @xmath211m@xmath212/vs to make the resistivity in the lmr regime . a clearly linear dependence of @xmath213 on the surface density @xmath33 is seen in all cases , indicating that this non - saturating linear resistivity is almost inversely proportional to the carrier density . in the figure we also show @xmath208 versus @xmath33 under the condition of different given conductivity @xmath214 and @xmath215 . in this case the half - width @xmath216 is independent of surface density . the linear dependence still holds , indicating that this linear behavior is not sensitive to the modest @xmath33-dependence of landau level broadening @xmath216 as long as the system is in the overlapped landau level regime . from the above discussion , it is obvious that lmr shows up in the system having overlapped landau levels and the separation of landau levels makes the mr departure from the linear increase . at high temperature , the thermal energy would smear the level separation and phonon scatterings further broaden landau levels . hence , it is believed that this lmr will be robust against raising temperature . this is indeed the case as seen in fig.[rhot ] , where we plot the calculated magnetoresistivity @xmath157 for the above system with zero - temperature linear mobility @xmath217m@xmath212/vs versus the magnetic field at different lattice temperatures . we can see that raising temperature to room temperature has little effect on the linearity of mr . due to the decreased mobility at higher temperature from phonon scattering , the weak sdh oscillation on the linear background tends to vanish . these features are in good agreement with the experimental report.@xcite in summary , we have studied the two - dimensional magnetotransport in the flat surface of a three - dimensional ti , which arises from the surface states with a wavevector - linear energy dispersion and a finite , positive zeeman splitting within the bulk energy gap . when the level broadening is comparable to or larger than the landau - level separation and the conduction electrons spread over many landau levels , a positive , dominantly linear and non - saturating magnetoresistance appears within a quite wide range of magnetic field and persists up to room temperature . this remarkable lmr provides a possible mechanism for the recently observed linear magnetoresistance in topological insulator bi@xmath0se@xmath1 nanoribbons.@xcite in contrast to quantum hall effect which appears in the case of well formed landau levels and to abrikosov s quantum magnetotransport,@xcite which is limited to the extreme quantum limit that all electrons coalesce into the lowest landau level , the discussed lmr is a phenomena of pure classical two - dimensional magnetotransport in a system having linear - energy - dispersion , appearing in the regime of overlapped landau levels , irrespective of its showing up in relatively high magnetic field range . furthermore , the present scheme deals with spatially uniform case without invoking the mobility fluctuation in a strongly inhomogeneous system , which is required in the classical parish and littlewood model to produce a lmr.@xcite the appearance of this significant positive - increasing linear magnetoresistance depends on the existence of a positive and sizable effective g - factor . if the zeeman energy splitting is quite small the resistivity @xmath157 would exhibit little change with changing magnetic field . in the case of a negative and sizable effective g - factor the magnetoresistivity would decrease linearly with increasing magnetic field . therefore , the behavior of the longitudinal resistivity versus magnetic field may provide a useful way for judging the direction and the size of the effective zeeman energy splitting in ti surface states . this work was supported by the national science foundation of china ( grant no . 11104002 ) , the national basic research program of china ( grant no . 2012cb927403 ) and by the program for science&technology innovation talents in universities of henan province ( grant no . 2012hastit029 ) .""" inputs = tokenizer( [ARTICLE_LEP, ARTICLE_MAGNET], max_length=1024, padding="max_length", truncation=True, return_tensors="pt", ) inputs = {k: inputs[k].to(torch_device) for k in inputs} hypotheses_batch = model.generate(**inputs) EXPECTED_LEP = ( "we study the rare decays @xmath0 ( @xmath1 ) at the gigaz option of the international linear collider " "( ilc ).<n> we calculate the branching ratios of @xmath2 in the two higgs doublet model ( 2hdm ), the " "minimal supersymmetric standard model ( mssm ), the next - to - minimal supersymmetric standard model " "( nmssm ) and the nearly minimal supersymmetric standard model ( nmssm ).<n> we find that the branching " "ratios of @xmath3 can reach @xmath4 in 2hdm, @xmath5 in mssm, @xmath6 in nmssm and @xmath7 in nmssm, " "while they are much smaller than @xmath8 in 2hdm, @xmath9 in mssm, @xmath10 in nmssm and @xmath11 in " "nmssm." ) EXPECTED_MAGNET = ( "we investigate the two - dimensional magnetotransport in the surface state of a topological insulator " "( ti ).<n> we find that a positive, nonsaturating and dominantly linear magnetoresistance can appear " "within quite wide magnetic - field range in the ti surface state having a positive and finite effective g " "- factor.<n> this linear magnetoresistance shows up in the system of high carrier concentration and low " "mobility when electrons are in extended states and spread over many smeared landau levels, and persists " "up to room temperature, providing a possible mechanism for the recently observed linear magnetoresistance " "in topological insulator bi@xmath0se@xmath1 nanoribbons." ) generated = tokenizer.batch_decode( hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True ) self.assertTrue(generated == [EXPECTED_LEP, EXPECTED_MAGNET])
BigBirdPegasusModelIntegrationTests
python
Textualize__textual
src/textual/containers.py
{ "start": 4066, "end": 4317 }
class ____(Widget): """An expanding container with vertical layout and no scrollbars.""" DEFAULT_CSS = """ Vertical { width: 1fr; height: 1fr; layout: vertical; overflow: hidden hidden; } """
Vertical
python
pytorch__pytorch
test/test_matmul_cuda.py
{ "start": 42809, "end": 47158 }
class ____(TestCase): @dtypes(torch.float16, torch.bfloat16) def test_mixed_dtypes_linear(self, dtype: torch.dtype, device: str = "cuda"): version = _get_torch_cuda_version() if version < (11, 8): self.skipTest("_mixed_dtypes_linear only compiled for CUDA 11.8+") def run_test( batch_shape, m, n, k, add_bias, activation, dtype, dtypeq, device, rtol, atol, ): if not add_bias and activation != "none": return val_lo, val_hi = -1, 1 valq_lo, valq_hi = -2, 2 input = make_tensor( *batch_shape, m, k, low=val_lo, high=val_hi, dtype=dtype, device=device ) weight = make_tensor( n, k, low=valq_lo, high=valq_hi, dtype=torch.int8, device=device ) scale = make_tensor( (n,), low=val_lo, high=val_hi, dtype=input.dtype, device=device ) bias = ( make_tensor( (n,), low=val_lo, high=val_hi, dtype=input.dtype, device=device ) if add_bias else None ) input_ref = input.reshape(-1, input.shape[-1]) # First, test plain multiplication. weight_ref = weight.T.to(input.dtype) * scale.view(1, n) weightq = ( pack_int4_to_int8(weight.T) if dtypeq == torch.quint4x2 else weight.T ) output_ref = torch.mm(input_ref, weight_ref).reshape(*input.shape[:-1], n) output = torch.ops.aten._mixed_dtypes_linear( input, quantized_weight_reorder_for_mixed_dtypes_linear_cutlass( weightq, dtypeq, transpose=False ), scale, ) torch.testing.assert_close(output, output_ref, rtol=rtol, atol=atol) # Second, test the linear operator itself. weight_ref = weight.to(input.dtype) * scale.view(n, 1) weightq = pack_int4_to_int8(weight) if dtypeq == torch.quint4x2 else weight bias_ref = bias.view(1, n) if add_bias else None output_ref = torch.nn.functional.linear( input_ref, weight_ref, bias=bias_ref ).reshape(*input.shape[:-1], n) if activation == "relu": relu = torch.nn.ReLU() output_ref = relu(output_ref) elif activation == "silu": silu = torch.nn.SiLU() output_ref = silu(output_ref) output = torch.ops.aten._mixed_dtypes_linear( input, quantized_weight_reorder_for_mixed_dtypes_linear_cutlass( weightq, dtypeq, transpose=True ), scale, bias=bias, activation=activation, ) torch.testing.assert_close(output, output_ref, rtol=rtol, atol=atol) dtypeqs = [torch.int8, torch.quint4x2] batch_shapes = [[], [2], [2, 1]] shapes = [ [8, 64, 64], [8, 64, 128], [8, 128, 64], [8, 128, 128], [8, 128, 192], [8, 128, 256], [8, 256, 128], [8, 256, 384], [8, 384, 256], ] activations = [None, "relu", "silu"] rtol, atol = 1e-3, 1e-3 if dtype == torch.bfloat16: rtol, atol = 1e-2, 1e-3 for dtypeq, batch_shape, (m, n, k), add_bias, activation in product( dtypeqs, batch_shapes, shapes, (False, True), activations ): run_test( batch_shape, m, n, k, add_bias, activation, dtype, dtypeq, device, rtol, atol, ) instantiate_device_type_tests(TestMatmulCuda, globals(), except_for="cpu") instantiate_device_type_tests(TestMixedDtypesLinearCuda, globals(), except_for="cpu") if __name__ == '__main__': TestCase._default_dtype_check_enabled = True run_tests()
TestMixedDtypesLinearCuda