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 | Textualize__rich | rich/_windows.py | {
"start": 58,
"end": 1901
} | class ____:
"""Windows features available."""
vt: bool = False
"""The console supports VT codes."""
truecolor: bool = False
"""The console supports truecolor."""
try:
import ctypes
from ctypes import LibraryLoader
if sys.platform == "win32":
windll = LibraryLoader(ctypes.WinDLL)
else:
windll = None
raise ImportError("Not windows")
from rich._win32_console import (
ENABLE_VIRTUAL_TERMINAL_PROCESSING,
GetConsoleMode,
GetStdHandle,
LegacyWindowsError,
)
except (AttributeError, ImportError, ValueError):
# Fallback if we can't load the Windows DLL
def get_windows_console_features() -> WindowsConsoleFeatures:
features = WindowsConsoleFeatures()
return features
else:
def get_windows_console_features() -> WindowsConsoleFeatures:
"""Get windows console features.
Returns:
WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.
"""
handle = GetStdHandle()
try:
console_mode = GetConsoleMode(handle)
success = True
except LegacyWindowsError:
console_mode = 0
success = False
vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
truecolor = False
if vt:
win_version = sys.getwindowsversion()
truecolor = win_version.major > 10 or (
win_version.major == 10 and win_version.build >= 15063
)
features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)
return features
if __name__ == "__main__":
import platform
features = get_windows_console_features()
from rich import print
print(f'platform="{platform.system()}"')
print(repr(features))
| WindowsConsoleFeatures |
python | pyqtgraph__pyqtgraph | pyqtgraph/GraphicsScene/mouseEvents.py | {
"start": 161,
"end": 5629
} | class ____(object):
"""
Instances of this class are delivered to items in a :class:`GraphicsScene <pyqtgraph.GraphicsScene>` via their mouseDragEvent() method when the item is being mouse-dragged.
"""
def __init__(self, moveEvent, pressEvent, lastEvent, start=False, finish=False):
self.start = start
self.finish = finish
self.accepted = False
self.currentItem = None
self._buttonDownScenePos = {}
self._buttonDownScreenPos = {}
for btn in [QtCore.Qt.MouseButton.LeftButton, QtCore.Qt.MouseButton.MiddleButton, QtCore.Qt.MouseButton.RightButton]:
self._buttonDownScenePos[btn] = moveEvent.buttonDownScenePos(btn)
self._buttonDownScreenPos[btn] = moveEvent.buttonDownScreenPos(btn)
self._scenePos = moveEvent.scenePos()
self._screenPos = moveEvent.screenPos()
if lastEvent is None:
self._lastScenePos = pressEvent.scenePos()
self._lastScreenPos = pressEvent.screenPos()
else:
self._lastScenePos = lastEvent.scenePos()
self._lastScreenPos = lastEvent.screenPos()
self._buttons = moveEvent.buttons()
self._button = pressEvent.button()
self._modifiers = moveEvent.modifiers()
self.acceptedItem = None
def accept(self):
"""An item should call this method if it can handle the event. This will prevent the event being delivered to any other items."""
self.accepted = True
self.acceptedItem = self.currentItem
def ignore(self):
"""An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items."""
self.accepted = False
def isAccepted(self):
return self.accepted
def scenePos(self):
"""Return the current scene position of the mouse."""
return Point(self._scenePos)
def screenPos(self):
"""Return the current screen position (pixels relative to widget) of the mouse."""
return Point(self._screenPos)
def buttonDownScenePos(self, btn=None):
"""
Return the scene position of the mouse at the time *btn* was pressed.
If *btn* is omitted, then the button that initiated the drag is assumed.
"""
if btn is None:
btn = self.button()
return Point(self._buttonDownScenePos[btn])
def buttonDownScreenPos(self, btn=None):
"""
Return the screen position (pixels relative to widget) of the mouse at the time *btn* was pressed.
If *btn* is omitted, then the button that initiated the drag is assumed.
"""
if btn is None:
btn = self.button()
return Point(self._buttonDownScreenPos[btn])
def lastScenePos(self):
"""
Return the scene position of the mouse immediately prior to this event.
"""
return Point(self._lastScenePos)
def lastScreenPos(self):
"""
Return the screen position of the mouse immediately prior to this event.
"""
return Point(self._lastScreenPos)
def buttons(self):
"""
Return the buttons currently pressed on the mouse.
(see QGraphicsSceneMouseEvent::buttons in the Qt documentation)
"""
return self._buttons
def button(self):
"""Return the button that initiated the drag (may be different from the buttons currently pressed)
(see QGraphicsSceneMouseEvent::button in the Qt documentation)
"""
return self._button
def pos(self):
"""
Return the current position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._scenePos))
def lastPos(self):
"""
Return the previous position of the mouse in the coordinate system of the item
that the event was delivered to.
"""
return Point(self.currentItem.mapFromScene(self._lastScenePos))
def buttonDownPos(self, btn=None):
"""
Return the position of the mouse at the time the drag was initiated
in the coordinate system of the item that the event was delivered to.
"""
if btn is None:
btn = self.button()
return Point(self.currentItem.mapFromScene(self._buttonDownScenePos[btn]))
def isStart(self):
"""Returns True if this event is the first since a drag was initiated."""
return self.start
def isFinish(self):
"""Returns False if this is the last event in a drag. Note that this
event will have the same position as the previous one."""
return self.finish
def __repr__(self):
if self.currentItem is None:
lp = self._lastScenePos
p = self._scenePos
else:
lp = self.lastPos()
p = self.pos()
return "<MouseDragEvent (%g,%g)->(%g,%g) buttons=%s start=%s finish=%s>" % (lp.x(), lp.y(), p.x(), p.y(), str(self.buttons()), str(self.isStart()), str(self.isFinish()))
def modifiers(self):
"""Return any keyboard modifiers currently pressed.
(see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)
"""
return self._modifiers
| MouseDragEvent |
python | allegroai__clearml | clearml/backend_interface/task/repo/detectors.py | {
"start": 388,
"end": 440
} | class ____(Exception):
pass
@attr.s
| DetectionError |
python | mahmoud__glom | glom/tutorial.py | {
"start": 16340,
"end": 16898
} | class ____:
id = attr.ib(Factory(_contact_autoincrement), init=False)
name = attr.ib('')
pref_name = attr.ib('')
emails = attr.ib(Factory(list))
primary_email = attr.ib(Factory(_default_email, takes_self=True))
company = attr.ib('')
location = attr.ib('')
add_date = attr.ib(Factory(datetime.datetime.now))
# The next two parts are part of the Django-esque Manager pattern,
# mentioned in the ContactManager docstring
objects = ContactManager()
def save(self):
self.objects.save(self)
@attr.s
| Contact |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 24053,
"end": 38484
} | class ____(base_classes.Range):
def __init__(self, sheet, address):
self.sheet = sheet
self.options = None # Assigned by main.Range to keep API of sheet.range clean
if isinstance(address, tuple):
self._coords = address
row, col, nrows, ncols = address
if nrows and ncols:
self.xl = sheet.xl.cells[
"%s:%s"
% (
sheet.xl.rows[row].columns[col].get_address(),
sheet.xl.rows[row + nrows - 1]
.columns[col + ncols - 1]
.get_address(),
)
]
else:
self.xl = None
else:
self.xl = sheet.xl.cells[address]
self._coords = None
@property
def coords(self):
if self._coords is None:
self._coords = (
self.xl.first_row_index.get(),
self.xl.first_column_index.get(),
self.xl.count(each=kw.row),
self.xl.count(each=kw.column),
)
return self._coords
@property
def api(self):
return self.xl
def __len__(self):
return self.coords[2] * self.coords[3]
@property
def row(self):
return self.coords[0]
@property
def column(self):
return self.coords[1]
@property
def shape(self):
return self.coords[2], self.coords[3]
@property
def raw_value(self):
def ensure_2d(values):
# Usually done in converter, but macOS doesn't deliver any info about
# errors with values
if not isinstance(values, list):
return [[values]]
elif not isinstance(values[0], list):
return [values]
if self.xl is not None:
values = self.xl.value.get()
if self.options.get("err_to_str", False):
string_values = self.xl.string_value.get()
values = ensure_2d(values)
string_values = ensure_2d(string_values)
for row_ix, row in enumerate(string_values):
for col_ix, c in enumerate(row):
if c in cell_errors:
values[row_ix][col_ix] = c
return values
@raw_value.setter
def raw_value(self, value):
if self.xl is not None:
self.xl.value.set(value)
def clear_contents(self):
if self.xl is not None:
alerts_state = self.sheet.book.app.screen_updating
self.sheet.book.app.screen_updating = False
self.xl.clear_contents()
self.sheet.book.app.screen_updating = alerts_state
def clear_formats(self):
if self.xl is not None:
alerts_state = self.sheet.book.app.screen_updating
self.sheet.book.app.screen_updating = False
self.xl.clear_formats()
self.sheet.book.app.screen_updating = alerts_state
def clear(self):
if self.xl is not None:
alerts_state = self.sheet.book.app.screen_updating
self.sheet.book.app.screen_updating = False
self.xl.clear_range()
self.sheet.book.app.screen_updating = alerts_state
def end(self, direction):
direction = directions_s2k.get(direction, direction)
return Range(self.sheet, self.xl.get_end(direction=direction).get_address())
@property
def formula(self):
if self.xl is not None:
return self.xl.formula.get()
@formula.setter
def formula(self, value):
if self.xl is not None:
self.xl.formula.set(value)
@property
def formula2(self):
if self.xl is not None:
return self.xl.formula2.get()
@formula2.setter
def formula2(self, value):
if self.xl is not None:
self.xl.formula2.set(value)
@property
def formula_array(self):
if self.xl is not None:
rv = self.xl.formula_array.get()
return None if rv == kw.missing_value else rv
@formula_array.setter
def formula_array(self, value):
if self.xl is not None:
self.xl.formula_array.set(value)
@property
def font(self):
return Font(self, self.xl.font_object)
@property
def column_width(self):
if self.xl is not None:
rv = self.xl.column_width.get()
return None if rv == kw.missing_value else rv
else:
return 0
@column_width.setter
def column_width(self, value):
if self.xl is not None:
self.xl.column_width.set(value)
@property
def row_height(self):
if self.xl is not None:
rv = self.xl.row_height.get()
return None if rv == kw.missing_value else rv
else:
return 0
@row_height.setter
def row_height(self, value):
if self.xl is not None:
self.xl.row_height.set(value)
@property
def width(self):
if self.xl is not None:
return self.xl.width.get()
else:
return 0
@property
def height(self):
if self.xl is not None:
return self.xl.height.get()
else:
return 0
@property
def left(self):
return self.xl.properties().get(kw.left_position)
@property
def top(self):
return self.xl.properties().get(kw.top)
@property
def has_array(self):
if self.xl is not None:
return self.xl.has_array.get()
@property
def number_format(self):
if self.xl is not None:
rv = self.xl.number_format.get()
return None if rv == kw.missing_value else rv
@number_format.setter
def number_format(self, value):
if self.xl is not None:
alerts_state = self.sheet.book.app.screen_updating
self.sheet.book.app.screen_updating = False
self.xl.number_format.set(value)
self.sheet.book.app.screen_updating = alerts_state
def get_address(self, row_absolute, col_absolute, external):
if self.xl is not None:
return self.xl.get_address(
row_absolute=row_absolute,
column_absolute=col_absolute,
external=external,
)
@property
def address(self):
if self.xl is not None:
return self.xl.get_address()
else:
row, col, nrows, ncols = self.coords
return "$%s$%s{%sx%s}" % (col_name(col), row, nrows, ncols)
@property
def current_region(self):
return Range(self.sheet, self.xl.current_region.get_address())
def autofit(self, axis=None):
if self.xl is not None:
address = self.address
alerts_state = self.sheet.book.app.screen_updating
self.sheet.book.app.screen_updating = False
if axis == "rows" or axis == "r":
self.sheet.xl.rows[address].autofit()
elif axis == "columns" or axis == "c":
self.sheet.xl.columns[address].autofit()
elif axis is None:
self.sheet.xl.rows[address].autofit()
self.sheet.xl.columns[address].autofit()
self.sheet.book.app.screen_updating = alerts_state
def insert(self, shift=None, copy_origin=None):
# copy_origin is not supported on mac
shifts = {"down": kw.shift_down, "right": kw.shift_to_right, None: None}
self.xl.insert_into_range(shift=shifts[shift])
def delete(self, shift=None):
shifts = {"up": kw.shift_up, "left": kw.shift_to_left, None: None}
self.xl.delete_range(shift=shifts[shift])
def copy(self, destination=None):
self.xl.copy_range(destination=destination.api if destination else None)
def paste(self, paste=None, operation=None, skip_blanks=False, transpose=False):
pastes = {
# all_merging_conditional_formats unsupported on mac
"all": kw.paste_all,
"all_except_borders": kw.paste_all_except_borders,
"all_using_source_theme": kw.paste_all_using_source_theme,
"column_widths": kw.paste_column_widths,
"comments": kw.paste_comments,
"formats": kw.paste_formats,
"formulas": kw.paste_formulas,
"formulas_and_number_formats": kw.paste_formulas_and_number_formats,
"validation": kw.paste_validation,
"values": kw.paste_values,
"values_and_number_formats": kw.paste_values_and_number_formats,
None: None,
}
operations = {
"add": kw.paste_special_operation_add,
"divide": kw.paste_special_operation_divide,
"multiply": kw.paste_special_operation_multiply,
"subtract": kw.paste_special_operation_subtract,
None: None,
}
self.xl.paste_special(
what=pastes[paste],
operation=operations[operation],
skip_blanks=skip_blanks,
transpose=transpose,
)
@property
def hyperlink(self):
try:
return self.xl.hyperlinks[1].address.get()
except CommandError:
raise Exception("The cell doesn't seem to contain a hyperlink!")
def add_hyperlink(self, address, text_to_display=None, screen_tip=None):
if self.xl is not None:
self.xl.make(
at=self.xl,
new=kw.hyperlink,
with_properties={
kw.address: address,
kw.text_to_display: text_to_display,
kw.screen_tip: screen_tip,
},
)
@property
def color(self):
if (
not self.xl
or self.xl.interior_object.color_index.get() == kw.color_index_none
):
return None
else:
return tuple(self.xl.interior_object.color.get())
@color.setter
def color(self, color_or_rgb):
if isinstance(color_or_rgb, str):
color_or_rgb = utils.hex_to_rgb(color_or_rgb)
if self.xl is not None:
if color_or_rgb is None:
self.xl.interior_object.color_index.set(ColorIndex.xlColorIndexNone)
elif isinstance(color_or_rgb, int):
self.xl.interior_object.color.set(int_to_rgb(color_or_rgb))
else:
self.xl.interior_object.color.set(color_or_rgb)
@property
def name(self):
if not self.xl:
return None
xl = self.xl.named_item
if xl.get() == kw.missing_value:
return None
else:
return Name(self.sheet.book, xl=xl)
@name.setter
def name(self, value):
if self.xl is not None:
self.xl.name.set(value)
def __call__(self, arg1, arg2=None):
if arg2 is None:
col = (arg1 - 1) % self.shape[1]
row = int((arg1 - 1 - col) / self.shape[1])
return self(1 + row, 1 + col)
else:
return Range(
self.sheet,
self.sheet.xl.rows[self.row + arg1 - 1]
.columns[self.column + arg2 - 1]
.get_address(),
)
@property
def rows(self):
row = self.row
col1 = self.column
col2 = col1 + self.shape[1] - 1
return [
self.sheet.range((row + i, col1), (row + i, col2))
for i in range(self.shape[0])
]
@property
def columns(self):
col = self.column
row1 = self.row
row2 = row1 + self.shape[0] - 1
sht = self.sheet
return [
sht.range((row1, col + i), (row2, col + i)) for i in range(self.shape[1])
]
def select(self):
if self.xl is not None:
return self.xl.select()
@property
def merge_area(self):
return Range(self.sheet, self.xl.merge_area.get_address())
@property
def merge_cells(self):
return self.xl.merge_cells.get()
def merge(self, across):
self.xl.merge(across=across)
def unmerge(self):
self.xl.unmerge()
@property
def table(self):
if self.xl.list_object.name.get() == kw.missing_value:
return None
else:
return Table(self.sheet, self.xl.list_object.name.get())
@property
def characters(self):
# This is broken with AppleScript/Excel 2016
return Characters(parent=self, xl=self.xl.characters)
@property
def wrap_text(self):
return self.xl.wrap_text.get()
@wrap_text.setter
def wrap_text(self, value):
self.xl.wrap_text.set(value)
@property
def note(self):
try:
# No easy way to check whether there's a comment like on Windows
return (
Note(parent=self, xl=self.xl.Excel_comment)
if self.xl.Excel_comment.Excel_comment_text()
else None
)
except appscript.reference.CommandError:
return None
def copy_picture(self, appearance, format):
_appearance = {"screen": kw.screen, "printer": kw.printer}
_format = {"picture": kw.picture, "bitmap": kw.bitmap}
self.xl.copy_picture(appearance=_appearance[appearance], format=_format[format])
def to_png(self, path):
self.copy_picture(appearance="screen", format="bitmap")
im = ImageGrab.grabclipboard()
im.save(path)
def to_pdf(self, path, quality=None):
raise xlwings.XlwingsError("Range.to_pdf() isn't supported on macOS.")
def autofill(self, destination, type_):
types = {
"fill_copy": kw.fill_copy,
"fill_days": kw.fill_days,
"fill_default": kw.fill_default,
"fill_formats": kw.fill_formats,
"fill_months": kw.fill_months,
"fill_series": kw.fill_series,
"fill_values": kw.fill_values,
"fill_weekdays": kw.fill_weekdays,
"fill_years": kw.fill_years,
"growth_trend": kw.growth_trend,
"linear_trend": kw.linear_trend,
"flash_fill": kw.flashfill,
}
self.xl.autofill(destination=destination.api, type=types[type_])
| Range |
python | doocs__leetcode | solution/2300-2399/2397.Maximum Rows Covered by Columns/Solution.py | {
"start": 0,
"end": 478
} | class ____:
def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int:
rows = []
for row in matrix:
mask = reduce(or_, (1 << j for j, x in enumerate(row) if x), 0)
rows.append(mask)
ans = 0
for mask in range(1 << len(matrix[0])):
if mask.bit_count() != numSelect:
continue
t = sum((x & mask) == x for x in rows)
ans = max(ans, t)
return ans
| Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/kubernetes_engine.py | {
"start": 2199,
"end": 4050
} | class ____:
"""Helper for establishing connection to GKE cluster."""
def __init__(
self,
cluster_url: str,
ssl_ca_cert: str,
credentials: google.auth.credentials.Credentials,
enable_tcp_keepalive: bool = False,
use_dns_endpoint: bool = False,
):
self._cluster_url = cluster_url
self._ssl_ca_cert = ssl_ca_cert
self._credentials = credentials
self.enable_tcp_keepalive = enable_tcp_keepalive
self.use_dns_endpoint = use_dns_endpoint
def get_conn(self) -> client.ApiClient:
configuration = self._get_config()
configuration.refresh_api_key_hook = self._refresh_api_key_hook
if self.enable_tcp_keepalive:
_enable_tcp_keepalive()
return client.ApiClient(configuration)
def _refresh_api_key_hook(self, configuration: client.configuration.Configuration):
configuration.api_key = {"authorization": self._get_token(self._credentials)}
def _get_config(self) -> client.configuration.Configuration:
configuration = client.Configuration(
host=self._cluster_url,
api_key_prefix={"authorization": "Bearer"},
api_key={"authorization": self._get_token(self._credentials)},
)
if not self.use_dns_endpoint:
configuration.ssl_ca_cert = FileOrData(
{
"certificate-authority-data": self._ssl_ca_cert,
},
file_key_name="certificate-authority",
).as_file()
return configuration
@staticmethod
def _get_token(creds: google.auth.credentials.Credentials) -> str:
if creds.token is None or creds.expired:
auth_req = google_requests.Request()
creds.refresh(auth_req)
return creds.token
| GKEClusterConnection |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 21504,
"end": 25026
} | class ____:
def test_invalid_policies(self):
pq = ["string"]
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), pq)
with pytest.raises(TypeError):
x509.CertificatePolicies([1, pi]) # type:ignore[list-item]
def test_iter_len(self):
pq = ["string"]
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), pq)
cp = x509.CertificatePolicies([pi])
assert len(cp) == 1
for policyinfo in cp:
assert policyinfo == pi
def test_iter_input(self):
policies = [
x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), ["string"])
]
cp = x509.CertificatePolicies(iter(policies))
assert list(cp) == policies
def test_repr(self):
pq = ["string"]
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), pq)
cp = x509.CertificatePolicies([pi])
assert repr(cp) == (
"<CertificatePolicies([<PolicyInformation(policy_identifier=<O"
"bjectIdentifier(oid=1.2.3, name=Unknown OID)>, policy_qualifi"
"ers=['string'])>])>"
)
def test_eq(self):
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), ["string"])
cp = x509.CertificatePolicies([pi])
pi2 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"), ["string"]
)
cp2 = x509.CertificatePolicies([pi2])
assert cp == cp2
def test_ne(self):
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), ["string"])
cp = x509.CertificatePolicies([pi])
pi2 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"), ["string2"]
)
cp2 = x509.CertificatePolicies([pi2])
assert cp != cp2
assert cp != object()
def test_indexing(self):
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), ["test"])
pi2 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.4"), ["test"])
pi3 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.5"), ["test"])
pi4 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.6"), ["test"])
pi5 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.7"), ["test"])
cp = x509.CertificatePolicies([pi, pi2, pi3, pi4, pi5])
assert cp[-1] == cp[4]
assert cp[2:6:2] == [cp[2], cp[4]]
def test_long_oid(self, backend):
"""
Test that parsing a CertificatePolicies ext with
a very long OID succeeds.
"""
cert = _load_cert(
os.path.join("x509", "bigoid.pem"),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.CertificatePolicies)
oid = x509.ObjectIdentifier(
"1.3.6.1.4.1.311.21.8.8950086.10656446.2706058"
".12775672.480128.147.13466065.13029902"
)
assert ext.value[0].policy_identifier == oid
def test_hash(self):
pi = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), ["string"])
cp = x509.CertificatePolicies([pi])
pi2 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"), ["string"]
)
cp2 = x509.CertificatePolicies([pi2])
pi3 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"), [x509.UserNotice(None, "text")]
)
cp3 = x509.CertificatePolicies([pi3])
assert hash(cp) == hash(cp2)
assert hash(cp) != hash(cp3)
| TestCertificatePolicies |
python | joke2k__faker | tests/providers/test_bank.py | {
"start": 1861,
"end": 2508
} | class ____:
"""Test az_AZ bank provider"""
def test_bban(self, faker, num_samples):
for _ in range(num_samples):
assert re.fullmatch(r"[A-Z]{4}\d{20}", faker.bban())
def test_iban(self, faker, num_samples):
for _ in range(num_samples):
iban = faker.iban()
assert is_valid_iban(iban)
assert iban[:2] == AzAzBankProvider.country_code
assert re.fullmatch(r"\d{2}[A-Z]{4}\d{20}", iban[2:])
def test_bank(self, faker, num_samples):
for _ in range(num_samples):
bank = faker.bank()
assert bank in AzAzBankProvider.banks
| TestAzAz |
python | cython__cython | Cython/Compiler/Tests/TestParseTreeTransforms.py | {
"start": 5733,
"end": 8328
} | class ____(DebuggerTestCase):
def elem_hasattrs(self, elem, attrs):
return all(attr in elem.attrib for attr in attrs)
def test_debug_info(self):
try:
assert os.path.exists(self.debug_dest)
t = DebugWriter.etree.parse(self.debug_dest)
# the xpath of the standard ElementTree is primitive, don't use
# anything fancy
L = list(t.find('/Module/Globals'))
assert L
xml_globals = {e.attrib['name']: e.attrib['type'] for e in L}
self.assertEqual(len(L), len(xml_globals))
L = list(t.find('/Module/Functions'))
assert L
xml_funcs = {e.attrib['qualified_name']: e for e in L}
self.assertEqual(len(L), len(xml_funcs))
# test globals
self.assertEqual('CObject', xml_globals.get('c_var'))
self.assertEqual('PythonObject', xml_globals.get('python_var'))
# test functions
funcnames = ('codefile.spam', 'codefile.ham', 'codefile.eggs',
'codefile.closure', 'codefile.inner')
required_xml_attrs = 'name', 'cname', 'qualified_name'
assert all(f in xml_funcs for f in funcnames)
spam, ham, eggs = [xml_funcs[funcname] for funcname in funcnames]
self.assertEqual(spam.attrib['name'], 'spam')
self.assertNotEqual('spam', spam.attrib['cname'])
assert self.elem_hasattrs(spam, required_xml_attrs)
# test locals of functions
spam_locals = list(spam.find('Locals'))
assert spam_locals
spam_locals.sort(key=lambda e: e.attrib['name'])
names = [e.attrib['name'] for e in spam_locals]
self.assertEqual(list('abcd'), names)
assert self.elem_hasattrs(spam_locals[0], required_xml_attrs)
# test arguments of functions
spam_arguments = list(spam.find('Arguments'))
assert spam_arguments
self.assertEqual(1, len(list(spam_arguments)))
# test step-into functions
step_into = spam.find('StepIntoFunctions')
spam_stepinto = [x.attrib['name'] for x in step_into]
assert spam_stepinto
self.assertEqual(2, len(spam_stepinto))
assert 'puts' in spam_stepinto
assert 'some_c_function' in spam_stepinto
except:
f = open(self.debug_dest)
try:
print(f.read())
finally:
f.close()
raise
| TestDebugTransform |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py | {
"start": 10335,
"end": 12639
} | class ____(nn.Module):
"""A classifier that uses attention to summarize the inputs.
Attributes:
hidden_size: The hidden size of the MLP classifier.
output_size: The number of output classes for the classifier.
dropout_rate: The dropout rate applied over the encoded_inputs, the summary
of the inputs, and inside the MLP. Applied when `deterministic` is False.
deterministic: Disables dropout if True.
"""
hidden_size: int
output_size: int
dropout_rate: float = 0.
deterministic: bool | None = None
def setup(self):
self.dropout_layer = nn.Dropout(rate=self.dropout_rate)
self.keys_only_mlp_attention = KeysOnlyMlpAttention(
hidden_size=self.hidden_size)
self.mlp = MLP(
hidden_size=self.hidden_size,
output_size=self.output_size,
output_bias=False,
dropout_rate=self.dropout_rate)
def __call__(self, encoded_inputs: Array, lengths: Array,
deterministic: bool | None = None) -> Array:
"""Applies model to the encoded inputs.
Args:
encoded_inputs: The inputs (e.g., sentences) that have already been
encoded by some encoder, e.g., an LSTM. <float32>[batch_size,
seq_length, encoded_inputs_size].
lengths: The lengths of the inputs. <int64>[batch_size].
deterministic: Disables dropout when set to True.
Returns:
An array of logits <float32>[batch_size, output_size].
"""
deterministic = nn.module.merge_param(
'deterministic', self.deterministic, deterministic)
encoded_inputs = self.dropout_layer(
encoded_inputs, deterministic=deterministic)
# Compute attention. attention.shape: <float32>[batch_size, seq_len].
mask = sequence_mask(lengths, encoded_inputs.shape[1])
attention = self.keys_only_mlp_attention(encoded_inputs, mask)
# Summarize the inputs by taking their weighted sum using attention scores.
context = jnp.expand_dims(attention, 1) @ encoded_inputs
context = context.squeeze(1) # <float32>[batch_size, encoded_inputs_size]
context = self.dropout_layer(context, deterministic=deterministic)
# Make the final prediction from the context vector (the summarized inputs).
logits = self.mlp(context, deterministic=deterministic)
return logits
| AttentionClassifier |
python | spyder-ide__spyder | spyder/widgets/collectionseditor.py | {
"start": 3801,
"end": 3936
} | class ____:
Edit = 'edit_section'
AddRemove = 'add_remove_section'
View = 'view_section'
| CollectionsEditorContextMenuSections |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0030_add_automation_rule_matches.py | {
"start": 218,
"end": 3050
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0029_add_time_fields"),
]
operations = [
migrations.CreateModel(
name="AutomationRuleMatch",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"created",
django_extensions.db.fields.CreationDateTimeField(
auto_now_add=True, verbose_name="created"
),
),
(
"modified",
django_extensions.db.fields.ModificationDateTimeField(
auto_now=True, verbose_name="modified"
),
),
("version_name", models.CharField(max_length=255)),
("match_arg", models.CharField(max_length=255)),
(
"action",
models.CharField(
choices=[
("activate-version", "Activate version"),
("hide-version", "Hide version"),
("make-version-public", "Make version public"),
("make-version-private", "Make version private"),
("set-default-version", "Set version as default"),
(
"delete-version",
"Delete version (on branch/tag deletion)",
),
],
max_length=255,
),
),
(
"version_type",
models.CharField(
choices=[
("branch", "Branch"),
("tag", "Tag"),
("external", "External"),
("unknown", "Unknown"),
],
max_length=32,
),
),
(
"rule",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="matches",
to="builds.VersionAutomationRule",
verbose_name="Matched rule",
),
),
],
options={
"ordering": ("-modified", "-created"),
},
),
]
| Migration |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 213563,
"end": 215999
} | class ____(ParseElementEnhance):
"""
Optional matching of the given expression.
:param expr: expression that must match zero or more times
:param default: (optional) - value to be returned
if the optional expression is not found.
Example:
.. testcode::
# US postal code can be a 5-digit zip, plus optional 4-digit qualifier
zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))
zip.run_tests('''
# traditional ZIP code
12345
# ZIP+4 form
12101-0001
# invalid ZIP
98765-
''')
prints:
.. testoutput::
:options: +NORMALIZE_WHITESPACE
# traditional ZIP code
12345
['12345']
# ZIP+4 form
12101-0001
['12101-0001']
# invalid ZIP
98765-
98765-
^
ParseException: Expected end of text, found '-' (at char 5), (line:1, col:6)
FAIL: Expected end of text, found '-' (at char 5), (line:1, col:6)
"""
__optionalNotMatched = _NullToken()
def __init__(
self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched
) -> None:
super().__init__(expr, savelist=False)
self.saveAsList = self.expr.saveAsList
self.defaultValue = default
self._may_return_empty = True
def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType:
self_expr = self.expr
try:
loc, tokens = self_expr._parse(
instring, loc, do_actions, callPreParse=False
)
except (ParseException, IndexError):
default_value = self.defaultValue
if default_value is not self.__optionalNotMatched:
if self_expr.resultsName:
tokens = ParseResults([default_value])
tokens[self_expr.resultsName] = default_value
else:
tokens = [default_value] # type: ignore[assignment]
else:
tokens = [] # type: ignore[assignment]
return loc, tokens
def _generateDefaultName(self) -> str:
inner = str(self.expr)
# strip off redundant inner {}'s
while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
inner = inner[1:-1]
return f"[{inner}]"
Optional = Opt
| Opt |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 8150,
"end": 8401
} | class ____(PydanticValueError):
code = 'list.max_items'
msg_template = 'ensure this value has at most {limit_value} items'
def __init__(self, *, limit_value: int) -> None:
super().__init__(limit_value=limit_value)
| ListMaxLengthError |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_gcs.py | {
"start": 1823,
"end": 2765
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.gcs.GCSHook")
def test_execute(self, mock_hook):
operator = GCSCreateBucketOperator(
task_id=TASK_ID,
bucket_name=TEST_BUCKET,
resource={"lifecycle": {"rule": [{"action": {"type": "Delete"}, "condition": {"age": 7}}]}},
storage_class="MULTI_REGIONAL",
location="EU",
labels={"env": "prod"},
project_id=TEST_PROJECT,
)
operator.execute(context=mock.MagicMock())
mock_hook.return_value.create_bucket.assert_called_once_with(
bucket_name=TEST_BUCKET,
storage_class="MULTI_REGIONAL",
location="EU",
labels={"env": "prod"},
project_id=TEST_PROJECT,
resource={"lifecycle": {"rule": [{"action": {"type": "Delete"}, "condition": {"age": 7}}]}},
)
| TestGoogleCloudStorageCreateBucket |
python | giampaolo__psutil | tests/test_bsd.py | {
"start": 17411,
"end": 19910
} | class ____(PsutilTestCase):
@staticmethod
def parse_meminfo(look_for):
with open('/proc/meminfo') as f:
for line in f:
if line.startswith(look_for):
return int(line.split()[1]) * 1024
raise ValueError(f"can't find {look_for}")
# --- virtual mem
def test_vmem_total(self):
assert psutil.virtual_memory().total == self.parse_meminfo("MemTotal:")
def test_vmem_free(self):
assert (
abs(psutil.virtual_memory().free - self.parse_meminfo("MemFree:"))
< TOLERANCE_SYS_MEM
)
def test_vmem_buffers(self):
assert (
abs(
psutil.virtual_memory().buffers
- self.parse_meminfo("Buffers:")
)
< TOLERANCE_SYS_MEM
)
def test_vmem_shared(self):
assert (
abs(
psutil.virtual_memory().shared
- self.parse_meminfo("MemShared:")
)
< TOLERANCE_SYS_MEM
)
def test_vmem_cached(self):
assert (
abs(psutil.virtual_memory().cached - self.parse_meminfo("Cached:"))
< TOLERANCE_SYS_MEM
)
# --- swap mem
def test_swapmem_total(self):
assert (
abs(psutil.swap_memory().total - self.parse_meminfo("SwapTotal:"))
< TOLERANCE_SYS_MEM
)
def test_swapmem_free(self):
assert (
abs(psutil.swap_memory().free - self.parse_meminfo("SwapFree:"))
< TOLERANCE_SYS_MEM
)
def test_swapmem_used(self):
smem = psutil.swap_memory()
assert smem.used == smem.total - smem.free
# --- others
def test_cpu_stats_interrupts(self):
with open('/proc/stat', 'rb') as f:
for line in f:
if line.startswith(b'intr'):
interrupts = int(line.split()[1])
break
else:
raise ValueError("couldn't find line")
assert abs(psutil.cpu_stats().interrupts - interrupts) < 1000
def test_cpu_stats_ctx_switches(self):
with open('/proc/stat', 'rb') as f:
for line in f:
if line.startswith(b'ctxt'):
ctx_switches = int(line.split()[1])
break
else:
raise ValueError("couldn't find line")
assert abs(psutil.cpu_stats().ctx_switches - ctx_switches) < 1000
| NetBSDTestCase |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 14861,
"end": 15465
} | class ____:
param_names = ["shape", "axis", "drop_ncols"]
params = [
get_benchmark_shapes("TimeDrop"),
[0, 1],
[1, 0.8],
]
def setup(self, shape, axis, drop_ncols):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
drop_count = (
int(len(self.df.axes[axis]) * drop_ncols)
if isinstance(drop_ncols, float)
else drop_ncols
)
self.labels = self.df.axes[axis][:drop_count]
def time_drop(self, shape, axis, drop_ncols):
execute(self.df.drop(self.labels, axis=axis))
| TimeDrop |
python | pytorch__pytorch | torch/__init__.py | {
"start": 73913,
"end": 83066
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.quint2x4
_storage_classes: set[type[_Union[TypedStorage, UntypedStorage]]] = {
UntypedStorage,
DoubleStorage,
FloatStorage,
LongStorage,
IntStorage,
ShortStorage,
CharStorage,
ByteStorage,
HalfStorage,
BoolStorage,
QUInt8Storage,
QInt8Storage,
QInt32Storage,
BFloat16Storage,
ComplexFloatStorage,
ComplexDoubleStorage,
QUInt4x2Storage,
QUInt2x4Storage,
TypedStorage,
}
# The _tensor_classes set is initialized by the call to initialize_python_bindings.
_tensor_classes: set[type["torch.Tensor"]] = set()
# If you edit these imports, please update torch/__init__.py.in as well
from torch import amp as amp, random as random, serialization as serialization
from torch._tensor_str import set_printoptions
from torch.amp import autocast, GradScaler
from torch.random import get_rng_state, initial_seed, manual_seed, seed, set_rng_state
from torch.serialization import load, save
################################################################################
# Initialize extension
################################################################################
# Shared memory manager needs to know the exact location of manager executable
def _manager_path():
if platform.system() == "Windows":
return b""
path = get_file_path("torch", "bin", "torch_shm_manager")
prepare_multiprocessing_environment(get_file_path("torch"))
if not os.path.exists(path):
raise RuntimeError("Unable to find torch_shm_manager at " + path)
return path.encode("utf-8")
_C._initExtension(_manager_path())
del _manager_path
# Appease the type checker: it can't deal with direct setting of globals().
# Note that we will see "too many" functions when reexporting this way; there
# is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions
# so that this import is good enough
if TYPE_CHECKING:
# Some type signatures pulled in from _VariableFunctions here clash with
# signatures already imported. For now these clashes are ignored; see
# PR #43339 for details.
from torch._C._VariableFunctions import * # type: ignore[assignment, misc] # noqa: F403
# Fixup segment_reduce visibility
_segment_reduce = segment_reduce
del segment_reduce # noqa: F821
# Ops not to be exposed in `torch` namespace,
# mostly helper ops.
PRIVATE_OPS = ("unique_dim",)
__name, __obj = "", None
for __name in dir(_C._VariableFunctions):
if __name.startswith("__") or __name in PRIVATE_OPS:
continue
__obj = getattr(_C._VariableFunctions, __name)
__obj.__module__ = __name__ # "torch"
# Hide some APIs that should not be public
if __name == "segment_reduce":
# TODO: Once the undocumented FC window is passed, remove the line below
globals()[__name] = __obj
__name = "_" + __name
globals()[__name] = __obj
if not __name.startswith("_"):
__all__.append(__name)
del __name, __obj
################################################################################
# Add torch.dtype instances to the public API
################################################################################
import torch
__all__.extend(
name for name in dir(torch) if isinstance(getattr(torch, name), torch.dtype)
)
################################################################################
# Import TorchDynamo's lazy APIs to avoid circular dependencies
################################################################################
# needs to be before from torch.functional import * to avoid circular dependencies
from torch._compile import _disable_dynamo # usort: skip
################################################################################
# Import interface functions defined in Python
################################################################################
# needs to be after the above ATen bindings so we can overwrite from Python side
from torch import _VF as _VF, functional as functional # usort: skip
from torch.functional import * # usort: skip # noqa: F403
################################################################################
# Remove unnecessary members
################################################################################
del _StorageBase
del _LegacyStorage
################################################################################
# Define _assert
################################################################################
# needs to be before the submodule imports to avoid circular dependencies
def _assert(condition, message):
r"""A wrapper around Python's assert which is symbolically traceable."""
if type(condition) is not torch.Tensor and overrides.has_torch_function(
(condition,)
):
return overrides.handle_torch_function(
_assert, (condition,), condition, message
)
assert condition, message
################################################################################
# Import most common subpackages
################################################################################
# Use the redundant form so that type checkers know that these are a part of
# the public API. The "regular" import lines are there solely for the runtime
# side effect of adding to the imported module's members for other users.
# needs to be before import torch.nn as nn to avoid circular dependencies
from torch.autograd import ( # usort: skip
enable_grad as enable_grad,
inference_mode as inference_mode,
no_grad as no_grad,
set_grad_enabled as set_grad_enabled,
)
from torch import (
__config__ as __config__,
__future__ as __future__,
_awaits as _awaits,
accelerator as accelerator,
autograd as autograd,
backends as backends,
cpu as cpu,
cuda as cuda,
distributed as distributed,
distributions as distributions,
fft as fft,
futures as futures,
hub as hub,
jit as jit,
linalg as linalg,
mps as mps,
mtia as mtia,
multiprocessing as multiprocessing,
nested as nested,
nn as nn,
optim as optim,
overrides as overrides,
profiler as profiler,
sparse as sparse,
special as special,
testing as testing,
types as types,
utils as utils,
version as version,
xpu as xpu,
)
from torch.signal import windows as windows
# Quantized, sparse, AO, etc. should be last to get imported, as nothing
# is expected to depend on them.
from torch import ao as ao # usort: skip
# nn.quant* depends on ao -- so should be after those.
import torch.nn.intrinsic
import torch.nn.qat
import torch.nn.quantizable
import torch.nn.quantized
_C._init_names(list(_storage_classes))
# attach docstrings to torch and tensor functions
from torch import _size_docs, _storage_docs, _tensor_docs, _torch_docs
del _torch_docs, _tensor_docs, _storage_docs, _size_docs
def compiled_with_cxx11_abi() -> builtins.bool:
r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1"""
return True
from torch import _library as _library, _ops as _ops
# Import the ops and classes "namespace"
from torch._ops import ops as ops # usort: skip
from torch._classes import classes as classes # usort: skip
sys.modules.setdefault(f"{__name__}.ops", ops)
sys.modules.setdefault(f"{__name__}.classes", classes)
# quantization depends on torch.fx and torch.ops
# Import quantization
from torch import quantization as quantization # usort: skip
# Import the quasi random sampler
from torch import quasirandom as quasirandom # usort: skip
# If you are seeing this, it means that this call site was not checked if
# the memory format could be preserved, and it was switched to old default
# behaviour of contiguous
legacy_contiguous_format = contiguous_format # defined by _C._initExtension()
# Register fork handler to initialize OpenMP in child processes (see gh-28389)
from torch.multiprocessing._atfork import register_after_fork
register_after_fork(torch.get_num_threads)
del register_after_fork
# Import tools that require fully imported torch (for applying
# torch.jit.script as a decorator, for instance):
from torch._lobpcg import lobpcg as lobpcg
# These were previously defined in native_functions.yaml and appeared on the
# `torch` namespace, but we moved them to c10 dispatch to facilitate custom
# class usage. We add these lines here to preserve backward compatibility.
quantized_lstm = ops.aten.quantized_lstm
quantized_gru = ops.aten.quantized_gru
# Import experimental masked operations support. See
# [RFC-0016](https://github.com/pytorch/rfcs/pull/27) for more
# information.
from torch import masked as masked
# Import removed ops with error message about removal
from torch._linalg_utils import ( # type: ignore[misc]
_symeig as symeig,
eig,
lstsq,
matrix_rank,
solve,
)
from torch.utils.dlpack import from_dlpack, to_dlpack
| QUInt2x4Storage |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 189301,
"end": 191371
} | class ____(test.TestCase):
def _compareZeros(self, dtype, use_gpu):
# Creates a tensor of non-zero values with shape 2 x 3.
# NOTE(kearnes): The default numpy dtype associated with tf.string is
# np.object (and can't be changed without breaking a lot things), which
# causes a TypeError in constant_op.constant below. Here we catch the
# special case of tf.string and set the numpy dtype appropriately.
if dtype == dtypes.string:
numpy_dtype = np.bytes_
else:
numpy_dtype = dtype.as_numpy_dtype
d = constant_op.constant(np.ones((2, 3), dtype=numpy_dtype), dtype=dtype)
# Constructs a tensor of zeros of the same dimensions and type as "d".
z_var = array_ops.zeros_like(d)
# Test that the type is correct
self.assertEqual(z_var.dtype, dtype)
# Test that the shape is correct
self.assertEqual([2, 3], z_var.get_shape())
# Test that the value is correct
z_value = z_var.numpy()
self.assertFalse(np.any(z_value))
self.assertEqual((2, 3), z_value.shape)
def testZerosLikeCPU(self):
for dtype in [
dtypes.float32,
dtypes.float64,
dtypes.int32,
dtypes.uint8,
dtypes.int16,
dtypes.int8,
dtypes.complex64,
dtypes.complex128,
dtypes.int64,
]:
self._compareZeros(dtype, use_gpu=False)
def testZerosLikeGPU(self):
for dtype in [
dtypes.float32,
dtypes.float64,
dtypes.int32,
dtypes.bool,
dtypes.int64,
]:
self._compareZeros(dtype, use_gpu=True)
def testZerosLikeDtype(self):
# Make sure zeros_like works even for dtypes that cannot be cast between
shape = (3, 5)
dtypes_ = np.float32, np.complex64
for in_type in dtypes_:
x = np.arange(15).astype(in_type).reshape(*shape)
for out_type in dtypes_:
y = array_ops.zeros_like(x, dtype=out_type).numpy()
self.assertEqual(y.dtype, out_type)
self.assertEqual(y.shape, shape)
self.assertAllEqual(y, np.zeros(shape, dtype=out_type))
| ZerosLikeTest |
python | django__django | tests/utils_tests/test_choices.py | {
"start": 2019,
"end": 3380
} | class ____(SimpleTestCase):
def test_empty(self):
def generator():
yield from ()
for choices in ({}, [], (), set(), frozenset(), generator(), None, ""):
with self.subTest(choices=choices):
result = flatten_choices(choices)
self.assertIsInstance(result, collections.abc.Generator)
self.assertEqual(list(result), [])
def test_non_empty(self):
choices = [
("C", _("Club")),
("D", _("Diamond")),
("H", _("Heart")),
("S", _("Spade")),
]
result = flatten_choices(choices)
self.assertIsInstance(result, collections.abc.Generator)
self.assertEqual(list(result), choices)
def test_nested_choices(self):
choices = [
("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]),
("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]),
("unknown", _("Unknown")),
]
expected = [
("vinyl", _("Vinyl")),
("cd", _("CD")),
("vhs", _("VHS Tape")),
("dvd", _("DVD")),
("unknown", _("Unknown")),
]
result = flatten_choices(choices)
self.assertIsInstance(result, collections.abc.Generator)
self.assertEqual(list(result), expected)
| FlattenChoicesTests |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/prefect_gcp/deployments/steps.py | {
"start": 403,
"end": 530
} | class ____(TypedDict):
"""
The output of the `push_to_gcs` step.
"""
bucket: str
folder: str
| PushToGcsOutput |
python | celery__celery | celery/events/dumper.py | {
"start": 757,
"end": 3137
} | class ____:
"""Monitor events."""
def __init__(self, out=sys.stdout):
self.out = out
def say(self, msg):
print(msg, file=self.out)
# need to flush so that output can be piped.
try:
self.out.flush()
except AttributeError: # pragma: no cover
pass
def on_event(self, ev):
timestamp = datetime.fromtimestamp(ev.pop('timestamp'), timezone.utc)
type = ev.pop('type').lower()
hostname = ev.pop('hostname')
if type.startswith('task-'):
uuid = ev.pop('uuid')
if type in ('task-received', 'task-sent'):
task = TASK_NAMES[uuid] = '{}({}) args={} kwargs={}' \
.format(ev.pop('name'), uuid,
ev.pop('args'),
ev.pop('kwargs'))
else:
task = TASK_NAMES.get(uuid, '')
return self.format_task_event(hostname, timestamp,
type, task, ev)
fields = ', '.join(
f'{key}={ev[key]}' for key in sorted(ev)
)
sep = fields and ':' or ''
self.say(f'{hostname} [{timestamp}] {humanize_type(type)}{sep} {fields}')
def format_task_event(self, hostname, timestamp, type, task, event):
fields = ', '.join(
f'{key}={event[key]}' for key in sorted(event)
)
sep = fields and ':' or ''
self.say(f'{hostname} [{timestamp}] {humanize_type(type)}{sep} {task} {fields}')
def evdump(app=None, out=sys.stdout):
"""Start event dump."""
app = app_or_default(app)
dumper = Dumper(out=out)
dumper.say('-> evdump: starting capture...')
conn = app.connection_for_read().clone()
def _error_handler(exc, interval):
dumper.say(CONNECTION_ERROR % (
conn.as_uri(), exc, humanize_seconds(interval, 'in', ' ')
))
while 1:
try:
conn.ensure_connection(_error_handler)
recv = app.events.Receiver(conn, handlers={'*': dumper.on_event})
recv.capture()
except (KeyboardInterrupt, SystemExit):
return conn and conn.close()
except conn.connection_errors + conn.channel_errors:
dumper.say('-> Connection lost, attempting reconnect')
if __name__ == '__main__': # pragma: no cover
evdump()
| Dumper |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/snap.py | {
"start": 1102,
"end": 6155
} | class ____(IHaveNew):
kind: ConfigTypeKind
key: str
given_name: Optional[str]
description: Optional[str]
type_param_keys: Optional[Sequence[str]] # only valid for closed generics
enum_values: Optional[Sequence["ConfigEnumValueSnap"]] # only valid for enums
fields: Optional[Sequence["ConfigFieldSnap"]] # only valid for dicts and selectors
scalar_kind: Optional[ConfigScalarKind] # only valid for scalars
field_aliases: Optional[Mapping[str, str]] # only valid for strict shapes
# serdes log
# * Adding scalar_kind
# * Adding field_aliases
def __new__(
cls,
kind: ConfigTypeKind,
key: str,
given_name: Optional[str],
description: Optional[str],
type_param_keys: Optional[Sequence[str]],
enum_values: Optional[Sequence["ConfigEnumValueSnap"]],
fields: Optional[Sequence["ConfigFieldSnap"]],
# Old version of object will not have these properties
scalar_kind: Optional[ConfigScalarKind] = None,
field_aliases: Optional[Mapping[str, str]] = None,
):
return super().__new__(
cls,
kind=kind,
key=key,
given_name=given_name,
description=description,
type_param_keys=type_param_keys,
enum_values=enum_values,
fields=(
None
if fields is None
else sorted(
check.list_param(fields, "field", of_type=ConfigFieldSnap),
key=_ct_name,
)
),
scalar_kind=scalar_kind,
field_aliases=field_aliases or {},
)
@property
def key_type_key(self) -> str:
"""For a type which has keys such as Map, returns the type of the key."""
# valid for Map, which has its key type as the first entry in type_param_keys
check.invariant(self.kind == ConfigTypeKind.MAP)
type_param_keys = check.is_list(self.type_param_keys, of_type=str)
check.invariant(len(type_param_keys) == 2)
return type_param_keys[0]
@property
def inner_type_key(self) -> str:
"""For container types such as Array or Noneable, the contained type. For a Map, the value type."""
# valid for Noneable, Map, and Array
check.invariant(
self.kind == ConfigTypeKind.NONEABLE
or self.kind == ConfigTypeKind.ARRAY
or self.kind == ConfigTypeKind.MAP
)
type_param_keys = check.is_list(self.type_param_keys, of_type=str)
if self.kind == ConfigTypeKind.MAP:
# For a Map, the inner (value) type is the second entry (the first is the key type)
check.invariant(len(type_param_keys) == 2)
return type_param_keys[1]
else:
check.invariant(len(type_param_keys) == 1)
return type_param_keys[0]
@property
def scalar_type_key(self) -> str:
check.invariant(self.kind == ConfigTypeKind.SCALAR_UNION)
type_param_keys = check.is_list(self.type_param_keys, of_type=str)
return type_param_keys[0]
@property
def non_scalar_type_key(self) -> str:
check.invariant(self.kind == ConfigTypeKind.SCALAR_UNION)
type_param_keys = check.is_list(self.type_param_keys, of_type=str)
return type_param_keys[1]
def _get_field(self, name: str) -> Optional["ConfigFieldSnap"]:
check.str_param(name, "name")
check.invariant(ConfigTypeKind.has_fields(self.kind))
fields = check.is_list(self.fields, of_type=ConfigFieldSnap)
for f in fields:
if f.name == name:
return f
return None
def get_field(self, name: str) -> "ConfigFieldSnap":
field = self._get_field(name)
if not field:
check.failed(f"Field {name} not found")
return field
def has_field(self, name: str) -> bool:
return bool(self._get_field(name))
@property
def field_names(self) -> Sequence[str]:
fields = check.is_list(self.fields, of_type=ConfigFieldSnap)
# Typing error caught by making is_list typed -- schrockn 2024-06-09
return [fs.name for fs in fields] # type: ignore
def get_child_type_keys(self) -> Sequence[str]:
if ConfigTypeKind.is_closed_generic(self.kind):
# all closed generics have type params
return cast("list[str]", self.type_param_keys)
elif ConfigTypeKind.has_fields(self.kind):
return [
field.type_key
for field in cast("list[ConfigFieldSnap]", check.not_none(self.fields))
]
else:
return []
def has_enum_value(self, value: object) -> bool:
check.invariant(self.kind == ConfigTypeKind.ENUM)
for enum_value in cast("list[ConfigEnumValueSnap]", self.enum_values):
if enum_value.value == value:
return True
return False
@whitelist_for_serdes
@record
| ConfigTypeSnap |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 853,
"end": 904
} | class ____(TypedDict, total=True):
x: int
| ParentE |
python | encode__django-rest-framework | tests/test_encoders.py | {
"start": 420,
"end": 4521
} | class ____(TestCase):
"""
Tests the JSONEncoder method
"""
def setUp(self):
self.encoder = JSONEncoder()
def test_encode_decimal(self):
"""
Tests encoding a decimal
"""
d = Decimal(3.14)
assert self.encoder.default(d) == float(d)
def test_encode_datetime(self):
"""
Tests encoding a datetime object
"""
current_time = datetime.now()
assert self.encoder.default(current_time) == current_time.isoformat()
current_time_utc = current_time.replace(tzinfo=utc)
assert self.encoder.default(current_time_utc) == current_time.isoformat() + 'Z'
def test_encode_time(self):
"""
Tests encoding a timezone
"""
current_time = datetime.now().time()
assert self.encoder.default(current_time) == current_time.isoformat()
def test_encode_time_tz(self):
"""
Tests encoding a timezone aware timestamp
"""
current_time = datetime.now().time()
current_time = current_time.replace(tzinfo=utc)
with pytest.raises(ValueError):
self.encoder.default(current_time)
def test_encode_date(self):
"""
Tests encoding a date object
"""
current_date = date.today()
assert self.encoder.default(current_date) == current_date.isoformat()
def test_encode_timedelta(self):
"""
Tests encoding a timedelta object
"""
delta = timedelta(hours=1)
assert self.encoder.default(delta) == str(delta.total_seconds())
def test_encode_uuid(self):
"""
Tests encoding a UUID object
"""
unique_id = uuid4()
assert self.encoder.default(unique_id) == str(unique_id)
def test_encode_ipaddress_ipv4address(self):
"""
Tests encoding ipaddress IPv4Address object
"""
obj = ipaddress.IPv4Address("192.168.1.1")
assert self.encoder.default(obj) == "192.168.1.1"
def test_encode_ipaddress_ipv6address(self):
"""
Tests encoding ipaddress IPv6Address object
"""
obj = ipaddress.IPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
assert self.encoder.default(obj) == "2001:db8:85a3::8a2e:370:7334"
def test_encode_ipaddress_ipv4network(self):
"""
Tests encoding ipaddress IPv4Network object
"""
obj = ipaddress.IPv4Network("192.0.2.8/29")
assert self.encoder.default(obj) == "192.0.2.8/29"
def test_encode_ipaddress_ipv6network(self):
"""
Tests encoding ipaddress IPv4Network object
"""
obj = ipaddress.IPv6Network("2001:4860:0000::0000/32")
assert self.encoder.default(obj) == "2001:4860::/32"
def test_encode_ipaddress_ipv4interface(self):
"""
Tests encoding ipaddress IPv4Interface object
"""
obj = ipaddress.IPv4Interface("192.0.2.8/29")
assert self.encoder.default(obj) == "192.0.2.8/29"
def test_encode_ipaddress_ipv6interface(self):
"""
Tests encoding ipaddress IPv4Network object
"""
obj = ipaddress.IPv6Interface("2001:4860:4860::8888/32")
assert self.encoder.default(obj) == "2001:4860:4860::8888/32"
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
def test_encode_coreapi_raises_error(self):
"""
Tests encoding a coreapi objects raises proper error
"""
with pytest.raises(RuntimeError):
self.encoder.default(coreapi.Document())
with pytest.raises(RuntimeError):
self.encoder.default(coreapi.Error())
def test_encode_object_with_tolist(self):
"""
Tests encoding a object with tolist method
"""
foo = MockList()
assert self.encoder.default(foo) == [1, 2, 3]
def test_encode_empty_returnlist(self):
"""
Tests encoding an empty ReturnList
"""
foo = ReturnList(serializer=None)
assert self.encoder.default(foo) == []
| JSONEncoderTests |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/property_subclasses/my_models.py | {
"start": 1039,
"end": 1980
} | class ____(ndb.StringProperty):
def __init__(self, bits, **kwds):
assert isinstance(bits, int)
assert bits > 0 and bits % 4 == 0 # Make it simple to use hex
super(BoundedLongIntegerProperty, self).__init__(**kwds)
self._bits = bits
def _validate(self, value):
assert -(2 ** (self._bits - 1)) <= value < 2 ** (self._bits - 1)
def _to_base_type(self, value):
# convert from signed -> unsigned
if value < 0:
value += 2**self._bits
assert 0 <= value < 2**self._bits
# Return number as a zero-padded hex string with correct number of
# digits:
return "%0*x" % (self._bits // 4, value)
def _from_base_type(self, value):
value = int(value, 16)
if value >= 2 ** (self._bits - 1):
value -= 2**self._bits
return value
# Define an entity class holding some long integers.
| BoundedLongIntegerProperty |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/entrypoint.py | {
"start": 3277,
"end": 3354
} | class ____(Enum):
DEFAULT = "default"
FLUENTBIT = "fluentbit"
| LogFormat |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 1194,
"end": 1413
} | class ____(CookiecutterException):
"""
Exception for missing config file.
Raised when get_config() is passed a path to a config file, but no file
is found at that path.
"""
| ConfigDoesNotExistException |
python | ray-project__ray | python/ray/tests/test_client.py | {
"start": 22576,
"end": 30191
} | class ____:
pass
obj_ref = f.remote()
actor_ref = SomeClass.remote()
"""
def test_object_ref_cleanup(call_ray_start_shared):
# Checks no error output when running the script in
# object_ref_cleanup_script
# See https://github.com/ray-project/ray/issues/17968 for details
with ray_start_client_server_for_address(call_ray_start_shared):
result = run_string_as_driver(object_ref_cleanup_script)
assert "Error in sys.excepthook:" not in result
assert "AttributeError: 'NoneType' object has no " not in result
assert "Exception ignored in" not in result
def test_wrapped_actor_creation(call_ray_start_shared, shutdown_only):
"""
When the client schedules an actor, the server will load a separate
copy of the actor class if it's defined in a separate file. This
means that modifications to the client's copy of the actor class
aren't propagated to the server. Currently, tracing logic modifies
the signatures of actor methods to pass around metadata when ray.remote
is applied to an actor class. However, if a user does something like:
class SomeActor:
def __init__(self):
pass
def decorate_actor():
RemoteActor = ray.remote(SomeActor)
...
Then the SomeActor class will have its signatures modified on the client
side, but not on the server side, since ray.remote was applied inside of
the function instead of directly on the actor. Note if it were directly
applied to the actor then the signature would be modified when the server
imports the class.
"""
import ray
ray.init(SHARED_CLIENT_SERVER_ADDRESS)
run_wrapped_actor_creation()
@pytest.mark.parametrize("use_client", [True, False])
def test_init_requires_no_resources(call_ray_start_shared, use_client, shutdown_only):
import ray
if not use_client:
address = call_ray_start_shared
ray.init(address)
else:
ray.init(SHARED_CLIENT_SERVER_ADDRESS)
@ray.remote(num_cpus=0)
def f():
pass
ray.get(f.remote())
def test_object_ref_release(call_ray_start_shared, shutdown_only):
import ray
ray.init(SHARED_CLIENT_SERVER_ADDRESS)
a = ray.put("Hello")
ray.shutdown()
ray.init(SHARED_CLIENT_SERVER_ADDRESS)
del a
with disable_client_hook():
ref_cnt = ray.util.client.ray.get_context().client_worker.reference_count
assert all(v > 0 for v in ref_cnt.values())
def test_empty_objects(call_ray_start_shared):
"""
Tests that client works with "empty" objects. Sanity check, since put requests
will fail if the serialized version of an object consists of zero bytes.
"""
objects = [0, b"", "", [], np.array(()), {}, set(), None]
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
for obj in objects:
ref = ray.put(obj)
if isinstance(obj, np.ndarray):
assert np.array_equal(ray.get(ref), obj)
else:
assert ray.get(ref) == obj
def test_large_remote_call(call_ray_start_shared):
"""
Test remote calls with large (multiple chunk) arguments
"""
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
@ray.remote
def f(large_obj):
return large_obj.shape
@ray.remote
def f2(*args):
assert args[0] == 123
return args[1].shape
@ray.remote
def f3(*args, **kwargs):
assert args[0] == "a"
assert args[1] == "b"
return kwargs["large_obj"].shape
# 1024x1024x16 f64's =~ 128 MiB. Chunking size is 64 MiB, so guarantees
# that transferring argument requires multiple chunks.
assert OBJECT_TRANSFER_CHUNK_SIZE < 2**20 * 128
large_obj = np.random.random((1024, 1024, 16))
assert ray.get(f.remote(large_obj)) == (1024, 1024, 16)
assert ray.get(f2.remote(123, large_obj)) == (1024, 1024, 16)
assert ray.get(f3.remote("a", "b", large_obj=large_obj)) == (1024, 1024, 16)
@ray.remote
class SomeActor:
def __init__(self, large_obj):
self.inner = large_obj
def some_method(self, large_obj):
return large_obj.shape == self.inner.shape
a = SomeActor.remote(large_obj)
assert ray.get(a.some_method.remote(large_obj))
def test_ignore_reinit(call_ray_start_shared, shutdown_only):
import ray
ctx1 = ray.init(SHARED_CLIENT_SERVER_ADDRESS)
ctx2 = ray.init(SHARED_CLIENT_SERVER_ADDRESS, ignore_reinit_error=True)
assert ctx1 == ctx2
def test_client_actor_missing_field(call_ray_start_shared):
"""
Tests that trying to access methods that don't exist for an actor
raises the correct exception.
"""
class SomeSuperClass:
def parent_func(self):
return 24
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
@ray.remote
class SomeClass(SomeSuperClass):
def child_func(self):
return 42
handle = SomeClass.remote()
assert ray.get(handle.parent_func.remote()) == 24
assert ray.get(handle.child_func.remote()) == 42
with pytest.raises(AttributeError):
# We should raise attribute error when accessing a non-existent func
_ = SomeClass.nonexistent_func
def test_serialize_client_actor_handle(call_ray_start_shared):
"""
Test that client actor handles can be serialized. This is needed since
some objects like datasets keep a handle to actors.
See https://github.com/ray-project/ray/issues/31581 for more context
"""
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
@ray.remote
class SomeClass:
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
handle = SomeClass.remote(1234)
serialized = cloudpickle.dumps(handle)
deserialized = cloudpickle.loads(serialized)
assert ray.get(deserialized.get_value.remote()) == 1234
def test_actor_streaming_returns_error_message(call_ray_start_shared):
"""
num_returns="streaming" is not supported with Ray Client.
"""
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
@ray.remote
class Actor:
def stream(self):
yield "hi"
a = Actor.remote()
with pytest.raises(
RuntimeError,
match=re.escape(
'Streaming actor methods (num_returns="streaming") are '
"not currently supported when using Ray Client."
),
):
a.stream.options(num_returns="streaming").remote()
def test_get_runtime_context_gcs_client(call_ray_start_shared):
"""
Tests get_runtime_context gcs_client
"""
with ray_start_client_server_for_address(call_ray_start_shared) as ray:
context = ray.get_runtime_context()
assert context.gcs_address, "gcs_address not set"
def test_internal_kv_in_proxy_mode(call_ray_start_shared):
import ray
ray.init(SHARED_CLIENT_SERVER_ADDRESS)
client_api = ray.util.client.ray
client_api._internal_kv_put(b"key", b"val")
assert client_api._internal_kv_get(b"key") == b"val"
assert client_api._internal_kv_del(b"key") == 1
assert client_api._internal_kv_get(b"key") is None
if __name__ == "__main__":
sys.exit(pytest.main(["-sv", __file__]))
| SomeClass |
python | pytorch__pytorch | .github/scripts/pytest_caching_utils.py | {
"start": 1015,
"end": 9086
} | class ____(NamedTuple):
owner: str
name: str
# Create a Repo from a string like "owner/repo"
@classmethod
def from_string(cls, repo_string: str) -> "GithubRepo":
if "/" not in repo_string:
raise ValueError(
f"repo_string must be of the form 'owner/repo', not {repo_string}"
)
owner, name = repo_string.split("/")
return cls(owner, name)
def __str__(self) -> str:
return f"{self.owner}/{self.name}"
def upload_pytest_cache(
pr_identifier: PRIdentifier,
repo: GithubRepo,
job_identifier: str,
sha: str,
test_config: str,
shard: str,
cache_dir: Path,
temp_dir: Path,
bucket: str = BUCKET,
) -> None:
"""
Uploads the pytest cache to S3, merging it with any previous caches from previous runs of the same job.
In particular, this keeps all the failed tests across all runs of this job in the cache, so that
future jobs that download this cache will prioritize running tests that have failed in the past.
Args:
pr_identifier: A unique, human readable identifier for the PR
job: The name of the job that is uploading the cache
"""
if not isinstance(pr_identifier, PRIdentifier):
raise ValueError(
f"pr_identifier must be of type PRIdentifier, not {type(pr_identifier)}"
)
if not bucket:
bucket = BUCKET
# Upload the cache
obj_key_prefix = _get_s3_key_prefix(
pr_identifier, repo, job_identifier, sha, test_config, shard
)
zip_file_path = zip_folder(cache_dir, temp_dir / ZIP_UPLOAD / obj_key_prefix)
obj_key = f"{obj_key_prefix}{os.path.splitext(zip_file_path)[1]}" # Keep the new file extension
upload_file_to_s3(zip_file_path, bucket, obj_key)
def download_pytest_cache(
pr_identifier: PRIdentifier,
repo: GithubRepo,
job_identifier: str,
dest_cache_dir: Path,
temp_dir: Path,
bucket: str = BUCKET,
) -> None:
"""
Downloads the pytest cache from S3. The goal is to detect any tests that have failed in the past
and run them first, so that the dev can get faster feedback on them.
We merge the cache from all shards since tests can get shuffled around from one shard to another
(based on when we last updated our stats on how long each test takes to run). This ensures that
even if a test moves to a different shard, that shard will know to run it first if had failed previously.
"""
if not bucket:
bucket = BUCKET
if not isinstance(pr_identifier, PRIdentifier):
raise ValueError(
f"pr_identifier must be of type PRIdentifier, not {type(pr_identifier)}"
)
obj_key_prefix = _get_s3_key_prefix(pr_identifier, repo, job_identifier)
zip_download_dir = temp_dir / CACHE_ZIP_DOWNLOADS / obj_key_prefix
# downloads the cache zips for all shards
downloads = download_s3_objects_with_prefix(
bucket, obj_key_prefix, zip_download_dir
)
for downloaded_zip in downloads:
# Unzip into random folder, then merge with the current cache
cache_dir_for_shard = (
temp_dir / UNZIPPED_CACHES / os.urandom(16).hex() / PYTEST_CACHE_DIR_NAME
)
unzip_folder(downloaded_zip, cache_dir_for_shard)
print(f"Merging cache from {downloaded_zip}")
_merge_pytest_caches(cache_dir_for_shard, dest_cache_dir)
def _get_s3_key_prefix(
pr_identifier: PRIdentifier,
repo: GithubRepo,
job_identifier: str,
sha: str = "",
test_config: str = "",
shard: str = "",
) -> str:
"""
The prefix to any S3 object key for a pytest cache. It's only a prefix though, not a full path to an object.
For example, it won't include the file extension.
"""
prefix = f"{PYTEST_CACHE_KEY_PREFIX}/{repo.owner}/{repo.name}/{pr_identifier}/{sanitize_for_s3(job_identifier)}"
if sha:
prefix += f"/{sha}"
if test_config:
prefix += f"/{sanitize_for_s3(test_config)}"
if shard:
prefix += f"/{shard}"
return prefix
def _merge_pytest_caches(
pytest_cache_dir_to_merge_from: Path, pytest_cache_dir_to_merge_into: Path
) -> None:
# LASTFAILED_FILE_PATH is the only file we actually care about in the cache
# since it contains all the tests that failed.
#
# The remaining files are static supporting files that don't really matter. They
# make the cache folder play nice with other tools devs tend to use (e.g. git).
# But since pytest doesn't recreate these files if the .pytest_cache folder already exists,
# we'll copy them over as a way to protect against future bugs where a certain tool
# may need those files to exist to work properly (their combined file size is negligible)
static_files_to_copy = [
".gitignore",
"CACHEDIR.TAG",
"README.md",
]
# Copy over the static files. These files never change, so only copy them
# if they don't already exist in the new cache
for static_file in static_files_to_copy:
source_file = pytest_cache_dir_to_merge_from / static_file
if not source_file.is_file():
continue
dest_file = pytest_cache_dir_to_merge_into / static_file
if not dest_file.exists():
copy_file(source_file, dest_file)
# Handle the v/cache/lastfailed file
_merge_lastfailed_files(
pytest_cache_dir_to_merge_from, pytest_cache_dir_to_merge_into
)
_merge_additional_failures_files(
pytest_cache_dir_to_merge_from, pytest_cache_dir_to_merge_into
)
def _merge_lastfailed_files(source_pytest_cache: Path, dest_pytest_cache: Path) -> None:
# Simple cases where one of the files doesn't exist
source_lastfailed_file = source_pytest_cache / LASTFAILED_FILE_PATH
dest_lastfailed_file = dest_pytest_cache / LASTFAILED_FILE_PATH
if not source_lastfailed_file.exists():
return
if not dest_lastfailed_file.exists():
copy_file(source_lastfailed_file, dest_lastfailed_file)
return
# Both files exist, so we need to merge them
from_lastfailed = load_json_file(source_lastfailed_file)
to_lastfailed = load_json_file(dest_lastfailed_file)
merged_content = _merged_lastfailed_content(from_lastfailed, to_lastfailed)
# Save the results
write_json_file(dest_lastfailed_file, merged_content)
def _merged_lastfailed_content(
from_lastfailed: dict[str, bool], to_lastfailed: dict[str, bool]
) -> dict[str, bool]:
"""
The lastfailed files are dictionaries where the key is the test identifier.
Each entry's value appears to always be `true`, but let's not count on that.
An empty dictionary is represented with a single value with an empty string as the key.
"""
# If an entry in from_lastfailed doesn't exist in to_lastfailed, add it and it's value
for key in from_lastfailed:
if key not in to_lastfailed:
to_lastfailed[key] = from_lastfailed[key]
if len(to_lastfailed) > 1:
# Remove the empty entry if it exists since we have actual entries now
if "" in to_lastfailed:
del to_lastfailed[""]
return to_lastfailed
def _merge_additional_failures_files(
source_pytest_cache: Path, dest_pytest_cache: Path
) -> None:
# Simple cases where one of the files doesn't exist
source_lastfailed_file = (
source_pytest_cache / TD_HEURISTIC_PREVIOUSLY_FAILED_ADDITIONAL
)
dest_lastfailed_file = dest_pytest_cache / TD_HEURISTIC_PREVIOUSLY_FAILED_ADDITIONAL
if not source_lastfailed_file.exists():
return
if not dest_lastfailed_file.exists():
copy_file(source_lastfailed_file, dest_lastfailed_file)
return
# Both files exist, so we need to merge them
from_lastfailed = load_json_file(source_lastfailed_file)
to_lastfailed = load_json_file(dest_lastfailed_file)
merged_content = list(set(from_lastfailed + to_lastfailed))
# Save the results
write_json_file(dest_lastfailed_file, merged_content)
| GithubRepo |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 8461,
"end": 8702
} | class ____(graphene.ObjectType):
assetKey = graphene.NonNull(GrapheneAssetKey)
partitionKeys = non_null_list(graphene.String)
class Meta:
name = "RequestedMaterializationsForAsset"
| GrapheneRequestedMaterializationsForAsset |
python | google__python-fire | fire/formatting_test.py | {
"start": 683,
"end": 2647
} | class ____(testutils.BaseTestCase):
def test_bold(self):
text = formatting.Bold('hello')
self.assertIn(text, ['hello', '\x1b[1mhello\x1b[0m'])
def test_underline(self):
text = formatting.Underline('hello')
self.assertIn(text, ['hello', '\x1b[4mhello\x1b[0m'])
def test_indent(self):
text = formatting.Indent('hello', spaces=2)
self.assertEqual(' hello', text)
def test_indent_multiple_lines(self):
text = formatting.Indent('hello\nworld', spaces=2)
self.assertEqual(' hello\n world', text)
def test_wrap_one_item(self):
lines = formatting.WrappedJoin(['rice'])
self.assertEqual(['rice'], lines)
def test_wrap_multiple_items(self):
lines = formatting.WrappedJoin(['rice', 'beans', 'chicken', 'cheese'],
width=15)
self.assertEqual(['rice | beans |',
'chicken |',
'cheese'], lines)
def test_ellipsis_truncate(self):
text = 'This is a string'
truncated_text = formatting.EllipsisTruncate(
text=text, available_space=10, line_length=LINE_LENGTH)
self.assertEqual('This is...', truncated_text)
def test_ellipsis_truncate_not_enough_space(self):
text = 'This is a string'
truncated_text = formatting.EllipsisTruncate(
text=text, available_space=2, line_length=LINE_LENGTH)
self.assertEqual('This is a string', truncated_text)
def test_ellipsis_middle_truncate(self):
text = '1000000000L'
truncated_text = formatting.EllipsisMiddleTruncate(
text=text, available_space=7, line_length=LINE_LENGTH)
self.assertEqual('10...0L', truncated_text)
def test_ellipsis_middle_truncate_not_enough_space(self):
text = '1000000000L'
truncated_text = formatting.EllipsisMiddleTruncate(
text=text, available_space=2, line_length=LINE_LENGTH)
self.assertEqual('1000000000L', truncated_text)
if __name__ == '__main__':
testutils.main()
| FormattingTest |
python | fsspec__filesystem_spec | fsspec/tests/abstract/open.py | {
"start": 16,
"end": 329
} | class ____:
def test_open_exclusive(self, fs, fs_target):
with fs.open(fs_target, "wb") as f:
f.write(b"data")
with fs.open(fs_target, "rb") as f:
assert f.read() == b"data"
with pytest.raises(FileExistsError):
fs.open(fs_target, "xb")
| AbstractOpenTests |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_resource_claim_template_spec.py | {
"start": 383,
"end": 4409
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'metadata': 'V1ObjectMeta',
'spec': 'V1beta2ResourceClaimSpec'
}
attribute_map = {
'metadata': 'metadata',
'spec': 'spec'
}
def __init__(self, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501
"""V1beta2ResourceClaimTemplateSpec - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._metadata = None
self._spec = None
self.discriminator = None
if metadata is not None:
self.metadata = metadata
self.spec = spec
@property
def metadata(self):
"""Gets the metadata of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:return: The metadata of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1beta2ResourceClaimTemplateSpec.
:param metadata: The metadata of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def spec(self):
"""Gets the spec of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:return: The spec of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:rtype: V1beta2ResourceClaimSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""Sets the spec of this V1beta2ResourceClaimTemplateSpec.
:param spec: The spec of this V1beta2ResourceClaimTemplateSpec. # noqa: E501
:type: V1beta2ResourceClaimSpec
"""
if self.local_vars_configuration.client_side_validation and spec is None: # noqa: E501
raise ValueError("Invalid value for `spec`, must not be `None`") # noqa: E501
self._spec = spec
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1beta2ResourceClaimTemplateSpec):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta2ResourceClaimTemplateSpec):
return True
return self.to_dict() != other.to_dict()
| V1beta2ResourceClaimTemplateSpec |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_numeric.py | {
"start": 2308,
"end": 4418
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpn.Interval()
with pytest.raises(ValueError):
bcpn.Interval(Int, 0.0, 1.0)
def test_valid_int(self) -> None:
prop = bcpn.Interval(Int, 0, 255)
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(127)
def test_invalid_int(self) -> None:
prop = bcpn.Interval(Int, 0, 255)
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_valid(True)
assert not prop.is_valid(0.0)
assert not prop.is_valid(1.0)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid("")
assert not prop.is_valid(())
assert not prop.is_valid([])
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
assert not prop.is_valid(-1)
assert not prop.is_valid(256)
def test_valid_float(self) -> None:
prop = bcpn.Interval(Float, 0.0, 1.0)
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(0.0)
assert prop.is_valid(1.0)
assert prop.is_valid(0.5)
def test_invalid_float(self) -> None:
prop = bcpn.Interval(Float, 0.0, 1.0)
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_valid(True)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid("")
assert not prop.is_valid(())
assert not prop.is_valid([])
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
assert not prop.is_valid(-0.001)
assert not prop.is_valid( 1.001)
def test_has_ref(self) -> None:
prop = bcpn.Interval(Float, 0.0, 1.0)
assert not prop.has_ref
def test_str(self) -> None:
prop = bcpn.Interval(Float, 0.0, 1.0)
assert str(prop) == "Interval(Float, 0.0, 1.0)"
| Test_Interval |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 5802,
"end": 10385
} | class ____(Serializer):
def __init__(self, environments=None, expand=None):
self.environments = environments
self.expand = expand
def get_attrs(self, item_list, user, **kwargs):
# TODO(dcramer): assert on relations
projects = Project.objects.filter(id__in=[i.project_id for i in item_list])
projects_data = {
project.id: serialized_project
for project, serialized_project in zip(projects, serialize(list(projects), user))
}
actors = [Actor.from_id(user_id=m.owner_user_id) for m in item_list if m.owner_user_id]
actors.extend(
[Actor.from_id(team_id=m.owner_team_id) for m in item_list if m.owner_team_id]
)
filtered_actors = list(filter(None, actors))
actors_serialized = serialize(Actor.resolve_many(filtered_actors), user, ActorSerializer())
actor_data = {
actor: serialized_actor
for actor, serialized_actor in zip(filtered_actors, actors_serialized)
}
# Query ALL environments (unfiltered) to determine muted status
# A monitor is muted only if ALL its environments are muted
all_monitor_environments = (
MonitorEnvironment.objects.filter(monitor__in=item_list)
.exclude(
status__in=[MonitorStatus.PENDING_DELETION, MonitorStatus.DELETION_IN_PROGRESS]
)
.order_by("monitor_id")
)
# Group environments by monitor
monitor_envs_by_id = {
monitor_id: list(envs)
for monitor_id, envs in groupby(all_monitor_environments, key=attrgetter("monitor_id"))
}
# A monitor is muted only if it has environments AND all of them are muted
is_muted_data = {
item.id: bool(monitor_envs_by_id.get(item.id, []))
and all(env.is_muted for env in monitor_envs_by_id.get(item.id, []))
for item in item_list
}
# Now query the filtered environments for serialization
monitor_environments_qs = (
MonitorEnvironment.objects.filter(monitor__in=item_list)
.annotate(status_ordering=MONITOR_ENVIRONMENT_ORDERING)
.order_by("status_ordering", "-last_checkin", "environment_id")
.exclude(
status__in=[MonitorStatus.PENDING_DELETION, MonitorStatus.DELETION_IN_PROGRESS]
)
)
if self.environments:
monitor_environments_qs = monitor_environments_qs.filter(
environment_id__in=[env.id for env in self.environments]
)
monitor_environments = list(monitor_environments_qs)
serialized_monitor_environments = defaultdict(list)
for monitor_env, serialized in zip(
monitor_environments, serialize(monitor_environments, user)
):
serialized_monitor_environments[monitor_env.monitor_id].append(serialized)
environment_data = {
item.id: serialized_monitor_environments.get(item.id, []) for item in item_list
}
attrs = {
item: {
"project": projects_data[item.project_id] if item.project_id else None,
"environments": environment_data[item.id],
"owner": actor_data.get(item.owner_actor),
"is_muted": is_muted_data[item.id],
}
for item in item_list
}
if self._expand("alertRule"):
for item in item_list:
attrs[item]["alertRule"] = item.get_issue_alert_rule_data()
return attrs
def serialize(self, obj, attrs, user, **kwargs) -> MonitorSerializerResponse:
config = obj.config.copy()
if "schedule_type" in config:
config["schedule_type"] = obj.get_schedule_type_display()
result: MonitorSerializerResponse = {
"id": str(obj.guid),
"status": obj.get_status_display(),
"isMuted": attrs["is_muted"],
"isUpserting": obj.is_upserting,
"name": obj.name,
"slug": obj.slug,
"config": config,
"dateCreated": obj.date_added,
"project": attrs["project"],
"environments": attrs["environments"],
"owner": attrs["owner"],
}
if self._expand("alertRule"):
result["alertRule"] = attrs["alertRule"]
return result
def _expand(self, key) -> bool:
if self.expand is None:
return False
return key in self.expand
| MonitorSerializer |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 1436,
"end": 1630
} | class ____(NoMutationModel):
a: int = 1
model_config = ConfigDict(frozen=False, from_attributes=True)
MutationModel(x=1).x = 2
MutationModel.model_validate(model.__dict__)
| MutationModel |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py | {
"start": 7083,
"end": 7166
} | class ____(DepthAnythingReassembleStage):
pass
| PromptDepthAnythingReassembleStage |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 50164,
"end": 50563
} | class ____:
xlValidateCustom = 7 # from enum XlDVType
xlValidateDate = 4 # from enum XlDVType
xlValidateDecimal = 2 # from enum XlDVType
xlValidateInputOnly = 0 # from enum XlDVType
xlValidateList = 3 # from enum XlDVType
xlValidateTextLength = 6 # from enum XlDVType
xlValidateTime = 5 # from enum XlDVType
xlValidateWholeNumber = 1 # from enum XlDVType
| DVType |
python | pytorch__pytorch | test/inductor/test_group_batch_fusion.py | {
"start": 1445,
"end": 2736
} | class ____(torch.nn.Module):
def __init__(self, z: int, has_bias: bool, device="cuda") -> None:
super().__init__()
self.z = z
self.device = device
self.seq_len = 10
self.seq1 = [
torch.nn.Linear(z, z, has_bias).to(self.device) for _ in range(self.seq_len)
]
self.seq2 = [
torch.nn.Linear(z, z, has_bias).to(self.device) for _ in range(self.seq_len)
]
self.seq3 = [
torch.nn.Linear(z, z, has_bias).to(self.device) for _ in range(self.seq_len)
]
def forward(self, x: torch.Tensor) -> torch.Tensor:
x1 = [x + 0.1 * i for i in range(self.seq_len)]
x2 = [self.seq1[i](x1[i]) for i in range(self.seq_len)]
x3 = [x2[i] - 0.1 * i for i in range(self.seq_len)]
x4 = [x1[i] for i in range(3)] + [x3[i] for i in range(3, self.seq_len)]
x5 = [self.seq2[i](x4[i]) for i in range(self.seq_len)]
x6 = [x5[i] + 0.1 * (self.seq_len - i) for i in range(self.seq_len)]
x7 = (
[x1[i] for i in range(4)]
+ [x3[i] for i in range(6, 8)]
+ [x6[i] for i in range(4)]
)
x8 = [self.seq3[i](x7[i]) for i in range(self.seq_len)]
x9 = torch.cat(x8, dim=1)
return x9
| MyModule |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py | {
"start": 114,
"end": 231
} | class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
@define() # auto_attribs = None => True
| C |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 327414,
"end": 335668
} | class ____:
# For alpha = .05, .01, and .001, and for each value of
# v = [1, 3, 10, 20, 120, inf], a Q was picked from each table for
# k = [2, 8, 14, 20].
# these arrays are written with `k` as column, and `v` as rows.
# Q values are taken from table 3:
# https://www.jstor.org/stable/2237810
q05 = [17.97, 45.40, 54.33, 59.56,
4.501, 8.853, 10.35, 11.24,
3.151, 5.305, 6.028, 6.467,
2.950, 4.768, 5.357, 5.714,
2.800, 4.363, 4.842, 5.126,
2.772, 4.286, 4.743, 5.012]
q01 = [90.03, 227.2, 271.8, 298.0,
8.261, 15.64, 18.22, 19.77,
4.482, 6.875, 7.712, 8.226,
4.024, 5.839, 6.450, 6.823,
3.702, 5.118, 5.562, 5.827,
3.643, 4.987, 5.400, 5.645]
q001 = [900.3, 2272, 2718, 2980,
18.28, 34.12, 39.69, 43.05,
6.487, 9.352, 10.39, 11.03,
5.444, 7.313, 7.966, 8.370,
4.772, 6.039, 6.448, 6.695,
4.654, 5.823, 6.191, 6.411]
qs = np.concatenate((q05, q01, q001))
ps = [.95, .99, .999]
vs = [1, 3, 10, 20, 120, np.inf]
ks = [2, 8, 14, 20]
data = list(zip(product(ps, vs, ks), qs))
# A small selection of large-v cases generated with R's `ptukey`
# Each case is in the format (q, k, v, r_result)
r_data = [
(0.1, 3, 9001, 0.002752818526842),
(1, 10, 1000, 0.000526142388912),
(1, 3, np.inf, 0.240712641229283),
(4, 3, np.inf, 0.987012338626815),
(1, 10, np.inf, 0.000519869467083),
]
@pytest.mark.slow
def test_cdf_against_tables(self):
for pvk, q in self.data:
p_expected, v, k = pvk
res_p = stats.studentized_range.cdf(q, k, v)
assert_allclose(res_p, p_expected, rtol=1e-4)
@pytest.mark.xslow
def test_ppf_against_tables(self):
for pvk, q_expected in self.data:
p, v, k = pvk
res_q = stats.studentized_range.ppf(p, k, v)
assert_allclose(res_q, q_expected, rtol=5e-4)
path_prefix = os.path.dirname(__file__)
relative_path = "data/studentized_range_mpmath_ref.json"
with open(os.path.join(path_prefix, relative_path)) as file:
pregenerated_data = json.load(file)
@pytest.mark.parametrize("case_result", pregenerated_data["cdf_data"])
def test_cdf_against_mp(self, case_result):
src_case = case_result["src_case"]
mp_result = case_result["mp_result"]
qkv = src_case["q"], src_case["k"], src_case["v"]
res = stats.studentized_range.cdf(*qkv)
assert_allclose(res, mp_result,
atol=src_case["expected_atol"],
rtol=src_case["expected_rtol"])
@pytest.mark.parametrize("case_result", pregenerated_data["pdf_data"])
def test_pdf_against_mp(self, case_result):
src_case = case_result["src_case"]
mp_result = case_result["mp_result"]
qkv = src_case["q"], src_case["k"], src_case["v"]
res = stats.studentized_range.pdf(*qkv)
assert_allclose(res, mp_result,
atol=src_case["expected_atol"],
rtol=src_case["expected_rtol"])
@pytest.mark.xslow
@pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.")
@pytest.mark.parametrize("case_result", pregenerated_data["moment_data"])
def test_moment_against_mp(self, case_result):
src_case = case_result["src_case"]
mp_result = case_result["mp_result"]
mkv = src_case["m"], src_case["k"], src_case["v"]
# Silence invalid value encountered warnings. Actual problems will be
# caught by the result comparison.
with np.errstate(invalid='ignore'):
res = stats.studentized_range.moment(*mkv)
assert_allclose(res, mp_result,
atol=src_case["expected_atol"],
rtol=src_case["expected_rtol"])
@pytest.mark.slow
def test_pdf_integration(self):
k, v = 3, 10
# Test whether PDF integration is 1 like it should be.
res = quad(stats.studentized_range.pdf, 0, np.inf, args=(k, v))
assert_allclose(res[0], 1)
@pytest.mark.xslow
def test_pdf_against_cdf(self):
k, v = 3, 10
# Test whether the integrated PDF matches the CDF using cumulative
# integration. Use a small step size to reduce error due to the
# summation. This is slow, but tests the results well.
x = np.arange(0, 10, step=0.01)
y_cdf = stats.studentized_range.cdf(x, k, v)[1:]
y_pdf_raw = stats.studentized_range.pdf(x, k, v)
y_pdf_cumulative = cumulative_trapezoid(y_pdf_raw, x)
# Because of error caused by the summation, use a relatively large rtol
assert_allclose(y_pdf_cumulative, y_cdf, rtol=1e-4)
@pytest.mark.parametrize("r_case_result", r_data)
def test_cdf_against_r(self, r_case_result):
# Test large `v` values using R
q, k, v, r_res = r_case_result
with np.errstate(invalid='ignore'):
res = stats.studentized_range.cdf(q, k, v)
assert_allclose(res, r_res)
@pytest.mark.xslow
@pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.")
def test_moment_vectorization(self):
# Test moment broadcasting. Calls `_munp` directly because
# `rv_continuous.moment` is broken at time of writing. See gh-12192
# Silence invalid value encountered warnings. Actual problems will be
# caught by the result comparison.
with np.errstate(invalid='ignore'):
m = stats.studentized_range._munp([1, 2], [4, 5], [10, 11])
assert_allclose(m.shape, (2,))
with pytest.raises(ValueError, match="...could not be broadcast..."):
stats.studentized_range._munp(1, [4, 5], [10, 11, 12])
@pytest.mark.xslow
def test_fitstart_valid(self):
with warnings.catch_warnings(), np.errstate(invalid="ignore"):
# the integration warning message may differ
warnings.simplefilter("ignore", IntegrationWarning)
k, df, _, _ = stats.studentized_range._fitstart([1, 2, 3])
assert_(stats.studentized_range._argcheck(k, df))
def test_infinite_df(self):
# Check that the CDF and PDF infinite and normal integrators
# roughly match for a high df case
res = stats.studentized_range.pdf(3, 10, np.inf)
res_finite = stats.studentized_range.pdf(3, 10, 99999)
assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4)
res = stats.studentized_range.cdf(3, 10, np.inf)
res_finite = stats.studentized_range.cdf(3, 10, 99999)
assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4)
def test_df_cutoff(self):
# Test that the CDF and PDF properly switch integrators at df=100,000.
# The infinite integrator should be different enough that it fails
# an allclose assertion. Also sanity check that using the same
# integrator does pass the allclose with a 1-df difference, which
# should be tiny.
res = stats.studentized_range.pdf(3, 10, 100000)
res_finite = stats.studentized_range.pdf(3, 10, 99999)
res_sanity = stats.studentized_range.pdf(3, 10, 99998)
assert_raises(AssertionError, assert_allclose, res, res_finite,
atol=1e-6, rtol=1e-6)
assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6)
res = stats.studentized_range.cdf(3, 10, 100000)
res_finite = stats.studentized_range.cdf(3, 10, 99999)
res_sanity = stats.studentized_range.cdf(3, 10, 99998)
assert_raises(AssertionError, assert_allclose, res, res_finite,
atol=1e-6, rtol=1e-6)
assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6)
def test_clipping(self):
# The result of this computation was -9.9253938401489e-14 on some
# systems. The correct result is very nearly zero, but should not be
# negative.
q, k, v = 34.6413996195345746, 3, 339
p = stats.studentized_range.sf(q, k, v)
assert_allclose(p, 0, atol=1e-10)
assert p >= 0
| TestStudentizedRange |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/cache_test.py | {
"start": 23602,
"end": 26437
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 3, 4])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]).cache()
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index))
@combinations.generate(test_base.default_test_combinations())
def testCacheRangeDataset(self):
dataset = dataset_ops.Dataset.range(10).cache()
expected_elements = list(range(10))
self.verifyRandomAccess(dataset, expected_elements)
@combinations.generate(test_base.default_test_combinations())
def testCacheOneDimensionalElements(self):
tensor = [1, 2, 3]
dataset = dataset_ops.Dataset.from_tensor_slices(tensor).cache()
self.verifyRandomAccess(dataset, tensor)
@combinations.generate(test_base.default_test_combinations())
def testCacheTwoDimensionalElements(self):
tensor = [[1, 2], [3, 4]]
dataset = dataset_ops.Dataset.from_tensor_slices(tensor).cache()
self.verifyRandomAccess(dataset, tensor)
@combinations.generate(test_base.default_test_combinations())
def testCacheThreeComponents(self):
dataset = dataset_ops.Dataset.from_tensor_slices(
([1, 2], [3, 4], [5, 6])).cache()
expected = [(1, 3, 5), (2, 4, 6)]
self.verifyRandomAccess(dataset, expected)
@combinations.generate(test_base.default_test_combinations())
def testCacheInputDatasetNotRandomlyAccessible(self):
dataset = dataset_ops.Dataset.range(10)
initial_state = constant_op.constant(0, dtypes.int64)
scan_func = lambda state, i: (state + i, state + i)
dataset = dataset.scan(
initial_state=initial_state, scan_func=scan_func).cache()
expected = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
self.verifyRandomAccess(dataset, expected)
@combinations.generate(test_base.default_test_combinations())
def testCacheInputDatasetUnknownCardinality(self):
dataset = dataset_ops.Dataset.range(20).filter(
lambda x: math_ops.equal(x % 2, 0)).cache()
expected = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
self.verifyRandomAccess(dataset, expected)
@combinations.generate(test_base.default_test_combinations())
def testCacheInputDatasetInfiniteCardinality(self):
dataset = dataset_ops.Dataset.range(20).filter(
lambda x: math_ops.equal(x % 2, 0)).repeat(-1).cache()
expected = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 2]
# Since the dataset has infinite cardinality, random access with caching
# will cache through the requested index. In this case, random access
# with caching will cache through index 11.
self.verifyRandomAccessInfiniteCardinality(dataset, expected)
| CacheRandomAccessTest |
python | airbytehq__airbyte | airbyte-ci/connectors/ci_credentials/ci_credentials/google_api.py | {
"start": 244,
"end": 2649
} | class ____:
"""
Simple Google API client
"""
logger: ClassVar[Logger] = Logger()
config: Mapping[str, Any]
scopes: List[str]
_access_token: str = None
def get(self, url: str, params: Mapping = None) -> Mapping[str, Any]:
"""Sends a GET request"""
token = self.get_access_token()
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json", "X-Goog-User-Project": self.project_id}
# Making a get request
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
return response.json()
def post(self, url: str, json: Mapping = None, params: Mapping = None) -> Mapping[str, Any]:
"""Sends a POST request"""
token = self.get_access_token()
headers = {"Authorization": f"Bearer {token}", "X-Goog-User-Project": self.project_id}
# Making a get request
response = requests.post(url, headers=headers, json=json, params=params)
try:
response.raise_for_status()
except Exception:
self.logger.error(f"error body: {response.text}")
raise
return response.json()
@property
def token_uri(self):
return self.config["token_uri"]
@property
def project_id(self):
return self.config["project_id"]
def __generate_jwt(self) -> str:
"""Generates JWT token by a service account json file and scopes"""
now = int(time.time())
claim = {
"iat": now,
"iss": self.config["client_email"],
"scope": ",".join(self.scopes),
"aud": self.token_uri,
"exp": now + TOKEN_TTL,
}
return jwt.encode(claim, self.config["private_key"].encode(), algorithm="RS256")
def get_access_token(self) -> str:
"""Generates an access token by a service account json file and scopes"""
if self._access_token is None:
self._access_token = self.__get_access_token()
return self._access_token
def __get_access_token(self) -> str:
jwt = self.__generate_jwt()
resp = requests.post(
self.token_uri,
data={
"assertion": jwt,
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
},
)
return resp.json()["access_token"]
| GoogleApi |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 79965,
"end": 80533
} | class ____(
ScaledTMAConfigMixin, CUDAConfigHeuristic
):
"""Scaled TMA template heuristic for CUDA: epilogue scaling variants (TensorWise, RowWise)"""
def __init__(self) -> None:
super().__init__()
# Override mm_configs to use scaled_persistent_mm_configs for TMA
self.mm_configs = self.scaled_persistent_mm_configs
@register_template_heuristic(
scaled_mm_device_tma_main_loop_scaling_template.uid,
"cuda",
register=torch.version.hip is None,
op_name="scaled_mm",
)
| CUDAScaledTMAEpilogueScalingTemplateConfigHeuristic |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 863,
"end": 927
} | class ____(Aaaa): # trailing comment
pass
| TestTrailingComment1 |
python | GoogleCloudPlatform__python-docs-samples | functions/slack/main_test.py | {
"start": 1101,
"end": 3710
} | class ____:
def test_verify_signature_request_form_empty(self):
with pytest.raises(ValueError):
request = Request()
main.verify_signature(request)
def test_verify_signature_token_incorrect(self):
with pytest.raises(ValueError):
request = Request(headers={"X-Slack-Signature": "12345"})
main.verify_signature(request)
def test_verify_web_hook_valid_request(self):
request = Request()
request.body = ""
now = str(int(time.time()))
verifier = SignatureVerifier(os.environ["SLACK_SECRET"])
test_signature = verifier.generate_signature(timestamp=now, body="")
request.headers = {
"X-Slack-Request-Timestamp": now,
"X-Slack-Signature": test_signature,
}
main.verify_signature(request)
def test_format_slack_message(self):
message = main.format_slack_message("lion", example_response)
# Just make sure there's a result.
assert "title" in message["attachments"][0]
assert message["attachments"][0]["color"] == "#3367d6"
def test_make_search_request(self):
with mock.patch.object(main, "kgsearch"):
entities = main.kgsearch.entities.return_value
search = entities.search.return_value
search.execute.return_value = example_response
message = main.make_search_request("lion")
# Just make sure there's a result.
assert "title" in message["attachments"][0]
assert message["attachments"][0]["color"] == "#3367d6"
def test_kg_search(self):
with mock.patch.object(main, "kgsearch"):
entities = main.kgsearch.entities.return_value
search = entities.search.return_value
search.execute.return_value = example_response
request = Request()
request.form = {"text": "lion"}
request.data = json.dumps(request.form)
now = str(int(time.time()))
verifier = SignatureVerifier(os.environ["SLACK_SECRET"])
test_signature = verifier.generate_signature(
timestamp=now, body=request.data
)
request.method = "POST"
request.headers = {
"X-Slack-Request-Timestamp": now,
"X-Slack-Signature": test_signature,
}
with mock.patch("main.jsonify", side_effect=json.dumps):
response = main.kg_search(request)
assert "lion" in response.lower()
assert "color" in response.lower()
| TestGCFPySlackSample |
python | pypa__hatch | tests/backend/metadata/test_hatch.py | {
"start": 234,
"end": 956
} | class ____:
def test_default(self, isolation):
config = {}
metadata = HatchMetadata(str(isolation), config, None)
assert metadata.build_config == metadata.build_config == {}
def test_not_table(self, isolation):
config = {"build": 0}
metadata = HatchMetadata(str(isolation), config, None)
with pytest.raises(TypeError, match="Field `tool.hatch.build` must be a table"):
_ = metadata.build_config
def test_correct(self, isolation):
config = {"build": {"reproducible": True}}
metadata = HatchMetadata(str(isolation), config, None)
assert metadata.build_config == metadata.build_config == {"reproducible": True}
| TestBuildConfig |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/_execution.py | {
"start": 6816,
"end": 9592
} | class ____(BaseExecutionPolicy):
"""Launch the shell through the Codex CLI sandbox.
Ideal when you have the Codex CLI installed and want the additional syscall and
filesystem restrictions provided by Anthropic's Seatbelt (macOS) or Landlock/seccomp
(Linux) profiles. Commands still run on the host, but within the sandbox requested by
the CLI. If the Codex binary is unavailable or the runtime lacks the required
kernel features (e.g., Landlock inside some containers), process startup fails with a
`RuntimeError`.
Configure sandbox behavior via `config_overrides` to align with your Codex CLI
profile. This policy does not add its own resource limits; combine it with
host-level guards (cgroups, container resource limits) as needed.
"""
binary: str = "codex"
platform: typing.Literal["auto", "macos", "linux"] = "auto"
config_overrides: Mapping[str, typing.Any] = field(default_factory=dict)
def spawn(
self,
*,
workspace: Path,
env: Mapping[str, str],
command: Sequence[str],
) -> subprocess.Popen[str]:
full_command = self._build_command(command)
return _launch_subprocess(
full_command,
env=env,
cwd=workspace,
preexec_fn=None,
start_new_session=False,
)
def _build_command(self, command: Sequence[str]) -> list[str]:
binary = self._resolve_binary()
platform_arg = self._determine_platform()
full_command: list[str] = [binary, "sandbox", platform_arg]
for key, value in sorted(dict(self.config_overrides).items()):
full_command.extend(["-c", f"{key}={self._format_override(value)}"])
full_command.append("--")
full_command.extend(command)
return full_command
def _resolve_binary(self) -> str:
path = shutil.which(self.binary)
if path is None:
msg = (
"Codex sandbox policy requires the '%s' CLI to be installed and available on PATH."
)
raise RuntimeError(msg % self.binary)
return path
def _determine_platform(self) -> str:
if self.platform != "auto":
return self.platform
if sys.platform.startswith("linux"):
return "linux"
if sys.platform == "darwin":
return "macos"
msg = (
"Codex sandbox policy could not determine a supported platform; "
"set 'platform' explicitly."
)
raise RuntimeError(msg)
@staticmethod
def _format_override(value: typing.Any) -> str:
try:
return json.dumps(value)
except TypeError:
return str(value)
@dataclass
| CodexSandboxExecutionPolicy |
python | kamyu104__LeetCode-Solutions | Python/find-all-anagrams-in-a-string.py | {
"start": 29,
"end": 666
} | class ____(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
result = []
cnts = [0] * 26
for c in p:
cnts[ord(c) - ord('a')] += 1
left, right = 0, 0
while right < len(s):
cnts[ord(s[right]) - ord('a')] -= 1
while left <= right and cnts[ord(s[right]) - ord('a')] < 0:
cnts[ord(s[left]) - ord('a')] += 1
left += 1
if right - left + 1 == len(p):
result.append(left)
right += 1
return result
| Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1434768,
"end": 1438233
} | class ____(TopLevelParameter):
"""
TopLevelSelectionParameter schema wrapper.
Parameters
----------
name : str, :class:`ParameterName`
Required. A unique name for the selection parameter. Selection names should be valid
JavaScript identifiers: they should contain only alphanumeric characters (or "$", or
"_") and may not start with a digit. Reserved keywords that may not be used as
parameter names are "datum", "event", "item", and "parent".
select : dict, :class:`SelectionType`, :class:`PointSelectionConfig`, :class:`IntervalSelectionConfig`, Literal['point', 'interval']
Determines the default event processing and data query for the selection. Vega-Lite
currently supports two selection types:
* ``"point"`` -- to select multiple discrete data values; the first value is
selected on ``click`` and additional values toggled on shift-click.
* ``"interval"`` -- to select a continuous range of data values on ``drag``.
bind : dict, :class:`Binding`, :class:`BindInput`, :class:`BindRange`, :class:`BindDirect`, :class:`BindCheckbox`, :class:`LegendBinding`, :class:`BindRadioSelect`, Literal['legend', 'scales'], :class:`LegendStreamBinding`
When set, a selection is populated by input elements (also known as dynamic query
widgets) or by interacting with the corresponding legend. Direct manipulation
interaction is disabled by default; to re-enable it, set the selection's `on
<https://vega.github.io/vega-lite/docs/selection.html#common-selection-properties>`__
property.
Legend bindings are restricted to selections that only specify a single field or
encoding.
Query widget binding takes the form of Vega's `input element binding definition
<https://vega.github.io/vega/docs/signals/#bind>`__ or can be a mapping between
projected field/encodings and binding definitions.
**See also:** `bind <https://vega.github.io/vega-lite/docs/bind.html>`__
documentation.
value : str, bool, dict, float, :class:`DateTime`, :class:`SelectionInit`, :class:`PrimitiveValue`, :class:`SelectionInitIntervalMapping`, Sequence[dict, :class:`SelectionInitMapping`], None
Initialize the selection with a mapping between `projected channels or field names
<https://vega.github.io/vega-lite/docs/selection.html#project>`__ and initial
values.
**See also:** `init <https://vega.github.io/vega-lite/docs/value.html>`__
documentation.
views : Sequence[str]
By default, top-level selections are applied to every view in the visualization. If
this property is specified, selections will only be applied to views with the given
names.
"""
_schema = {"$ref": "#/definitions/TopLevelSelectionParameter"}
def __init__(
self,
name: Optional[str | SchemaBase] = Undefined,
select: Optional[SchemaBase | Map | SelectionType_T] = Undefined,
bind: Optional[SchemaBase | Literal["legend", "scales"] | Map] = Undefined,
value: Optional[
Temporal | SchemaBase | Sequence[SchemaBase | Map] | Map | PrimitiveValue_T
] = Undefined,
views: Optional[Sequence[str]] = Undefined,
**kwds,
):
super().__init__(
name=name, select=select, bind=bind, value=value, views=views, **kwds
)
| TopLevelSelectionParameter |
python | mlflow__mlflow | mlflow/gateway/config.py | {
"start": 14763,
"end": 15303
} | class ____(ResponseModel):
name: str | None = None
# Use `str` instead of `Provider` enum to allow gateway backends such as Databricks to
# support new providers without breaking the gateway client.
provider: str
_ROUTE_EXTRA_SCHEMA = {
"example": {
"name": "openai-completions",
"route_type": "llm/v1/completions",
"model": {
"name": "gpt-4o-mini",
"provider": "openai",
},
"route_url": "/gateway/routes/completions/invocations",
}
}
| EndpointModelInfo |
python | getsentry__sentry | tests/snuba/test_referrer.py | {
"start": 177,
"end": 3039
} | class ____(TestCase):
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_not_exist(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
assert not validate_referrer("does_not_exist")
assert warn_log.call_count == 1
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_dynamic_tsdb_model(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
for model in TSDBModel:
assert validate_referrer(f"tsdb-modelid:{model.value}")
assert warn_log.call_count == 0
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_tsdb_model_with_suffix(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
assert validate_referrer("tsdb-modelid:300.user_count_snoozes")
assert warn_log.call_count == 0
assert validate_referrer("tsdb-modelid:4.frequency_snoozes")
assert warn_log.call_count == 0
# tsdb-modelid:4 doesn't use the `user_count_snoozes` suffix
assert not validate_referrer("tsdb-modelid:4.user_count_snoozes")
assert warn_log.call_count == 1
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_common_suffixes(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
assert validate_referrer("api.insights.http.domain-summary-transactions-list")
assert validate_referrer("api.insights.http.domain-summary-transactions-list.primary")
assert validate_referrer("api.insights.http.domain-summary-transactions-list.secondary")
assert warn_log.call_count == 0
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_uncommon_suffixes(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
assert not validate_referrer("api.insights.http.domain-summary-transactions-list.special")
assert not validate_referrer("api.insights.http.domain-summary-transactions-list.airyrpm")
assert warn_log.call_count == 2
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_tsdb_models(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
for model in TSDBModel:
assert hasattr(Referrer, f"TSDB_MODELID_{model.value}")
assert (
getattr(Referrer, f"TSDB_MODELID_{model.value}").value
== f"tsdb-modelid:{model.value}"
)
assert warn_log.call_count == 0
@patch("sentry.snuba.referrer.logger.warning")
def test_referrer_validate_base_enum_values(self, warn_log: MagicMock) -> None:
assert warn_log.call_count == 0
for i in Referrer:
assert validate_referrer(i.value)
assert warn_log.call_count == 0
| ReferrerTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 193791,
"end": 217070
} | class ____(Request):
"""
Edit task's details.
:param task: ID of the task
:type task: str
:param force: If not true, call fails if the task status is not 'created'
:type force: bool
:param name: Task name Unique within the company.
:type name: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param type: Type of task
:type type: TaskTypeEnum
:param comment: Free text comment
:type comment: str
:param parent: Parent task id Must be a completed task.
:type parent: str
:param project: Project ID of the project to which this task is assigned Must
exist[ab]
:type project: str
:param output_dest: Output storage id Must be a reference to an existing
storage.
:type output_dest: str
:param execution: Task execution params
:type execution: Execution
:param script: Script info
:type script: Script
:param hyperparams: Task hyper params per section
:type hyperparams: dict
:param configuration: Task configuration params
:type configuration: dict
:param models: Task models
:type models: TaskModels
:param container: Docker container parameters
:type container: dict
:param runtime: Task runtime mapping
:type runtime: dict
"""
_service = "tasks"
_action = "edit"
_version = "2.13"
_schema = {
"definitions": {
"artifact": {
"properties": {
"content_size": {
"description": "Raw data length in bytes",
"type": "integer",
},
"display_data": {
"description": "User-defined list of key/value pairs, sorted",
"items": {"items": {"type": "string"}, "type": "array"},
"type": "array",
},
"hash": {
"description": "Hash of entire raw data",
"type": "string",
},
"key": {"description": "Entry key", "type": "string"},
"mode": {
"$ref": "#/definitions/artifact_mode_enum",
"description": "System defined input/output indication",
},
"timestamp": {
"description": "Epoch time when artifact was created",
"type": "integer",
},
"type": {"description": "System defined type", "type": "string"},
"type_data": {
"$ref": "#/definitions/artifact_type_data",
"description": "Additional fields defined by the system",
},
"uri": {"description": "Raw data location", "type": "string"},
},
"required": ["key", "type"],
"type": "object",
},
"artifact_mode_enum": {
"default": "output",
"enum": ["input", "output"],
"type": "string",
},
"artifact_type_data": {
"properties": {
"content_type": {
"description": "System defined raw data content type",
"type": ["string", "null"],
},
"data_hash": {
"description": "Hash of raw data, without any headers or descriptive parts",
"type": ["string", "null"],
},
"preview": {
"description": "Description or textual data",
"type": ["string", "null"],
},
},
"type": "object",
},
"configuration_item": {
"properties": {
"description": {
"description": "The parameter description. Optional",
"type": ["string", "null"],
},
"name": {
"description": "Name of the parameter. Should be unique",
"type": ["string", "null"],
},
"type": {
"description": "Type of the parameter. Optional",
"type": ["string", "null"],
},
"value": {
"description": "Value of the parameter",
"type": ["string", "null"],
},
},
"type": "object",
},
"execution": {
"properties": {
"artifacts": {
"description": "Task artifacts",
"items": {"$ref": "#/definitions/artifact"},
"type": ["array", "null"],
},
"framework": {
"description": "Framework related to the task. Case insensitive. Mandatory for Training tasks. ",
"type": ["string", "null"],
},
"model_desc": {
"additionalProperties": True,
"description": "Json object representing the Model descriptors",
"type": ["object", "null"],
},
"model_labels": {
"additionalProperties": {"type": "integer"},
"description": "Json object representing the ids of the labels in the model.\n The keys are the layers' names and the values are the IDs.\n Not applicable for Register (Import) tasks.\n Mandatory for Training tasks",
"type": ["object", "null"],
},
"parameters": {
"additionalProperties": True,
"description": "Json object containing the Task parameters",
"type": ["object", "null"],
},
"queue": {
"description": "Queue ID where task was queued.",
"type": ["string", "null"],
},
},
"type": "object",
},
"params_item": {
"properties": {
"description": {
"description": "The parameter description. Optional",
"type": ["string", "null"],
},
"name": {
"description": "Name of the parameter. The combination of section and name should be unique",
"type": ["string", "null"],
},
"section": {
"description": "Section that the parameter belongs to",
"type": ["string", "null"],
},
"type": {
"description": "Type of the parameter. Optional",
"type": ["string", "null"],
},
"value": {
"description": "Value of the parameter",
"type": ["string", "null"],
},
},
"type": "object",
},
"script": {
"properties": {
"binary": {
"default": "python",
"description": "Binary to use when running the script",
"type": ["string", "null"],
},
"branch": {
"description": "Repository branch id If not provided and tag not provided, default repository branch is used.",
"type": ["string", "null"],
},
"diff": {
"description": "Uncommitted changes found in the repository when task was run",
"type": ["string", "null"],
},
"entry_point": {
"description": "Path to execute within the repository",
"type": ["string", "null"],
},
"repository": {
"description": "Name of the repository where the script is located",
"type": ["string", "null"],
},
"requirements": {
"description": "A JSON object containing requirements strings by key",
"type": ["object", "null"],
},
"tag": {
"description": "Repository tag",
"type": ["string", "null"],
},
"version_num": {
"description": "Version (changeset) number. Optional (default is head version) Unused if tag is provided.",
"type": ["string", "null"],
},
"working_dir": {
"description": "Path to the folder from which to run the script Default - root folder of repository",
"type": ["string", "null"],
},
},
"type": "object",
},
"section_params": {
"additionalProperties": {"$ref": "#/definitions/params_item"},
"description": "Task section params",
"type": "object",
},
"task_model_item": {
"properties": {
"model": {"description": "The model ID", "type": "string"},
"name": {"description": "The task model name", "type": "string"},
},
"required": ["name", "model"],
"type": "object",
},
"task_models": {
"properties": {
"input": {
"description": "The list of task input models",
"items": {"$ref": "#/definitions/task_model_item"},
"type": ["array", "null"],
},
"output": {
"description": "The list of task output models",
"items": {"$ref": "#/definitions/task_model_item"},
"type": ["array", "null"],
},
},
"type": "object",
},
"task_type_enum": {
"enum": [
"training",
"testing",
"inference",
"data_processing",
"application",
"monitor",
"controller",
"optimizer",
"service",
"qc",
"custom",
],
"type": "string",
},
},
"properties": {
"comment": {"description": "Free text comment ", "type": "string"},
"configuration": {
"additionalProperties": {"$ref": "#/definitions/configuration_item"},
"description": "Task configuration params",
"type": "object",
},
"container": {
"type": "object",
"description": "Docker container parameters",
"additionalProperties": {"type": ["string", "null"]},
},
"execution": {
"$ref": "#/definitions/execution",
"description": "Task execution params",
},
"force": {
"default": False,
"description": "If not true, call fails if the task status is not 'created'",
"type": "boolean",
},
"hyperparams": {
"additionalProperties": {"$ref": "#/definitions/section_params"},
"description": "Task hyper params per section",
"type": "object",
},
"models": {
"$ref": "#/definitions/task_models",
"description": "Task models",
},
"name": {
"description": "Task name Unique within the company.",
"type": "string",
},
"output_dest": {
"description": "Output storage id Must be a reference to an existing storage.",
"type": "string",
},
"parent": {
"description": "Parent task id Must be a completed task.",
"type": "string",
},
"project": {
"description": "Project ID of the project to which this task is assigned Must exist[ab]",
"type": "string",
},
"runtime": {
"description": "Task runtime mapping",
"type": ["object", "null"],
"additionalProperties": True,
},
"script": {"$ref": "#/definitions/script", "description": "Script info"},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
"task": {"description": "ID of the task", "type": "string"},
"type": {
"$ref": "#/definitions/task_type_enum",
"description": "Type of task",
},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
force: Optional[bool] = False,
name: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
type: Any = None,
comment: Optional[str] = None,
parent: Optional[str] = None,
project: Optional[str] = None,
output_dest: Optional[str] = None,
execution: Any = None,
script: Any = None,
hyperparams: Optional[dict] = None,
configuration: Optional[dict] = None,
models: Any = None,
container: Optional[dict] = None,
runtime: Optional[dict] = None,
**kwargs: Any
) -> None:
super(EditRequest, self).__init__(**kwargs)
self.task = task
self.force = force
self.name = name
self.tags = tags
self.system_tags = system_tags
self.type = type
self.comment = comment
self.parent = parent
self.project = project
self.output_dest = output_dest
self.execution = execution
self.script = script
self.hyperparams = hyperparams
self.configuration = configuration
self.models = models
self.container = container
self.runtime = runtime
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("force")
def force(self) -> Optional[bool]:
return self._property_force
@force.setter
def force(self, value: Optional[bool]) -> None:
if value is None:
self._property_force = None
return
self.assert_isinstance(value, "force", (bool,))
self._property_force = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("type")
def type(self) -> Any:
return self._property_type
@type.setter
def type(self, value: Any) -> None:
if value is None:
self._property_type = None
return
if isinstance(value, six.string_types):
try:
value = TaskTypeEnum(value)
except ValueError:
pass
else:
self.assert_isinstance(value, "type", enum.Enum)
self._property_type = value
@schema_property("comment")
def comment(self) -> Optional[str]:
return self._property_comment
@comment.setter
def comment(self, value: Optional[str]) -> None:
if value is None:
self._property_comment = None
return
self.assert_isinstance(value, "comment", six.string_types)
self._property_comment = value
@schema_property("parent")
def parent(self) -> Optional[str]:
return self._property_parent
@parent.setter
def parent(self, value: Optional[str]) -> None:
if value is None:
self._property_parent = None
return
self.assert_isinstance(value, "parent", six.string_types)
self._property_parent = value
@schema_property("project")
def project(self) -> Optional[str]:
return self._property_project
@project.setter
def project(self, value: Optional[str]) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("output_dest")
def output_dest(self) -> Optional[str]:
return self._property_output_dest
@output_dest.setter
def output_dest(self, value: Optional[str]) -> None:
if value is None:
self._property_output_dest = None
return
self.assert_isinstance(value, "output_dest", six.string_types)
self._property_output_dest = value
@schema_property("execution")
def execution(self) -> Any:
return self._property_execution
@execution.setter
def execution(self, value: Any) -> None:
if value is None:
self._property_execution = None
return
if isinstance(value, dict):
value = Execution.from_dict(value)
else:
self.assert_isinstance(value, "execution", Execution)
self._property_execution = value
@schema_property("hyperparams")
def hyperparams(self) -> Optional[dict]:
return self._property_hyperparams
@hyperparams.setter
def hyperparams(self, value: Optional[dict]) -> None:
if value is None:
self._property_hyperparams = None
return
self.assert_isinstance(value, "hyperparams", dict)
self.assert_isinstance(value.keys(), "hyperparams_keys", six.string_types, is_array=True)
self.assert_isinstance(value.values(), "hyperparams_values", (SectionParams, dict), is_array=True)
value = dict(((k, SectionParams(**v) if isinstance(v, dict) else v) for (k, v) in value.items()))
self._property_hyperparams = value
@schema_property("configuration")
def configuration(self) -> Optional[dict]:
return self._property_configuration
@configuration.setter
def configuration(self, value: Optional[dict]) -> None:
if value is None:
self._property_configuration = None
return
self.assert_isinstance(value, "configuration", dict)
self.assert_isinstance(value.keys(), "configuration_keys", six.string_types, is_array=True)
self.assert_isinstance(
value.values(),
"configuration_values",
(ConfigurationItem, dict),
is_array=True,
)
value = dict(((k, ConfigurationItem(**v) if isinstance(v, dict) else v) for (k, v) in value.items()))
self._property_configuration = value
@schema_property("script")
def script(self) -> Any:
return self._property_script
@script.setter
def script(self, value: Any) -> None:
if value is None:
self._property_script = None
return
if isinstance(value, dict):
value = Script.from_dict(value)
else:
self.assert_isinstance(value, "script", Script)
self._property_script = value
@schema_property("models")
def models(self) -> Any:
return self._property_models
@models.setter
def models(self, value: Any) -> None:
if value is None:
self._property_models = None
return
if isinstance(value, dict):
value = TaskModels.from_dict(value)
else:
self.assert_isinstance(value, "models", TaskModels)
self._property_models = value
@schema_property("container")
def container(self) -> Optional[dict]:
return self._property_container
@container.setter
def container(self, value: Optional[dict]) -> None:
if value is None:
self._property_container = None
return
self.assert_isinstance(value, "container", dict)
self._property_container = value
@schema_property("runtime")
def runtime(self) -> Optional[dict]:
return self._property_runtime
@runtime.setter
def runtime(self, value: Optional[dict]) -> None:
if value is None:
self._property_runtime = None
return
self.assert_isinstance(value, "runtime", dict)
self._property_runtime = value
| EditRequest |
python | numba__numba | numba/tests/test_typeof.py | {
"start": 1156,
"end": 1397
} | class ____(object):
@property
def _numba_type_(self):
"""
Magic attribute expected by Numba to get the numba type that
represents this object.
"""
return types.UniTuple(types.boolean, 42)
| Custom |
python | numpy__numpy | numpy/lib/_iotools.py | {
"start": 6223,
"end": 12872
} | class ____:
"""
Object to validate a list of strings to use as field names.
The strings are stripped of any non alphanumeric character, and spaces
are replaced by '_'. During instantiation, the user can define a list
of names to exclude, as well as a list of invalid characters. Names in
the exclusion list are appended a '_' character.
Once an instance has been created, it can be called with a list of
names, and a list of valid names will be created. The `__call__`
method accepts an optional keyword "default" that sets the default name
in case of ambiguity. By default this is 'f', so that names will
default to `f0`, `f1`, etc.
Parameters
----------
excludelist : sequence, optional
A list of names to exclude. This list is appended to the default
list ['return', 'file', 'print']. Excluded names are appended an
underscore: for example, `file` becomes `file_` if supplied.
deletechars : str, optional
A string combining invalid characters that must be deleted from the
names.
case_sensitive : {True, False, 'upper', 'lower'}, optional
* If True, field names are case-sensitive.
* If False or 'upper', field names are converted to upper case.
* If 'lower', field names are converted to lower case.
The default value is True.
replace_space : '_', optional
Character(s) used in replacement of white spaces.
Notes
-----
Calling an instance of `NameValidator` is the same as calling its
method `validate`.
Examples
--------
>>> import numpy as np
>>> validator = np.lib._iotools.NameValidator()
>>> validator(['file', 'field2', 'with space', 'CaSe'])
('file_', 'field2', 'with_space', 'CaSe')
>>> validator = np.lib._iotools.NameValidator(excludelist=['excl'],
... deletechars='q',
... case_sensitive=False)
>>> validator(['excl', 'field2', 'no_q', 'with space', 'CaSe'])
('EXCL', 'FIELD2', 'NO_Q', 'WITH_SPACE', 'CASE')
"""
defaultexcludelist = 'return', 'file', 'print'
defaultdeletechars = frozenset(r"""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
def __init__(self, excludelist=None, deletechars=None,
case_sensitive=None, replace_space='_'):
# Process the exclusion list ..
if excludelist is None:
excludelist = []
excludelist.extend(self.defaultexcludelist)
self.excludelist = excludelist
# Process the list of characters to delete
if deletechars is None:
delete = set(self.defaultdeletechars)
else:
delete = set(deletechars)
delete.add('"')
self.deletechars = delete
# Process the case option .....
if (case_sensitive is None) or (case_sensitive is True):
self.case_converter = lambda x: x
elif (case_sensitive is False) or case_sensitive.startswith('u'):
self.case_converter = lambda x: x.upper()
elif case_sensitive.startswith('l'):
self.case_converter = lambda x: x.lower()
else:
msg = f'unrecognized case_sensitive value {case_sensitive}.'
raise ValueError(msg)
self.replace_space = replace_space
def validate(self, names, defaultfmt="f%i", nbfields=None):
"""
Validate a list of strings as field names for a structured array.
Parameters
----------
names : sequence of str
Strings to be validated.
defaultfmt : str, optional
Default format string, used if validating a given string
reduces its length to zero.
nbfields : integer, optional
Final number of validated names, used to expand or shrink the
initial list of names.
Returns
-------
validatednames : list of str
The list of validated field names.
Notes
-----
A `NameValidator` instance can be called directly, which is the
same as calling `validate`. For examples, see `NameValidator`.
"""
# Initial checks ..............
if (names is None):
if (nbfields is None):
return None
names = []
if isinstance(names, str):
names = [names, ]
if nbfields is not None:
nbnames = len(names)
if (nbnames < nbfields):
names = list(names) + [''] * (nbfields - nbnames)
elif (nbnames > nbfields):
names = names[:nbfields]
# Set some shortcuts ...........
deletechars = self.deletechars
excludelist = self.excludelist
case_converter = self.case_converter
replace_space = self.replace_space
# Initializes some variables ...
validatednames = []
seen = {}
nbempty = 0
for item in names:
item = case_converter(item).strip()
if replace_space:
item = item.replace(' ', replace_space)
item = ''.join([c for c in item if c not in deletechars])
if item == '':
item = defaultfmt % nbempty
while item in names:
nbempty += 1
item = defaultfmt % nbempty
nbempty += 1
elif item in excludelist:
item += '_'
cnt = seen.get(item, 0)
if cnt > 0:
validatednames.append(item + '_%d' % cnt)
else:
validatednames.append(item)
seen[item] = cnt + 1
return tuple(validatednames)
def __call__(self, names, defaultfmt="f%i", nbfields=None):
return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields)
def str2bool(value):
"""
Tries to transform a string supposed to represent a boolean to a boolean.
Parameters
----------
value : str
The string that is transformed to a boolean.
Returns
-------
boolval : bool
The boolean representation of `value`.
Raises
------
ValueError
If the string is not 'True' or 'False' (case independent)
Examples
--------
>>> import numpy as np
>>> np.lib._iotools.str2bool('TRUE')
True
>>> np.lib._iotools.str2bool('false')
False
"""
value = value.upper()
if value == 'TRUE':
return True
elif value == 'FALSE':
return False
else:
raise ValueError("Invalid boolean")
| NameValidator |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 72247,
"end": 76199
} | class ____(TestCase):
rtol = 1e-5
atol = 1e-8
def _setup(self):
atol = self.atol
rtol = self.rtol
arr = np.array([100, 1000])
aran = np.arange(125).reshape((5, 5, 5))
self.all_close_tests = [
([1, 0], [1, 0]),
([atol], [0]),
([1], [1 + rtol + atol]),
(arr, arr + arr * rtol),
(arr, arr + arr * rtol + atol),
(aran, aran + aran * rtol),
(np.inf, np.inf),
(np.inf, [np.inf]),
([np.inf, -np.inf], [np.inf, -np.inf]),
]
self.none_close_tests = [
([np.inf, 0], [1, np.inf]),
([np.inf, -np.inf], [1, 0]),
([np.inf, np.inf], [1, -np.inf]),
([np.inf, np.inf], [1, 0]),
([np.nan, 0], [np.nan, -np.inf]),
([atol * 2], [0]),
([1], [1 + rtol + atol * 2]),
(aran, aran + rtol * 1.1 * aran + atol * 1.1),
(np.array([np.inf, 1]), np.array([0, np.inf])),
]
self.some_close_tests = [
([np.inf, 0], [np.inf, atol * 2]),
([atol, 1, 1e6 * (1 + 2 * rtol) + atol], [0, np.nan, 1e6]),
(np.arange(3), [0, 1, 2.1]),
(np.nan, [np.nan, np.nan, np.nan]),
([0], [atol, np.inf, -np.inf, np.nan]),
(0, [atol, np.inf, -np.inf, np.nan]),
]
self.some_close_results = [
[True, False],
[True, False, False],
[True, True, False],
[False, False, False],
[True, False, False, False],
[True, False, False, False],
]
def test_ip_isclose(self):
self._setup()
tests = self.some_close_tests
results = self.some_close_results
for (x, y), result in zip(tests, results):
assert_array_equal(np.isclose(x, y), result)
def tst_all_isclose(self, x, y):
assert_(np.all(np.isclose(x, y)), f"{x} and {y} not close")
def tst_none_isclose(self, x, y):
msg = "%s and %s shouldn't be close"
assert_(not np.any(np.isclose(x, y)), msg % (x, y))
def tst_isclose_allclose(self, x, y):
msg = "isclose.all() and allclose aren't same for %s and %s"
msg2 = "isclose and allclose aren't same for %s and %s"
if np.isscalar(x) and np.isscalar(y):
assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y))
else:
assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y))
def test_ip_all_isclose(self):
self._setup()
for x, y in self.all_close_tests:
self.tst_all_isclose(x, y)
def test_ip_none_isclose(self):
self._setup()
for x, y in self.none_close_tests:
self.tst_none_isclose(x, y)
def test_ip_isclose_allclose(self):
self._setup()
tests = self.all_close_tests + self.none_close_tests + self.some_close_tests
for x, y in tests:
self.tst_isclose_allclose(x, y)
def test_equal_nan(self):
assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True])
arr = np.array([1.0, np.nan])
assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True])
@xfailIfTorchDynamo # scalars vs 0D
def test_scalar_return(self):
assert_(np.isscalar(np.isclose(1, 1)))
def test_no_parameter_modification(self):
x = np.array([np.inf, 1])
y = np.array([0, np.inf])
np.isclose(x, y)
assert_array_equal(x, np.array([np.inf, 1]))
assert_array_equal(y, np.array([0, np.inf]))
def test_non_finite_scalar(self):
# GH7014, when two scalars are compared the output should also be a
# scalar
# XXX: test modified since there are array scalars
assert_(np.isclose(np.inf, -np.inf).item() is False)
assert_(np.isclose(0, np.inf).item() is False)
| TestIsclose |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/neuroevolution.py | {
"start": 80,
"end": 6006
} | class ____():
""" Evolutionary optimization of Neural Networks.
Parameters:
-----------
n_individuals: int
The number of neural networks that are allowed in the population at a time.
mutation_rate: float
The probability that a weight will be mutated.
model_builder: method
A method which returns a user specified NeuralNetwork instance.
"""
def __init__(self, population_size, mutation_rate, model_builder):
self.population_size = population_size
self.mutation_rate = mutation_rate
self.model_builder = model_builder
def _build_model(self, id):
""" Returns a new individual """
model = self.model_builder(n_inputs=self.X.shape[1], n_outputs=self.y.shape[1])
model.id = id
model.fitness = 0
model.accuracy = 0
return model
def _initialize_population(self):
""" Initialization of the neural networks forming the population"""
self.population = []
for _ in range(self.population_size):
model = self._build_model(id=np.random.randint(1000))
self.population.append(model)
def _mutate(self, individual, var=1):
""" Add zero mean gaussian noise to the layer weights with probability mutation_rate """
for layer in individual.layers:
if hasattr(layer, 'W'):
# Mutation of weight with probability self.mutation_rate
mutation_mask = np.random.binomial(1, p=self.mutation_rate, size=layer.W.shape)
layer.W += np.random.normal(loc=0, scale=var, size=layer.W.shape) * mutation_mask
mutation_mask = np.random.binomial(1, p=self.mutation_rate, size=layer.w0.shape)
layer.w0 += np.random.normal(loc=0, scale=var, size=layer.w0.shape) * mutation_mask
return individual
def _inherit_weights(self, child, parent):
""" Copies the weights from parent to child """
for i in range(len(child.layers)):
if hasattr(child.layers[i], 'W'):
# The child inherits both weights W and bias weights w0
child.layers[i].W = parent.layers[i].W.copy()
child.layers[i].w0 = parent.layers[i].w0.copy()
def _crossover(self, parent1, parent2):
""" Performs crossover between the neurons in parent1 and parent2 to form offspring """
child1 = self._build_model(id=parent1.id+1)
self._inherit_weights(child1, parent1)
child2 = self._build_model(id=parent2.id+1)
self._inherit_weights(child2, parent2)
# Perform crossover
for i in range(len(child1.layers)):
if hasattr(child1.layers[i], 'W'):
n_neurons = child1.layers[i].W.shape[1]
# Perform crossover between the individuals' neuron weights
cutoff = np.random.randint(0, n_neurons)
child1.layers[i].W[:, cutoff:] = parent2.layers[i].W[:, cutoff:].copy()
child1.layers[i].w0[:, cutoff:] = parent2.layers[i].w0[:, cutoff:].copy()
child2.layers[i].W[:, cutoff:] = parent1.layers[i].W[:, cutoff:].copy()
child2.layers[i].w0[:, cutoff:] = parent1.layers[i].w0[:, cutoff:].copy()
return child1, child2
def _calculate_fitness(self):
""" Evaluate the NNs on the test set to get fitness scores """
for individual in self.population:
loss, acc = individual.test_on_batch(self.X, self.y)
individual.fitness = 1 / (loss + 1e-8)
individual.accuracy = acc
def evolve(self, X, y, n_generations):
""" Will evolve the population for n_generations based on dataset X and labels y"""
self.X, self.y = X, y
self._initialize_population()
# The 40% highest fittest individuals will be selected for the next generation
n_winners = int(self.population_size * 0.4)
# The fittest 60% of the population will be selected as parents to form offspring
n_parents = self.population_size - n_winners
for epoch in range(n_generations):
# Determine the fitness of the individuals in the population
self._calculate_fitness()
# Sort population by fitness
sorted_i = np.argsort([model.fitness for model in self.population])[::-1]
self.population = [self.population[i] for i in sorted_i]
# Get the individual with the highest fitness
fittest_individual = self.population[0]
print ("[%d Best Individual - Fitness: %.5f, Accuracy: %.1f%%]" % (epoch,
fittest_individual.fitness,
float(100*fittest_individual.accuracy)))
# The 'winners' are selected for the next generation
next_population = [self.population[i] for i in range(n_winners)]
total_fitness = np.sum([model.fitness for model in self.population])
# The probability that a individual will be selected as a parent is proportionate to its fitness
parent_probabilities = [model.fitness / total_fitness for model in self.population]
# Select parents according to probabilities (without replacement to preserve diversity)
parents = np.random.choice(self.population, size=n_parents, p=parent_probabilities, replace=False)
for i in np.arange(0, len(parents), 2):
# Perform crossover to produce offspring
child1, child2 = self._crossover(parents[i], parents[i+1])
# Save mutated offspring for next population
next_population += [self._mutate(child1), self._mutate(child2)]
self.population = next_population
return fittest_individual
| Neuroevolution |
python | walkccc__LeetCode | solutions/426. Convert Binary Search Tree to Sorted Doubly Linked List/426.py | {
"start": 0,
"end": 723
} | class ____:
def treeToDoublyList(self, root: 'Node | None') -> 'Node | None':
if not root:
return None
leftHead = self.treeToDoublyList(root.left)
rightHead = self.treeToDoublyList(root.right)
root.left = root
root.right = root
return self._connect(self._connect(leftHead, root), rightHead)
def _connect(self, node1: 'Node | None', node2: 'Node | None') -> 'Node | None':
if not node1:
return node2
if not node2:
return node1
tail1 = node1.left
tail2 = node2.left
# Connect node1's tail with node2.
tail1.right = node2
node2.left = tail1
# Connect node2's tail with node1.
tail2.right = node1
node1.left = tail2
return node1
| Solution |
python | nedbat__coveragepy | tests/test_misc.py | {
"start": 1853,
"end": 3738
} | class ____(CoverageTest):
"""Tests of misc.file_be_gone."""
def test_remove_nonexistent_file(self) -> None:
# It's OK to try to remove a file that doesn't exist.
file_be_gone("not_here.txt")
def test_remove_actual_file(self) -> None:
# It really does remove a file that does exist.
self.make_file("here.txt", "We are here, we are here, we are here!")
file_be_gone("here.txt")
self.assert_doesnt_exist("here.txt")
def test_actual_errors(self) -> None:
# Errors can still happen.
# ". is a directory" on Unix, or "Access denied" on Windows
with pytest.raises(OSError):
file_be_gone(".")
VARS = {
"FOO": "fooey",
"BAR": "xyzzy",
}
@pytest.mark.parametrize(
"before, after",
[
("Nothing to do", "Nothing to do"),
("Dollar: $$", "Dollar: $"),
("Simple: $FOO is fooey", "Simple: fooey is fooey"),
("Braced: X${FOO}X.", "Braced: XfooeyX."),
("Missing: x${NOTHING}y is xy", "Missing: xy is xy"),
("Multiple: $$ $FOO $BAR ${FOO}", "Multiple: $ fooey xyzzy fooey"),
("Ill-formed: ${%5} ${{HI}} ${", "Ill-formed: ${%5} ${{HI}} ${"),
("Strict: ${FOO?} is there", "Strict: fooey is there"),
("Defaulted: ${WUT-missing}!", "Defaulted: missing!"),
("Defaulted empty: ${WUT-}!", "Defaulted empty: !"),
],
)
def test_substitute_variables(before: str, after: str) -> None:
assert substitute_variables(before, VARS) == after
@pytest.mark.parametrize(
"text",
[
"Strict: ${NOTHING?} is an error",
],
)
def test_substitute_variables_errors(text: str) -> None:
with pytest.raises(CoverageException) as exc_info:
substitute_variables(text, VARS)
assert text in str(exc_info.value)
assert "Variable NOTHING is undefined" in str(exc_info.value)
| RemoveFileTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/lichess/views.py | {
"start": 287,
"end": 2047
} | class ____(OAuth2Adapter):
provider_id = "lichess"
settings = app_settings.PROVIDERS.get(provider_id, {})
provider_base_url = settings.get("API_URL", "https://lichess.org")
access_token_url = f"{provider_base_url}/api/token"
authorize_url = f"{provider_base_url}/oauth"
profile_url = f"{provider_base_url}/api/account"
email_address_url = f"{provider_base_url}/api/account/email"
def complete_login(self, request, app, token, response):
profile_res = (
get_adapter()
.get_requests_session()
.get(
self.profile_url,
params={"access_token": token.token},
headers={"Authorization": f"Bearer {token.token}"},
)
)
profile_res.raise_for_status()
extra_data = profile_res.json()
user_profile = extra_data["result"] if "result" in extra_data else extra_data
# retrieve email address if requested
if QUERY_EMAIL:
email_data = (
get_adapter()
.get_requests_session()
.get(
self.email_address_url,
headers={"Authorization": f"Bearer {token.token}"},
)
)
email_data.raise_for_status()
email_data = email_data.json()
# extract email address from response
email = email_data.get("email", None)
if email:
user_profile["email"] = email
return self.get_provider().sociallogin_from_response(request, user_profile)
oauth2_login = OAuth2LoginView.adapter_view(LichessOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(LichessOAuth2Adapter)
| LichessOAuth2Adapter |
python | Textualize__textual | docs/examples/guide/styles/padding02.py | {
"start": 401,
"end": 755
} | class ____(App):
def compose(self) -> ComposeResult:
self.widget = Static(TEXT)
yield self.widget
def on_mount(self) -> None:
self.widget.styles.background = "purple"
self.widget.styles.width = 30
self.widget.styles.padding = (2, 4)
if __name__ == "__main__":
app = PaddingApp()
app.run()
| PaddingApp |
python | walkccc__LeetCode | solutions/1707. Maximum XOR With an Element From Array/1707.py | {
"start": 36,
"end": 130
} | class ____:
def __init__(self):
self.children: list[TrieNode | None] = [None] * 2
| TrieNode |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 247993,
"end": 249126
} | class ____(Response):
"""
Response of tasks.get_hyper_params endpoint.
:param params: Hyper parameters (keyed by task ID)
:type params: dict
"""
_service = "tasks"
_action = "get_hyper_params"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"params": {
"description": "Hyper parameters (keyed by task ID)",
"type": "array",
"items": {"type": "object"},
}
},
"type": "object",
}
def __init__(self, params: Optional[List[dict]] = None, **kwargs: Any) -> None:
super(GetHyperParamsResponse, self).__init__(**kwargs)
self.params = params
@schema_property("params")
def params(self) -> Optional[List[dict]]:
return self._property_params
@params.setter
def params(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_params = None
return
self.assert_isinstance(value, "params", (dict,), is_array=True)
self._property_params = list(value)
| GetHyperParamsResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor25.py | {
"start": 580,
"end": 765
} | class ____(Generic[T]):
def __init__(self, thing: T):
pass
@staticmethod
def method1(val: T) -> "B[T]":
# This should generate an error.
return B(0)
| B |
python | plotly__plotly.py | plotly/graph_objs/isosurface/_contour.py | {
"start": 233,
"end": 3513
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface"
_path_str = "isosurface.contour"
_valid_props = {"color", "show", "width"}
@property
def color(self):
"""
Sets the color of the contour lines.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def show(self):
"""
Sets whether or not dynamic contours are shown on hover
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["show"]
@show.setter
def show(self, val):
self["show"] = val
@property
def width(self):
"""
Sets the width of the contour lines.
The 'width' property is a number and may be specified as:
- An int or float in the interval [1, 16]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the color of the contour lines.
show
Sets whether or not dynamic contours are shown on hover
width
Sets the width of the contour lines.
"""
def __init__(self, arg=None, color=None, show=None, width=None, **kwargs):
"""
Construct a new Contour object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.Contour`
color
Sets the color of the contour lines.
show
Sets whether or not dynamic contours are shown on hover
width
Sets the width of the contour lines.
Returns
-------
Contour
"""
super().__init__("contour")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.isosurface.Contour
constructor must be a dict or
an instance of :class:`plotly.graph_objs.isosurface.Contour`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("show", arg, show)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Contour |
python | ray-project__ray | rllib/algorithms/sac/tests/test_sac.py | {
"start": 1481,
"end": 5874
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
np.random.seed(42)
torch.manual_seed(42)
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_sac_compilation(self):
"""Test whether SAC can be built and trained."""
config = (
sac.SACConfig()
.training(
n_step=3,
twin_q=True,
replay_buffer_config={
"capacity": 40000,
},
num_steps_sampled_before_learning_starts=0,
store_buffer_in_checkpoints=True,
train_batch_size=10,
)
.env_runners(
env_to_module_connector=(
lambda env, spaces, device: FlattenObservations()
),
num_env_runners=0,
rollout_fragment_length=10,
)
)
num_iterations = 1
image_space = Box(-1.0, 1.0, shape=(84, 84, 3))
simple_space = Box(-1.0, 1.0, shape=(3,))
tune.register_env(
"random_dict_env",
lambda _: RandomEnv(
{
"observation_space": Dict(
{
"a": simple_space,
"b": Discrete(2),
"c": image_space,
}
),
"action_space": Box(-1.0, 1.0, shape=(1,)),
}
),
)
tune.register_env(
"random_tuple_env",
lambda _: RandomEnv(
{
"observation_space": Tuple(
[simple_space, Discrete(2), image_space]
),
"action_space": Box(-1.0, 1.0, shape=(1,)),
}
),
)
# Test for different env types (discrete w/ and w/o image, + cont).
for env in [
"random_dict_env",
"random_tuple_env",
]:
print("Env={}".format(env))
config.environment(env)
algo = config.build()
for i in range(num_iterations):
results = algo.train()
check_train_results_new_api_stack(results)
print(results)
algo.stop()
def test_sac_dict_obs_order(self):
dict_space = Dict(
{
"img": Box(low=0, high=1, shape=(42, 42, 3)),
"cont": Box(low=0, high=100, shape=(3,)),
}
)
# Dict space .sample() returns an ordered dict.
# Make sure the keys in samples are ordered differently.
dict_samples = [dict(reversed(dict_space.sample().items())) for _ in range(10)]
class NestedDictEnv(gym.Env):
def __init__(self):
self.action_space = Box(low=-1.0, high=1.0, shape=(2,))
self.observation_space = dict_space
self.steps = 0
def reset(self, *, seed=None, options=None):
self.steps = 0
return dict_samples[0], {}
def step(self, action):
self.steps += 1
terminated = False
truncated = self.steps >= 5
return dict_samples[self.steps], 1, terminated, truncated, {}
tune.register_env("nested", lambda _: NestedDictEnv())
config = (
sac.SACConfig()
.environment("nested")
.training(
replay_buffer_config={
"capacity": 10,
},
num_steps_sampled_before_learning_starts=0,
train_batch_size=5,
)
.env_runners(
num_env_runners=0,
rollout_fragment_length=5,
env_to_module_connector=(
lambda env, spaces, device: FlattenObservations()
),
)
)
num_iterations = 1
algo = config.build()
for _ in range(num_iterations):
results = algo.train()
check_train_results_new_api_stack(results)
print(results)
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestSAC |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 11908,
"end": 13578
} | class ____(nn.Module):
"""
A module for vector quantization using learned embedding vectors.
This module implements the quantization process similar to te one described in
the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
input vectors into discrete codebook vectors, which are learned during training.
Current implementation improves over previous ones by avoiding costly matrix multiplications
and allowing for post-hoc remapping of indices.
"""
def __init__(self, config: Emu3VQVAEConfig):
super().__init__()
self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
def forward(self, hidden_state: torch.Tensor):
batch_size, temporal, channels, height, width = hidden_state.shape
hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous()
hidden_state_flattened = hidden_state.view(-1, channels)
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True)
embedding_sum = torch.sum(self.embedding.weight**2, dim=1)
# "bd,dn->bn",
distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1))
distances = hidden_state_sum + embedding_sum - distances
min_encoding_indices = torch.argmin(distances, dim=1)
min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width)
return min_encoding_indices
| Emu3VQVAEVectorQuantizer |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_uneven.py | {
"start": 859,
"end": 2662
} | class ____(FSDPTest):
def _get_ref_results(self, device, model, input, my_lr):
with torch.no_grad():
# Compute one iteration local output.
weight = model.weight.T.clone().to(device_type)
v = torch.Tensor(input[self.rank]).to(device_type)
ref_forward_output_my_rank = torch.matmul(v, weight)
# Compute one iteration global weight update.
v = torch.Tensor(input[: self.world_size]).to(device_type)
grad = v.float().sum(0).repeat(weight.shape[0], 1).div(self.world_size)
ref_weight_out = weight - grad.T * my_lr
return ref_forward_output_my_rank, ref_weight_out
@skip_if_lt_x_gpu(2)
def test_one_iteration(self, device):
"""Test FSDP with uneven divide of parameter shards."""
model = Linear(3, 3, bias=False)
input = torch.rand(self.world_size, 3)
my_lr = 0.1
ref_forward_output_my_rank, ref_weight_out = self._get_ref_results(
device, model, input, my_lr
)
model.to(device_type)
model = FSDP(model)
optim = SGD(model.parameters(), lr=my_lr)
self.assertTrue(len(input) >= self.world_size)
in_data = torch.Tensor(input[self.rank]).to(device_type)
out = model(in_data)
out.float().sum().backward()
optim.step()
optim.zero_grad()
with model.summon_full_params(model):
weight_out = model.module.weight.T.clone()
self.assertEqual(ref_forward_output_my_rank, out)
self.assertEqual(ref_weight_out, weight_out)
devices = ("cuda", "hpu", "xpu")
instantiate_device_type_tests(
TestUnevenParamShard, globals(), only_for=devices, allow_xpu=True
)
if __name__ == "__main__":
run_tests()
| TestUnevenParamShard |
python | kamyu104__LeetCode-Solutions | Python/number-of-ships-in-a-rectangle.py | {
"start": 222,
"end": 396
} | class ____(object):
def hasShips(self, topRight, bottomLeft):
"""
:type topRight: Point
:type bottomLeft: Point
:rtype bool
"""
pass
| Sea |
python | protocolbuffers__protobuf | python/google/protobuf/internal/containers.py | {
"start": 15854,
"end": 19978
} | class ____(MutableMapping[_K, _V]):
"""Simple, type-checked, dict-like container for with submessage values."""
# Disallows assignment to other attributes.
__slots__ = ['_key_checker', '_values', '_message_listener',
'_message_descriptor', '_entry_descriptor']
def __init__(
self,
message_listener: Any,
message_descriptor: Any,
key_checker: Any,
entry_descriptor: Any,
) -> None:
"""
Args:
message_listener: A MessageListener implementation.
The ScalarMap will call this object's Modified() method when it
is modified.
key_checker: A type_checkers.ValueChecker instance to run on keys
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
entry_descriptor: The MessageDescriptor of a map entry: key and value.
"""
self._message_listener = message_listener
self._message_descriptor = message_descriptor
self._key_checker = key_checker
self._entry_descriptor = entry_descriptor
self._values = {}
def __getitem__(self, key: _K) -> _V:
key = self._key_checker.CheckValue(key)
try:
return self._values[key]
except KeyError:
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
self._values[key] = new_element
self._message_listener.Modified()
return new_element
def get_or_create(self, key: _K) -> _V:
"""get_or_create() is an alias for getitem (ie. map[key]).
Args:
key: The key to get or create in the map.
This is useful in cases where you want to be explicit that the call is
mutating the map. This can avoid lint errors for statements like this
that otherwise would appear to be pointless statements:
msg.my_map[key]
"""
return self[key]
@overload
def get(self, key: _K) -> Optional[_V]:
...
@overload
def get(self, key: _K, default: _T) -> Union[_V, _T]:
...
# We need to override this explicitly, because our defaultdict-like behavior
# will make the default implementation (from our base class) always insert
# the key.
def get(self, key, default=None):
if key in self:
return self[key]
else:
return default
def __contains__(self, item: _K) -> bool:
item = self._key_checker.CheckValue(item)
return item in self._values
def __setitem__(self, key: _K, value: _V) -> NoReturn:
raise ValueError('May not set values directly, call my_map[key].foo = 5')
def __delitem__(self, key: _K) -> None:
key = self._key_checker.CheckValue(key)
del self._values[key]
self._message_listener.Modified()
def __len__(self) -> int:
return len(self._values)
def __iter__(self) -> Iterator[_K]:
return iter(self._values)
def __repr__(self) -> str:
return repr(self._values)
def setdefault(self, key: _K, value: Optional[_V] = None) -> _V:
raise NotImplementedError(
'Set message map value directly is not supported, call'
' my_map[key].foo = 5'
)
def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
# pylint: disable=protected-access
for key in other._values:
# According to documentation: "When parsing from the wire or when merging,
# if there are duplicate map keys the last key seen is used".
if key in self:
del self[key]
self[key].CopyFrom(other[key])
# self._message_listener.Modified() not required here, because
# mutations to submessages already propagate.
def InvalidateIterators(self) -> None:
# It appears that the only way to reliably invalidate iterators to
# self._values is to ensure that its size changes.
original = self._values
self._values = original.copy()
original[None] = None
# This is defined in the abstract base, but we can do it much more cheaply.
def clear(self) -> None:
self._values.clear()
self._message_listener.Modified()
def GetEntryClass(self) -> Any:
return self._entry_descriptor._concrete_class
| MessageMap |
python | celery__celery | t/unit/worker/test_autoscale.py | {
"start": 815,
"end": 2058
} | class ____:
def test_register_with_event_loop(self):
parent = Mock(name='parent')
parent.autoscale = True
parent.consumer.on_task_message = set()
w = autoscale.WorkerComponent(parent)
assert parent.autoscaler is None
assert w.enabled
hub = Mock(name='hub')
w.create(parent)
w.register_with_event_loop(parent, hub)
assert (parent.autoscaler.maybe_scale in
parent.consumer.on_task_message)
hub.call_repeatedly.assert_called_with(
parent.autoscaler.keepalive, parent.autoscaler.maybe_scale,
)
parent.hub = hub
hub.on_init = []
w.instantiate = Mock()
w.register_with_event_loop(parent, Mock(name='loop'))
assert parent.consumer.on_task_message
def test_info_without_event_loop(self):
parent = Mock(name='parent')
parent.autoscale = True
parent.max_concurrency = '10'
parent.min_concurrency = '2'
parent.use_eventloop = False
w = autoscale.WorkerComponent(parent)
w.create(parent)
info = w.info(parent)
assert 'autoscaler' in info
assert parent.autoscaler_cls().info.called
| test_WorkerComponent |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 37765,
"end": 40142
} | class ____(TestCase):
def test_single_limit_single_dtype(self):
tensors = [
torch.empty([100], dtype=torch.float),
torch.empty([200], dtype=torch.float),
torch.empty([100], dtype=torch.float),
torch.empty([50], dtype=torch.float),
]
result, per_bucket_size_limits = dist._compute_bucket_assignment_by_size(
tensors, [400]
)
self.assertTrue(all(size_lim == 400 for size_lim in per_bucket_size_limits))
self.assertEqual([[0], [1], [2], [3]], result)
def test_single_limit_multi_dtype(self):
tensors = [
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
]
result, per_bucket_size_limits = dist._compute_bucket_assignment_by_size(
tensors, [400]
)
self.assertTrue(all(size_lim == 400 for size_lim in per_bucket_size_limits))
self.assertEqual([[0, 2], [1, 3], [4], [5]], result)
def test_multi_limit_single_dtype(self):
tensors = [
torch.empty([10], dtype=torch.float),
torch.empty([10], dtype=torch.float),
torch.empty([10], dtype=torch.float),
torch.empty([10], dtype=torch.float),
]
result, per_bucket_size_limits = dist._compute_bucket_assignment_by_size(
tensors, [40, 80]
)
self.assertEqual(per_bucket_size_limits, [40, 80, 80])
self.assertEqual([[0], [1, 2], [3]], result)
def test_multi_limit_multi_dtype(self):
tensors = [
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
torch.empty([50], dtype=torch.float),
torch.empty([25], dtype=torch.double),
]
result, per_bucket_size_limits = dist._compute_bucket_assignment_by_size(
tensors, [200, 400]
)
self.assertEqual([[0], [1], [2, 4], [3, 5]], result)
self.assertEqual(per_bucket_size_limits, [200, 200, 400, 400])
| ComputeBucketAssignmentTest |
python | numba__numba | numba/tests/test_struct_ref.py | {
"start": 8431,
"end": 9967
} | class ____(MemoryLeakMixin, TestCase):
def setUp(self):
self._cache_dir = temp_directory(TestStructRefCaching.__name__)
self._cache_override = override_config('CACHE_DIR', self._cache_dir)
self._cache_override.__enter__()
warnings.simplefilter("error")
warnings.filterwarnings(action="ignore", module="typeguard")
def tearDown(self):
self._cache_override.__exit__(None, None, None)
warnings.resetwarnings()
def test_structref_caching(self):
def assert_cached(stats):
self.assertEqual(len(stats.cache_hits), 1)
self.assertEqual(len(stats.cache_misses), 0)
def assert_not_cached(stats):
self.assertEqual(len(stats.cache_hits), 0)
self.assertEqual(len(stats.cache_misses), 1)
def check(cached):
check_make = njit(cache=True)(caching_test_make)
check_use = njit(cache=True)(caching_test_use)
vs = np.random.random(3)
ctr = 17
factor = 3
st = check_make(vs, ctr)
got = check_use(st, factor)
expect = vs * factor + ctr
self.assertPreciseEqual(got, expect)
if cached:
assert_cached(check_make.stats)
assert_cached(check_use.stats)
else:
assert_not_cached(check_make.stats)
assert_not_cached(check_use.stats)
check(cached=False)
check(cached=True)
@structref.register
| TestStructRefCaching |
python | facebook__pyre-check | tools/generate_taint_models/tests/function_tainter_test.py | {
"start": 702,
"end": 1657
} | class ____:
value: str
def test_dataclass_parameter(data: TestRequestDataclass) -> TestReturnDataclass:
return TestReturnDataclass(w=data.x1, z=data.y)
def test_simple_parameter(x1: str, y: int) -> None:
pass
def test_simple_and_dataclass_parameters(data: TestRequestDataclass, x: str) -> None:
pass
# pyre-ignore
def test_args_kwargs_without_annotation(*args, **kwargs):
pass
def test_args_kwargs_with_any_annotation(*args: Any, **kwargs: Any) -> None:
pass
def test_optional_annotation(data: Optional[TestRequestDataclass]) -> None:
pass
def test_annotated_annotation(
data: Annotated[TestRequestDataclass, WhateverAnnotation(value="test")]
) -> None:
pass
def test_mixed_args(
data1: Optional[TestRequestDataclass],
data2: Annotated[TestRequestDataclass, WhateverAnnotation(value="test")],
x: str,
*args, # pyre-ignore
**kwargs # pyre-ignore
) -> None:
pass
| WhateverAnnotation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_sheet_views4.py | {
"start": 301,
"end": 4889
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_sheet_views() method.
Repeat of tests in test_write_sheet_views3.py with explicit topLeft cells.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_sheet_views1(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(15, 0, 1, 0)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="600" topLeftCell="A2"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views2(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(30, 0, 2, 0)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="900" topLeftCell="A3"/><selection pane="bottomLeft" activeCell="A3" sqref="A3"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views3(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(105, 0, 7, 0)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="2400" topLeftCell="A8"/><selection pane="bottomLeft" activeCell="A8" sqref="A8"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views4(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(0, 8.43, 0, 1)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1350" topLeftCell="B1"/><selection pane="topRight" activeCell="B1" sqref="B1"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views5(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(0, 17.57, 0, 2)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="2310" topLeftCell="C1"/><selection pane="topRight" activeCell="C1" sqref="C1"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views6(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(0, 45, 0, 5)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="5190" topLeftCell="F1"/><selection pane="topRight" activeCell="F1" sqref="F1"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views7(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(15, 8.43, 1, 1)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1350" ySplit="600" topLeftCell="B2"/><selection pane="topRight" activeCell="B1" sqref="B1"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/><selection pane="bottomRight" activeCell="B2" sqref="B2"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views8(self):
"""Test the _write_sheet_views() method with split panes"""
self.worksheet.select()
self.worksheet.split_panes(45, 54.14, 3, 6)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6150" ySplit="1200" topLeftCell="G4"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight" activeCell="G4" sqref="G4"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestWriteSheetViews |
python | numba__numba | numba/tests/test_api.py | {
"start": 791,
"end": 2614
} | class ____(TestCase):
"""
Test the jit and njit decorators
"""
def test_jit_nopython_forceobj(self):
with self.assertRaises(ValueError) as cm:
jit(nopython=True, forceobj=True)
self.assertIn(
"Only one of 'nopython' or 'forceobj' can be True.",
str(cm.exception)
)
def py_func(x):
return x
jit_func = jit(nopython=True)(py_func)
jit_func(1)
# Check length of nopython_signatures to check
# which mode the function was compiled in
self.assertEqual(len(jit_func.nopython_signatures), 1)
jit_func = jit(forceobj=True)(py_func)
jit_func(1)
self.assertEqual(len(jit_func.nopython_signatures), 0)
def test_njit_nopython_forceobj(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', RuntimeWarning)
njit(forceobj=True)
self.assertEqual(len(w), 1)
self.assertIn(
'forceobj is set for njit and is ignored', str(w[0].message)
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', RuntimeWarning)
njit(nopython=True)
self.assertEqual(len(w), 1)
self.assertIn(
'nopython is set for njit and is ignored', str(w[0].message)
)
def py_func(x):
return x
jit_func = njit(nopython=True)(py_func)
jit_func(1)
self.assertEqual(len(jit_func.nopython_signatures), 1)
jit_func = njit(forceobj=True)(py_func)
jit_func(1)
# Since forceobj is ignored this has to compile in nopython mode
self.assertEqual(len(jit_func.nopython_signatures), 1)
if __name__ == '__main__':
unittest.main()
| TestJitDecorator |
python | huggingface__transformers | src/transformers/models/instructblip/processing_instructblip.py | {
"start": 1549,
"end": 6969
} | class ____(ProcessorMixin):
r"""
Constructs an InstructBLIP processor which wraps a BLIP image processor and a LLaMa/T5 tokenizer into a single
processor.
[`InstructBlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the
docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
Args:
image_processor (`BlipImageProcessor`):
An instance of [`BlipImageProcessor`]. The image processor is a required input.
tokenizer (`AutoTokenizer`):
An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
qformer_tokenizer (`AutoTokenizer`):
An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
num_query_tokens (`int`, *optional*):"
Number of tokens used by the Qformer as queries, should be same as in model's config.
"""
def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
if not hasattr(tokenizer, "image_token"):
self.image_token = AddedToken("<image>", normalized=False, special=True)
tokenizer.add_tokens([self.image_token], special_tokens=True)
else:
self.image_token = tokenizer.image_token
self.num_query_tokens = num_query_tokens
super().__init__(image_processor, tokenizer, qformer_tokenizer)
def __call__(
self,
images: Optional[ImageInput] = None,
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
**kwargs: Unpack[InstructBlipProcessorKwargs],
) -> BatchFeature:
"""
This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
[`BertTokenizerFast.__call__`] to prepare text for the model.
Please refer to the docstring of the above two methods for more information.
Args:
images (`ImageInput`):
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
tensor. Both channels-first and channels-last formats are supported.
text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
"""
if images is None and text is None:
raise ValueError("You have to specify at least images or text.")
output_kwargs = self._merge_kwargs(
InstructBlipProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
encoding = {}
if text is not None:
if isinstance(text, str):
text = [text]
elif not isinstance(text, list) and not isinstance(text[0], str):
raise ValueError("Invalid input text. Please provide a string, or a list of strings")
qformer_text_encoding = self.qformer_tokenizer(text, **output_kwargs["text_kwargs"])
encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
# We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
if output_kwargs["text_kwargs"].get("max_length") is not None:
output_kwargs["text_kwargs"]["max_length"] -= self.num_query_tokens
text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
if images is not None:
# Image tokens should not be padded/truncated or prepended with special BOS token
image_tokens = self.image_token.content * self.num_query_tokens
output_kwargs["text_kwargs"]["add_special_tokens"] = False
output_kwargs["text_kwargs"]["padding"] = False
output_kwargs["text_kwargs"]["truncation"] = False
image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
for k in text_encoding:
text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
encoding.update(text_encoding)
if images is not None:
image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
encoding.update(image_encoding)
# Cast to desired return tensors type
encoding = BatchFeature(encoding, tensor_type=return_tensors)
return encoding
@property
def model_input_names(self):
tokenizer_input_names = self.tokenizer.model_input_names
image_processor_input_names = self.image_processor.model_input_names
qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
return tokenizer_input_names + image_processor_input_names + qformer_input_names
__all__ = ["InstructBlipProcessor"]
| InstructBlipProcessor |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 70375,
"end": 72682
} | class ____(SingleContinuousDistribution):
_argnames = ('mu', 's')
set = Interval.open(0, 1)
@staticmethod
def check(mu, s):
_value_check((s ** 2).is_real is not False and s ** 2 > 0, "Squared scale parameter s must be positive.")
_value_check(mu.is_real is not False, "Location parameter must be real")
def _logit(self, x):
return log(x / (1 - x))
def pdf(self, x):
mu, s = self.mu, self.s
return exp(-(self._logit(x) - mu)**2/(2*s**2))*(S.One/sqrt(2*pi*(s**2)))*(1/(x*(1 - x)))
def _cdf(self, x):
mu, s = self.mu, self.s
return (S.One/2)*(1 + erf((self._logit(x) - mu)/(sqrt(2*s**2))))
def LogitNormal(name, mu, s):
r"""
Create a continuous random variable with a Logit-Normal distribution.
The density of the logistic distribution is given by
.. math::
f(x) := \frac{1}{s \sqrt{2 \pi}} \frac{1}{x(1 - x)} e^{- \frac{(logit(x) - \mu)^2}{s^2}}
where logit(x) = \log(\frac{x}{1 - x})
Parameters
==========
mu : Real number, the location (mean)
s : Real number, `s > 0`, a scale
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import LogitNormal, density, cdf
>>> from sympy import Symbol,pprint
>>> mu = Symbol("mu", real=True)
>>> s = Symbol("s", positive=True)
>>> z = Symbol("z")
>>> X = LogitNormal("x",mu,s)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
/ / z \\
-|-mu + log|-----||
\ \1 - z//
---------------------
2
___ 2*s
\/ 2 *e
----------------------------
____
2*\/ pi *s*z*(1 - z)
>>> density(X)(z)
sqrt(2)*exp(-(-mu + log(z/(1 - z)))**2/(2*s**2))/(2*sqrt(pi)*s*z*(1 - z))
>>> cdf(X)(z)
erf(sqrt(2)*(-mu + log(z/(1 - z)))/(2*s))/2 + 1/2
References
==========
.. [1] https://en.wikipedia.org/wiki/Logit-normal_distribution
"""
return rv(name, LogitNormalDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Log Normal distribution ------------------------------------------------------
| LogitNormalDistribution |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 16074,
"end": 17283
} | class ____(nn.Module):
def __init__(self, config: OwlViTTextConfig):
super().__init__()
self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
self.position_embedding = nn.Embedding(config.max_position_embeddings, config.hidden_size)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> torch.Tensor:
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None:
inputs_embeds = self.token_embedding(input_ids)
position_embeddings = self.position_embedding(position_ids)
embeddings = inputs_embeds + position_embeddings
return embeddings
| OwlViTTextEmbeddings |
python | yaml__pyyaml | lib/yaml/resolver.py | {
"start": 6873,
"end": 9004
} | class ____(BaseResolver):
pass
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:bool',
re.compile(r'''^(?:yes|Yes|YES|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF)$''', re.X),
list('yYnNtTfFoO'))
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:float',
re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
|\.[0-9][0-9_]*(?:[eE][-+][0-9]+)?
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
|[-+]?\.(?:inf|Inf|INF)
|\.(?:nan|NaN|NAN))$''', re.X),
list('-+0123456789.'))
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:int',
re.compile(r'''^(?:[-+]?0b[0-1_]+
|[-+]?0[0-7_]+
|[-+]?(?:0|[1-9][0-9_]*)
|[-+]?0x[0-9a-fA-F_]+
|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
list('-+0123456789'))
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:merge',
re.compile(r'^(?:<<)$'),
['<'])
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:null',
re.compile(r'''^(?: ~
|null|Null|NULL
| )$''', re.X),
['~', 'n', 'N', ''])
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:timestamp',
re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
|[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
(?:[Tt]|[ \t]+)[0-9][0-9]?
:[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
list('0123456789'))
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:value',
re.compile(r'^(?:=)$'),
['='])
# The following resolver is only for documentation purposes. It cannot work
# because plain scalars cannot start with '!', '&', or '*'.
Resolver.add_implicit_resolver(
'tag:yaml.org,2002:yaml',
re.compile(r'^(?:!|&|\*)$'),
list('!&*'))
| Resolver |
python | eventlet__eventlet | eventlet/green/ssl.py | {
"start": 16743,
"end": 19417
} | class ____(_original_sslcontext):
__slots__ = ()
def wrap_socket(self, sock, *a, **kw):
return GreenSSLSocket(sock, *a, _context=self, **kw)
# https://github.com/eventlet/eventlet/issues/371
# Thanks to Gevent developers for sharing patch to this problem.
if hasattr(_original_sslcontext.options, 'setter'):
# In 3.6, these became properties. They want to access the
# property __set__ method in the superclass, and they do so by using
# super(SSLContext, SSLContext). But we rebind SSLContext when we monkey
# patch, which causes infinite recursion.
# https://github.com/python/cpython/commit/328067c468f82e4ec1b5c510a4e84509e010f296
@_original_sslcontext.options.setter
def options(self, value):
super(_original_sslcontext, _original_sslcontext).options.__set__(self, value)
@_original_sslcontext.verify_flags.setter
def verify_flags(self, value):
super(_original_sslcontext, _original_sslcontext).verify_flags.__set__(self, value)
@_original_sslcontext.verify_mode.setter
def verify_mode(self, value):
super(_original_sslcontext, _original_sslcontext).verify_mode.__set__(self, value)
if hasattr(_original_sslcontext, "maximum_version"):
@_original_sslcontext.maximum_version.setter
def maximum_version(self, value):
super(_original_sslcontext, _original_sslcontext).maximum_version.__set__(self, value)
if hasattr(_original_sslcontext, "minimum_version"):
@_original_sslcontext.minimum_version.setter
def minimum_version(self, value):
super(_original_sslcontext, _original_sslcontext).minimum_version.__set__(self, value)
SSLContext = GreenSSLContext
# TODO: ssl.create_default_context() was added in 2.7.9.
# Not clear we're still trying to support Python versions even older than that.
if hasattr(__ssl, 'create_default_context'):
_original_create_default_context = __ssl.create_default_context
def green_create_default_context(*a, **kw):
# We can't just monkey-patch on the green version of `wrap_socket`
# on to SSLContext instances, but SSLContext.create_default_context
# does a bunch of work. Rather than re-implementing it all, just
# switch out the __class__ to get our `wrap_socket` implementation
context = _original_create_default_context(*a, **kw)
context.__class__ = GreenSSLContext
return context
create_default_context = green_create_default_context
_create_default_https_context = green_create_default_context
| GreenSSLContext |
python | realpython__materials | python-getter-setter/employee4.py | {
"start": 302,
"end": 661
} | class ____:
birth_date = Date()
start_date = Date()
def __init__(self, name, birth_date, start_date):
self.name = name
self.birth_date = birth_date
self.start_date = start_date
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value.upper()
| Employee |
python | numba__numba | numba/core/ir.py | {
"start": 31369,
"end": 32236
} | class ____(EqualityCheckMixin, AbstractRHS):
"""
A freevar, as loaded by LOAD_DECREF.
(i.e. a variable defined in an enclosing non-global scope)
"""
def __init__(self, index, name, value, loc):
assert isinstance(index, int)
assert isinstance(name, str)
assert isinstance(loc, Loc)
# index inside __code__.co_freevars
self.index = index
# variable name
self.name = name
# frozen value
self.value = value
self.loc = loc
def __str__(self):
return 'freevar(%s: %s)' % (self.name, self.value)
def infer_constant(self):
return self.value
def __deepcopy__(self, memo):
# Override to not copy constant values in code
return FreeVar(index=self.index, name=self.name, value=self.value,
loc=self.loc)
| FreeVar |
python | astropy__astropy | astropy/io/fits/scripts/fitsheader.py | {
"start": 8336,
"end": 17172
} | class ____(HeaderFormatter):
"""Class to convert the header(s) of a FITS file into a Table object.
The table returned by the `parse` method will contain four columns:
filename, hdu, keyword, and value.
Subclassed from HeaderFormatter, which contains the meat of the formatting.
"""
def _parse_internal(self, hdukeys, keywords, compressed):
"""Method called by the parse method in the parent class."""
tablerows = []
for hdu in hdukeys:
try:
for card in self._get_cards(hdu, keywords, compressed):
tablerows.append(
{
"filename": self.filename,
"hdu": hdu,
"keyword": card.keyword,
"value": str(card.value),
}
)
except ExtensionNotFoundException:
pass
if tablerows:
from astropy import table
return table.Table(tablerows)
return None
def print_headers_traditional(args):
"""Prints FITS header(s) using the traditional 80-char format.
Parameters
----------
args : argparse.Namespace
Arguments passed from the command-line as defined below.
"""
for idx, filename in enumerate(args.filename): # support wildcards
if idx > 0 and not args.keyword:
print() # print a newline between different files
formatter = None
try:
formatter = HeaderFormatter(filename)
print(
formatter.parse(args.extensions, args.keyword, args.compressed), end=""
)
except OSError as e:
log.error(str(e))
finally:
if formatter:
formatter.close()
def print_headers_as_table(args):
"""Prints FITS header(s) in a machine-readable table format.
Parameters
----------
args : argparse.Namespace
Arguments passed from the command-line as defined below.
"""
tables = []
# Create a Table object for each file
for filename in args.filename: # Support wildcards
formatter = None
try:
formatter = TableHeaderFormatter(filename)
tbl = formatter.parse(args.extensions, args.keyword, args.compressed)
if tbl:
tables.append(tbl)
except OSError as e:
log.error(str(e)) # file not found or unreadable
finally:
if formatter:
formatter.close()
# Concatenate the tables
if len(tables) == 0:
return False
elif len(tables) == 1:
resulting_table = tables[0]
else:
from astropy import table
resulting_table = table.vstack(tables)
# Print the string representation of the concatenated table
resulting_table.write(sys.stdout, format=args.table)
def print_headers_as_comparison(args):
"""Prints FITS header(s) with keywords as columns.
This follows the dfits+fitsort format.
Parameters
----------
args : argparse.Namespace
Arguments passed from the command-line as defined below.
"""
from astropy import table
tables = []
# Create a Table object for each file
for filename in args.filename: # Support wildcards
formatter = None
try:
formatter = TableHeaderFormatter(filename, verbose=False)
tbl = formatter.parse(args.extensions, args.keyword, args.compressed)
if tbl:
# Remove empty keywords
tbl = tbl[np.where(tbl["keyword"] != "")]
else:
tbl = table.Table([[filename]], names=("filename",))
tables.append(tbl)
except OSError as e:
log.error(str(e)) # file not found or unreadable
finally:
if formatter:
formatter.close()
# Concatenate the tables
if len(tables) == 0:
return False
elif len(tables) == 1:
resulting_table = tables[0]
else:
resulting_table = table.vstack(tables)
# If we obtained more than one hdu, merge hdu and keywords columns
hdus = resulting_table["hdu"]
if np.ma.isMaskedArray(hdus):
hdus = hdus.compressed()
if len(np.unique(hdus)) > 1:
for tab in tables:
new_column = table.Column([f"{row['hdu']}:{row['keyword']}" for row in tab])
tab.add_column(new_column, name="hdu+keyword")
keyword_column_name = "hdu+keyword"
else:
keyword_column_name = "keyword"
# Check how many hdus we are processing
final_tables = []
for tab in tables:
final_table = [table.Column([tab["filename"][0]], name="filename")]
if "value" in tab.colnames:
for row in tab:
if row["keyword"] in ("COMMENT", "HISTORY"):
continue
final_table.append(
table.Column([row["value"]], name=row[keyword_column_name])
)
final_tables.append(table.Table(final_table))
final_table = table.vstack(final_tables)
# Sort if requested
if args.sort:
final_table.sort(args.sort)
# Reorganise to keyword by columns
final_table.pprint(max_lines=-1, max_width=-1)
def main(args=None):
"""This is the main function called by the `fitsheader` script."""
parser = argparse.ArgumentParser(
description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter
)
# TODO: pass suggest_on_error as kwarg when PYTHON_LT_14 is dropped
parser.suggest_on_error = True
parser.add_argument(
"--version", action="version", version=f"%(prog)s {__version__}"
)
parser.add_argument(
"-e",
"--extension",
metavar="HDU",
action="append",
dest="extensions",
help=(
"specify the extension by name or number; this argument can "
"be repeated to select multiple extensions"
),
)
parser.add_argument(
"-k",
"--keyword",
metavar="KEYWORD",
action="append",
type=str,
help=(
"specify a keyword; this argument can be repeated to select "
"multiple keywords; also supports wildcards"
),
)
mode_group = parser.add_mutually_exclusive_group()
mode_group.add_argument(
"-t",
"--table",
nargs="?",
default=False,
metavar="FORMAT",
help=(
"print the header(s) in machine-readable table format; the "
'default format is "ascii.fixed_width" (can be "ascii.csv", '
'"ascii.html", "ascii.latex", "fits", etc)'
),
)
mode_group.add_argument(
"-f",
"--fitsort",
action="store_true",
help=(
"print the headers as a table with each unique "
"keyword in a given column (fitsort format) "
),
)
parser.add_argument(
"-s",
"--sort",
metavar="SORT_KEYWORD",
action="append",
type=str,
help=(
"sort output by the specified header keywords, can be repeated to "
"sort by multiple keywords; Only supported with -f/--fitsort"
),
)
parser.add_argument(
"-c",
"--compressed",
action="store_true",
help=(
"for compressed image data, show the true header which describes "
"the compression rather than the data"
),
)
parser.add_argument(
"filename",
nargs="+",
help="path to one or more files; wildcards are supported",
)
args = parser.parse_args(args)
# If `--table` was used but no format specified,
# then use ascii.fixed_width by default
if args.table is None:
args.table = "ascii.fixed_width"
if args.sort:
args.sort = [key.replace(".", " ") for key in args.sort]
if not args.fitsort:
log.error(
"Sorting with -s/--sort is only supported in conjunction with"
" -f/--fitsort"
)
# 2: Unix error convention for command line syntax
sys.exit(2)
if args.keyword:
args.keyword = [key.replace(".", " ") for key in args.keyword]
# Now print the desired headers
try:
if args.table:
print_headers_as_table(args)
elif args.fitsort:
print_headers_as_comparison(args)
else:
print_headers_traditional(args)
except OSError:
# A 'Broken pipe' OSError may occur when stdout is closed prematurely,
# eg. when calling `fitsheader file.fits | head`. We let this pass.
pass
| TableHeaderFormatter |
python | openai__gym | gym/wrappers/time_aware_observation.py | {
"start": 137,
"end": 2402
} | class ____(gym.ObservationWrapper):
"""Augment the observation with the current time step in the episode.
The observation space of the wrapped environment is assumed to be a flat :class:`Box`.
In particular, pixel observations are not supported. This wrapper will append the current timestep within the current episode to the observation.
Example:
>>> import gym
>>> env = gym.make('CartPole-v1')
>>> env = TimeAwareObservation(env)
>>> env.reset()
array([ 0.03810719, 0.03522411, 0.02231044, -0.01088205, 0. ])
>>> env.step(env.action_space.sample())[0]
array([ 0.03881167, -0.16021058, 0.0220928 , 0.28875574, 1. ])
"""
def __init__(self, env: gym.Env):
"""Initialize :class:`TimeAwareObservation` that requires an environment with a flat :class:`Box` observation space.
Args:
env: The environment to apply the wrapper
"""
super().__init__(env)
assert isinstance(env.observation_space, Box)
assert env.observation_space.dtype == np.float32
low = np.append(self.observation_space.low, 0.0)
high = np.append(self.observation_space.high, np.inf)
self.observation_space = Box(low, high, dtype=np.float32)
self.is_vector_env = getattr(env, "is_vector_env", False)
def observation(self, observation):
"""Adds to the observation with the current time step.
Args:
observation: The observation to add the time step to
Returns:
The observation with the time step appended to
"""
return np.append(observation, self.t)
def step(self, action):
"""Steps through the environment, incrementing the time step.
Args:
action: The action to take
Returns:
The environment's step using the action.
"""
self.t += 1
return super().step(action)
def reset(self, **kwargs):
"""Reset the environment setting the time to zero.
Args:
**kwargs: Kwargs to apply to env.reset()
Returns:
The reset environment
"""
self.t = 0
return super().reset(**kwargs)
| TimeAwareObservation |
python | pytorch__pytorch | test/test_custom_ops.py | {
"start": 84762,
"end": 88275
} | class ____(CustomOpTestCaseBase):
test_ns = "mini_op_test"
def _init_op_delayed_backward_error(self):
name = "delayed_error"
qualname = f"{self.test_ns}::{name}"
lib = self.lib()
lib.define(f"{name}(Tensor x) -> Tensor")
lib.impl(name, lambda x: x.clone(), "CompositeExplicitAutograd")
op = self.get_op(qualname)
class Op(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, grad):
raise NotImplementedError
def autograd_impl(x):
return Op.apply(x)
lib.impl(name, autograd_impl, "Autograd")
return op
def _init_op_with_no_abstract_impl(self):
name = "no_abstract"
qualname = f"{self.test_ns}::{name}"
lib = self.lib()
lib.define(f"{name}(Tensor x) -> Tensor", tags=(torch.Tag.pt2_compliant_tag,))
lib.impl(name, lambda x: x.clone(), "CPU")
return torch._library.utils.lookup_op(qualname)
def setUp(self):
super().setUp()
self._op_with_no_abstract_impl = self._init_op_with_no_abstract_impl()
self._op_delayed_backward_error = self._init_op_delayed_backward_error()
@optests.dontGenerateOpCheckTests("Testing this API")
def test_dont_generate(self):
op = op_with_incorrect_schema(self, "incorrect_schema")
x = torch.randn(3)
op(x)
def test_mm(self):
x = torch.randn(2, 3, requires_grad=True)
y = torch.randn(3, 5)
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result, x @ y)
def test_mm_meta(self):
x = torch.randn(2, 3, requires_grad=True, device="meta")
y = torch.randn(3, 5, device="meta")
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result.shape, (x @ y).shape)
def test_mm_fake(self):
with torch._subclasses.fake_tensor.FakeTensorMode():
x = torch.randn(2, 3, requires_grad=True, device="cpu")
y = torch.randn(3, 5, device="cpu")
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result.shape, (x @ y).shape)
def test_mm_errors(self):
x = torch.randn(2, 3, requires_grad=True)
y = torch.randn(4, 5)
with self.assertRaisesRegex(RuntimeError, "cannot be multiplied"):
result = torch.ops.aten.mm.default(x, y)
def test_nonzero(self):
x = torch.tensor([0, 1, 2, 0, 0])
y = torch.ops.aten.nonzero.default(x)
self.assertEqual(y, torch.tensor([[1], [2]]))
def test_inplace(self):
x = torch.randn(3)
x_clone = x.clone()
y = torch.ops.aten.sin_(x)
self.assertEqual(x, x_clone.sin())
def test_incorrect_schema(self):
op = op_with_incorrect_schema(self, "incorrect_schema")
x = torch.randn(3)
op(x)
def test_no_abstract(self):
op = self._op_with_no_abstract_impl
x = torch.randn(3)
op(x)
def test_delayed_error(self):
op = self._op_delayed_backward_error
x = torch.randn([], requires_grad=True)
y = op(x)
with self.assertRaises(NotImplementedError):
y.sum().backward()
def test_delayed_error_no_requires_grad(self):
op = self._op_delayed_backward_error
x = torch.randn([])
y = op(x)
| MiniOpTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/struct_store/sql_query.py | {
"start": 4841,
"end": 12368
} | class ____(BaseQueryEngine):
"""
GPT natural language query engine over a structured database.
NOTE: deprecated in favor of SQLTableRetriever, kept for backward compatibility.
Given a natural language query, we will extract the query to SQL.
Runs raw SQL over a SQLStructStoreIndex. No LLM calls are made during
the SQL execution.
NOTE: this query cannot work with composed indices - if the index
contains subindices, those subindices will not be queried.
NOTE: Any Text-to-SQL application should be aware that executing
arbitrary SQL queries can be a security risk. It is recommended to
take precautions as needed, such as using restricted roles, read-only
databases, sandboxing, etc.
Args:
index (SQLStructStoreIndex): A SQL Struct Store Index
text_to_sql_prompt (Optional[BasePromptTemplate]): A Text to SQL
BasePromptTemplate to use for the query.
Defaults to DEFAULT_TEXT_TO_SQL_PROMPT.
context_query_kwargs (Optional[dict]): Keyword arguments for the
context query. Defaults to {}.
synthesize_response (bool): Whether to synthesize a response from the
query results. Defaults to True.
sql_only (bool) : Whether to get only sql and not the sql query result.
Default to False.
response_synthesis_prompt (Optional[BasePromptTemplate]): A
Response Synthesis BasePromptTemplate to use for the query. Defaults to
DEFAULT_RESPONSE_SYNTHESIS_PROMPT.
"""
def __init__(
self,
index: SQLStructStoreIndex,
text_to_sql_prompt: Optional[BasePromptTemplate] = None,
context_query_kwargs: Optional[dict] = None,
synthesize_response: bool = True,
response_synthesis_prompt: Optional[BasePromptTemplate] = None,
sql_only: bool = False,
**kwargs: Any,
) -> None:
"""Initialize params."""
self._index = index
self._llm = Settings.llm
self._sql_database = index.sql_database
self._sql_context_container = index.sql_context_container
self._ref_doc_id_column = index.ref_doc_id_column
self._text_to_sql_prompt = text_to_sql_prompt or DEFAULT_TEXT_TO_SQL_PROMPT
self._response_synthesis_prompt = (
response_synthesis_prompt or DEFAULT_RESPONSE_SYNTHESIS_PROMPT
)
self._context_query_kwargs = context_query_kwargs or {}
self._synthesize_response = synthesize_response
self._sql_only = sql_only
super().__init__(callback_manager=Settings.callback_manager)
def _get_prompt_modules(self) -> PromptMixinType:
"""Get prompt modules."""
return {}
def _parse_response_to_sql(self, response: str) -> str:
"""Parse response to SQL."""
# Find and remove SQLResult part
sql_result_start = response.find("SQLResult:")
if sql_result_start != -1:
response = response[:sql_result_start]
# If LLM returns SQLQuery: or ```sql, extract the SQL query
sql_query_start = response.find("SQLQuery:")
if sql_query_start != -1:
response = response[sql_query_start:]
response = response.replace("SQLQuery:", "")
sql_markdown_start = response.find("```sql")
if sql_markdown_start != -1:
response = response.replace("```sql", "")
response = response.replace("```", "")
# If LLM talks between the end of query and SQL result
# find semi-colon and remove everything after it
semi_colon = response.find(";")
if semi_colon != -1:
response = response[: semi_colon + 1]
# Replace escaped single quotes, happens when
# there's a ' in the value (e.g. "I'm")
response = response.replace("\\'", "''")
return response.strip()
def _get_table_context(self, query_bundle: QueryBundle) -> str:
"""
Get table context.
Get tables schema + optional context as a single string. Taken from
SQLContextContainer.
"""
if self._sql_context_container.context_str is not None:
tables_desc_str = self._sql_context_container.context_str
else:
table_desc_list = []
context_dict = self._sql_context_container.context_dict
if context_dict is None:
raise ValueError(
"context_dict must be provided. There is currently no "
"table context."
)
for table_desc in context_dict.values():
table_desc_list.append(table_desc)
tables_desc_str = "\n\n".join(table_desc_list)
return tables_desc_str
def _run_with_sql_only_check(self, sql_query_str: str) -> Tuple[str, Dict]:
"""Don't run sql if sql_only is true, else continue with normal path."""
if self._sql_only:
metadata: Dict[str, Any] = {}
raw_response_str = sql_query_str
else:
raw_response_str, metadata = self._sql_database.run_sql(sql_query_str)
return raw_response_str, metadata
def _query(self, query_bundle: QueryBundle) -> Response:
"""Answer a query."""
table_desc_str = self._get_table_context(query_bundle)
logger.info(f"> Table desc str: {table_desc_str}")
response_str = self._llm.predict(
self._text_to_sql_prompt,
query_str=query_bundle.query_str,
schema=table_desc_str,
dialect=self._sql_database.dialect,
)
sql_query_str = self._parse_response_to_sql(response_str)
# assume that it's a valid SQL query
logger.debug(f"> Predicted SQL query: {sql_query_str}")
raw_response_str, metadata = self._run_with_sql_only_check(sql_query_str)
metadata["sql_query"] = sql_query_str
if self._synthesize_response:
response_str = self._llm.predict(
self._response_synthesis_prompt,
query_str=query_bundle.query_str,
sql_query=sql_query_str,
sql_response_str=raw_response_str,
)
else:
response_str = raw_response_str
return Response(response=response_str, metadata=metadata)
async def _aquery(self, query_bundle: QueryBundle) -> Response:
"""Answer a query."""
table_desc_str = self._get_table_context(query_bundle)
logger.info(f"> Table desc str: {table_desc_str}")
response_str = await self._llm.apredict(
self._text_to_sql_prompt,
query_str=query_bundle.query_str,
schema=table_desc_str,
dialect=self._sql_database.dialect,
)
sql_query_str = self._parse_response_to_sql(response_str)
# assume that it's a valid SQL query
logger.debug(f"> Predicted SQL query: {sql_query_str}")
response_str, metadata = self._run_with_sql_only_check(sql_query_str)
metadata["sql_query"] = sql_query_str
return Response(response=response_str, metadata=metadata)
def _validate_prompt(
custom_prompt: BasePromptTemplate,
default_prompt: BasePromptTemplate,
) -> None:
"""Validate prompt."""
if custom_prompt.template_vars != default_prompt.template_vars:
raise ValueError(
"custom_prompt must have the following template variables: "
f"{default_prompt.template_vars}"
)
| NLStructStoreQueryEngine |
python | euske__pdfminer | pdfminer/pdfparser.py | {
"start": 3981,
"end": 5328
} | class ____(PDFParser):
"""
PDFStreamParser is used to parse PDF content streams
that is contained in each page and has instructions
for rendering the page. A reference to a PDF document is
needed because a PDF content stream can also have
indirect references to other objects in the same document.
"""
def __init__(self, data):
PDFParser.__init__(self, BytesIO(data))
return
def flush(self):
self.add_results(*self.popall())
return
KEYWORD_OBJ = KWD(b'obj')
def do_keyword(self, pos, token):
if token is self.KEYWORD_R:
# reference to indirect object
try:
((_, objid), (_, genno)) = self.pop(2)
(objid, genno) = (int(objid), int(genno))
obj = PDFObjRef(self.doc, objid, genno)
self.push((pos, obj))
except PSSyntaxError:
pass
return
elif token in (self.KEYWORD_OBJ, self.KEYWORD_ENDOBJ):
if STRICT:
# See PDF Spec 3.4.6: Only the object values are stored in the
# stream; the obj and endobj keywords are not used.
raise PDFSyntaxError('Keyword endobj found in stream')
return
# others
self.push((pos, token))
return
| PDFStreamParser |
python | kamyu104__LeetCode-Solutions | Python/count-ways-to-build-good-strings.py | {
"start": 34,
"end": 606
} | class ____(object):
def countGoodStrings(self, low, high, zero, one):
"""
:type low: int
:type high: int
:type zero: int
:type one: int
:rtype: int
"""
MOD = 10**9+7
result = 0
dp = [0]*(high+1)
dp[0] = 1
for i in xrange(1, high+1):
if i >= zero:
dp[i] = (dp[i]+dp[i-zero])%MOD
if i >= one:
dp[i] = (dp[i]+dp[i-one])%MOD
if i >= low:
result = (result+dp[i])%MOD
return result
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/v1_compat_tests/identity_op_py_test.py | {
"start": 1007,
"end": 1442
} | class ____(test.TestCase):
@test_util.run_v1_only("Don't need to test VariableV1 in TF2.")
def testRefIdentityShape(self):
shape = [2, 3]
tensor = variable_v1.VariableV1(
constant_op.constant([[1, 2, 3], [6, 5, 4]], dtype=dtypes.int32))
self.assertEqual(shape, tensor.get_shape())
self.assertEqual(shape, gen_array_ops.ref_identity(tensor).get_shape())
if __name__ == "__main__":
test.main()
| IdentityOpTest |
python | walkccc__LeetCode | solutions/105. Construct Binary Tree from Preorder and Inorder Traversal/105.py | {
"start": 0,
"end": 797
} | class ____:
def buildTree(
self,
preorder: list[int],
inorder: list[int],
) -> TreeNode | None:
inToIndex = {num: i for i, num in enumerate(inorder)}
def build(
preStart: int,
preEnd: int,
inStart: int,
inEnd: int,
) -> TreeNode | None:
if preStart > preEnd:
return None
rootVal = preorder[preStart]
rootInIndex = inToIndex[rootVal]
leftSize = rootInIndex - inStart
root = TreeNode(rootVal)
root.left = build(preStart + 1, preStart + leftSize,
inStart, rootInIndex - 1)
root.right = build(preStart + leftSize + 1,
preEnd, rootInIndex + 1, inEnd)
return root
return build(0, len(preorder) - 1, 0, len(inorder) - 1)
| Solution |
python | walkccc__LeetCode | solutions/2274. Maximum Consecutive Floors Without Special Floors/2274.py | {
"start": 0,
"end": 263
} | class ____:
def maxConsecutive(self, bottom: int, top: int, special: list[int]) -> int:
ans = 0
special.sort()
for a, b in zip(special, special[1:]):
ans = max(ans, b - a - 1)
return max(ans, special[0] - bottom, top - special[-1])
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/text/sentence_window.py | {
"start": 667,
"end": 5012
} | class ____(NodeParser):
"""
Sentence window node parser.
Splits a document into Nodes, with each node being a sentence.
Each node contains a window from the surrounding sentences in the metadata.
Args:
sentence_splitter (Optional[Callable]): splits text into sentences
include_metadata (bool): whether to include metadata in nodes
include_prev_next_rel (bool): whether to include prev/next relationships
"""
sentence_splitter: Callable[[str], List[str]] = Field(
default_factory=split_by_sentence_tokenizer,
description="The text splitter to use when splitting documents.",
exclude=True,
)
window_size: int = Field(
default=DEFAULT_WINDOW_SIZE,
description="The number of sentences on each side of a sentence to capture.",
gt=0,
)
window_metadata_key: str = Field(
default=DEFAULT_WINDOW_METADATA_KEY,
description="The metadata key to store the sentence window under.",
)
original_text_metadata_key: str = Field(
default=DEFAULT_OG_TEXT_METADATA_KEY,
description="The metadata key to store the original sentence in.",
)
@classmethod
def class_name(cls) -> str:
return "SentenceWindowNodeParser"
@classmethod
def from_defaults(
cls,
sentence_splitter: Optional[Callable[[str], List[str]]] = None,
window_size: int = DEFAULT_WINDOW_SIZE,
window_metadata_key: str = DEFAULT_WINDOW_METADATA_KEY,
original_text_metadata_key: str = DEFAULT_OG_TEXT_METADATA_KEY,
include_metadata: bool = True,
include_prev_next_rel: bool = True,
callback_manager: Optional[CallbackManager] = None,
id_func: Optional[Callable[[int, Document], str]] = None,
) -> "SentenceWindowNodeParser":
callback_manager = callback_manager or CallbackManager([])
sentence_splitter = sentence_splitter or split_by_sentence_tokenizer()
id_func = id_func or default_id_func
return cls(
sentence_splitter=sentence_splitter,
window_size=window_size,
window_metadata_key=window_metadata_key,
original_text_metadata_key=original_text_metadata_key,
include_metadata=include_metadata,
include_prev_next_rel=include_prev_next_rel,
callback_manager=callback_manager,
id_func=id_func,
)
def _parse_nodes(
self,
nodes: Sequence[BaseNode],
show_progress: bool = False,
**kwargs: Any,
) -> List[BaseNode]:
"""Parse document into nodes."""
all_nodes: List[BaseNode] = []
nodes_with_progress = get_tqdm_iterable(nodes, show_progress, "Parsing nodes")
for node in nodes_with_progress:
nodes = self.build_window_nodes_from_documents([node])
all_nodes.extend(nodes)
return all_nodes
def build_window_nodes_from_documents(
self, documents: Sequence[Document]
) -> List[BaseNode]:
"""Build window nodes from documents."""
all_nodes: List[BaseNode] = []
for doc in documents:
text = doc.text
text_splits = self.sentence_splitter(text)
nodes = build_nodes_from_splits(
text_splits,
doc,
id_func=self.id_func,
)
# add window to each node
for i, node in enumerate(nodes):
window_nodes = nodes[
max(0, i - self.window_size) : min(
i + self.window_size + 1, len(nodes)
)
]
node.metadata[self.window_metadata_key] = " ".join(
[n.text for n in window_nodes]
)
node.metadata[self.original_text_metadata_key] = node.text
# exclude window metadata from embed and llm
node.excluded_embed_metadata_keys.extend(
[self.window_metadata_key, self.original_text_metadata_key]
)
node.excluded_llm_metadata_keys.extend(
[self.window_metadata_key, self.original_text_metadata_key]
)
all_nodes.extend(nodes)
return all_nodes
| SentenceWindowNodeParser |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 89698,
"end": 91938
} | class ____(Response):
"""
Response of projects.get_task_parents endpoint.
:param parents: The list of unique task parents sorted by their names
:type parents: Sequence[dict]
"""
_service = "projects"
_action = "get_task_parents"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"parents": {
"description": "The list of unique task parents sorted by their names",
"items": {
"properties": {
"id": {
"description": "The ID of the parent task",
"type": "string",
},
"name": {
"description": "The name of the parent task",
"type": "string",
},
"project": {
"id": {
"description": "The ID of the parent task project",
"type": "string",
},
"name": {
"description": "The name of the parent task project",
"type": "string",
},
"type": "object",
},
},
"type": "object",
},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, parents: Optional[List[dict]] = None, **kwargs: Any) -> None:
super(GetTaskParentsResponse, self).__init__(**kwargs)
self.parents = parents
@schema_property("parents")
def parents(self) -> Optional[List[dict]]:
return self._property_parents
@parents.setter
def parents(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_parents = None
return
self.assert_isinstance(value, "parents", (list, tuple))
self.assert_isinstance(value, "parents", (dict,), is_array=True)
self._property_parents = value
| GetTaskParentsResponse |
python | huggingface__transformers | tests/models/instructblipvideo/test_video_processing_instructblipvideo.py | {
"start": 1052,
"end": 2965
} | class ____:
def __init__(
self,
parent,
batch_size=5,
num_channels=3,
num_frames=4,
min_resolution=30,
max_resolution=80,
do_resize=True,
size=None,
do_normalize=True,
image_mean=OPENAI_CLIP_MEAN,
image_std=OPENAI_CLIP_STD,
do_convert_rgb=True,
):
super().__init__()
size = size if size is not None else {"height": 18, "width": 18}
self.parent = parent
self.batch_size = batch_size
self.num_frames = num_frames
self.num_channels = num_channels
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_resize = do_resize
self.size = size
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
self.do_convert_rgb = do_convert_rgb
def prepare_video_processor_dict(self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def expected_output_video_shape(self, images):
return self.num_frames, self.num_channels, self.size["height"], self.size["width"]
def prepare_video_inputs(self, equal_resolution=False, return_tensors="pil"):
videos = prepare_video_inputs(
batch_size=self.batch_size,
num_frames=self.num_frames,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
return_tensors=return_tensors,
)
return videos
@require_torch
@require_vision
| InstructBlipVideoVideoProcessingTester |
python | doocs__leetcode | solution/0000-0099/0025.Reverse Nodes in k-Group/Solution.py | {
"start": 151,
"end": 969
} | class ____:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def reverse(head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
cur = head
while cur:
nxt = cur.next
cur.next = dummy.next
dummy.next = cur
cur = nxt
return dummy.next
dummy = pre = ListNode(next=head)
while pre:
cur = pre
for _ in range(k):
cur = cur.next
if cur is None:
return dummy.next
node = pre.next
nxt = cur.next
cur.next = None
pre.next = reverse(node)
node.next = nxt
pre = node
return dummy.next
| Solution |
python | doocs__leetcode | solution/2300-2399/2359.Find Closest Node to Given Two Nodes/Solution.py | {
"start": 0,
"end": 793
} | class ____:
def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
def f(i):
dist = [inf] * n
dist[i] = 0
q = deque([i])
while q:
i = q.popleft()
for j in g[i]:
if dist[j] == inf:
dist[j] = dist[i] + 1
q.append(j)
return dist
g = defaultdict(list)
for i, j in enumerate(edges):
if j != -1:
g[i].append(j)
n = len(edges)
d1 = f(node1)
d2 = f(node2)
ans, d = -1, inf
for i, (a, b) in enumerate(zip(d1, d2)):
if (t := max(a, b)) < d:
d = t
ans = i
return ans
| Solution |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 8091,
"end": 8801
} | class ____(dict):
"""
plotly.graph_objs.ErrorZ is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter3d.ErrorZ
"""
def __init__(self, *args, **kwargs):
"""
plotly.graph_objs.ErrorZ is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter3d.ErrorZ
"""
warnings.warn(
"""plotly.graph_objs.ErrorZ is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter3d.ErrorZ
""",
DeprecationWarning,
)
super().__init__(*args, **kwargs)
| ErrorZ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.