code stringlengths 1 25.8M | language stringclasses 18 values | source stringclasses 4 values | repo stringclasses 78 values | path stringlengths 0 268 |
|---|---|---|---|---|
from __future__ import print_function
import sys
from math import e
from random import randint
from gi.repository import Gtk, GObject
from gi.repository import Gdk
from pychess.System import uistuff
from pychess.System.idle_add import idle_add
from pychess.System.prefix import addDataPrefix
from pychess.Utils.const import WHITE, DRAW, RUNNING, WHITEWON, BLACKWON
from pychess.Utils.lutils import leval
__title__ = _("Score")
__icon__ = addDataPrefix("glade/panel_score.svg")
__desc__ = _("The score panel tries to evaluate the positions and shows you a graph of the game progress")
class Sidepanel:
def load (self, gmwidg):
self.boardview = gmwidg.board.view
self.plot = ScorePlot(self.boardview)
self.sw = __widget__ = Gtk.ScrolledWindow()
__widget__.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
port = Gtk.Viewport()
port.add(self.plot)
port.set_shadow_type(Gtk.ShadowType.NONE)
__widget__.add(port)
__widget__.show_all()
self.plot.connect("selected", self.plot_selected)
self.boardview.connect('shown_changed', self.shown_changed)
self.boardview.model.connect_after("game_changed", self.game_changed)
self.boardview.model.connect_after("moves_undoing", self.moves_undoing)
self.boardview.model.connect_after("analysis_changed", self.analysis_changed)
# Add the initial board
self.boardview.model.connect_after("game_started", self.game_changed)
uistuff.keepDown(__widget__)
return __widget__
def moves_undoing (self, model, moves):
for i in range(moves):
self.plot.undo()
# As shown_changed will normally be emitted just after game_changed -
# if we are viewing the latest position - we can do the selection change
# now, and thereby avoid redraw being called twice
if self.plot.selected == model.ply-model.lowply:
self.plot.select(model.ply-model.lowply - moves)
self.plot.redraw()
def game_changed (self, model):
if len(self.plot)+model.lowply > model.ply:
return
for i in range(len(self.plot)+model.lowply, model.ply):
if i in model.scores:
points = model.scores[i][1]
else:
points = leval.evaluateComplete(model.getBoardAtPly(i).board, WHITE)
self.plot.addScore(points)
if model.status == DRAW:
points = 0
elif model.status == WHITEWON:
points = sys.maxsize
elif model.status == BLACKWON:
points = -sys.maxsize
else:
if model.ply in model.scores:
points = model.scores[model.ply][1]
else:
points = leval.evaluateComplete(model.getBoardAtPly(model.ply).board, WHITE)
self.plot.addScore(points)
# As shown_changed will normally be emitted just after game_changed -
# if we are viewing the latest position - we can do the selection change
# now, and thereby avoid redraw being called twice
if self.plot.selected == model.ply-model.lowply -1:
self.plot.select(model.ply-model.lowply)
self.plot.redraw()
# Uncomment this to debug eval function
return
board = model.boards[-1].board
opboard = model.boards[-1].clone().board
opboard.setColor(1-opboard.color)
material, phase = leval.evalMaterial (board)
if board.color == WHITE:
print("material", -material)
e1 = leval.evalKingTropism (board)
e2 = leval.evalKingTropism (opboard)
print("evaluation: %d + %d = %d " % (e1, e2, e1+e2))
p1 = leval.evalPawnStructure (board, phase)
p2 = leval.evalPawnStructure (opboard, phase)
print("pawns: %d + %d = %d " % (p1, p2, p1+p2))
print("knights:",-leval.evalKnights (board))
print("king:",-leval.evalKing(board,phase))
else:
print("material", material)
print("evaluation:",leval.evalKingTropism (board))
print("pawns:", leval.evalPawnStructure (board, phase))
print("pawns2:", leval.evalPawnStructure (opboard, phase))
print("pawns3:", leval.evalPawnStructure (board, phase) + \
leval.evalPawnStructure (opboard, phase))
print("knights:",leval.evalKnights (board))
print("king:",leval.evalKing(board,phase))
print("----------------------")
def shown_changed (self, boardview, shown):
if not boardview.shownIsMainLine():
return
if self.plot.selected != shown:
self.plot.select(shown-self.boardview.model.lowply)
self.plot.redraw()
adj = self.sw.get_vadjustment()
y = self.plot.moveHeight*(shown-self.boardview.model.lowply)
if y < adj.get_value() or y > adj.get_value() + adj.get_page_size():
adj.set_value(min(y, adj.get_upper()-adj.get_page_size()))
def analysis_changed (self, gamemodel, ply):
if self.boardview.animating:
return
if not self.boardview.shownIsMainLine():
return
if ply-gamemodel.lowply > len(self.plot.scores)-1:
# analysis line of yet undone position
return
color = (ply-1) % 2
score = gamemodel.scores[ply][1]
score = score * -1 if color==WHITE else score
self.plot.changeScore(ply-gamemodel.lowply, score)
self.plot.select(ply)
self.plot.redraw()
def plot_selected (self, plot, selected):
try:
board = self.boardview.model.boards[selected]
except IndexError:
return
self.boardview.setShownBoard(board)
class ScorePlot (Gtk.DrawingArea):
__gtype_name__ = "ScorePlot"+str(randint(0,sys.maxsize))
__gsignals__ = {
"selected" : (GObject.SignalFlags.RUN_FIRST, None, (int,))
}
def __init__ (self, boardview):
GObject.GObject.__init__(self)
self.boardview = boardview
self.connect("draw", self.expose)
self.connect("button-press-event", self.press)
self.props.can_focus = True
self.set_events(Gdk.EventMask.BUTTON_PRESS_MASK|Gdk.EventMask.KEY_PRESS_MASK)
self.moveHeight = 12
self.scores = []
self.selected = 0
def addScore (self, score):
self.scores.append(score)
def changeScore(self, ply, score):
if self.scores:
self.scores[ply] = score
def __len__ (self):
return len(self.scores)
def undo (self):
del self.scores[-1]
def select (self, index):
self.selected = index
def clear (self):
del self.scores[:]
@idle_add
def redraw (self):
if self.get_window():
a = self.get_allocation()
rect = Gdk.Rectangle()
rect.x, rect.y, rect.width, rect.height = (0, 0, a.width, a.height)
self.get_window().invalidate_rect(rect, True)
self.get_window().process_updates(True)
def press (self, widget, event):
self.grab_focus()
self.emit('selected', event.y/self.moveHeight)
def expose (self, widget, context):
a = widget.get_allocation()
context.rectangle(a.x, a.y,
a.width, a.height)
context.clip()
self.draw(context)
self.set_size_request(-1, (len(self.scores))*self.moveHeight)
return False
def draw (self, cr):
m = self.boardview.model
if m.isPlayingICSGame():
return
width = self.get_allocation().width
height = len(self.scores)*self.moveHeight
########################################
# Draw background #
########################################
cr.set_source_rgb (1, 1, 1)
cr.rectangle(0, 0, width, height)
cr.fill()
########################################
# Draw dark middle line #
########################################
cr.set_source_rgb (0, 0, 0)
cr.move_to(width/2., 0)
cr.line_to(width/2., height)
cr.set_line_width(0.15)
cr.stroke()
########################################
# Draw the actual plot (dark area) #
########################################
sign = lambda n: n == 0 and 1 or n/abs(n)
if self.scores:
mapper = lambda score: (e**(-5e-4*abs(score))-1) * sign(score)
cr.set_source_rgb (0, 0, 0)
cr.move_to(width, 0)
cr.line_to(width/2 - width/2*mapper(self.scores[0]), 0)
for i, score in enumerate(self.scores):
x = width/2 - width/2*mapper(score)
y = (i+1) * self.moveHeight
cr.line_to(x, y)
cr.line_to(width, height)
cr.fill_preserve()
########################################
# Draw light middle line #
########################################
cr.save()
cr.clip()
cr.set_source_rgb (1, 1, 1)
cr.move_to(width/2., 0)
cr.line_to(width/2., height)
cr.set_line_width(0.15)
cr.stroke()
cr.restore()
########################################
# Draw selection #
########################################
lw = 2.
cr.set_line_width(lw)
y = (self.selected)*self.moveHeight
cr.rectangle(lw/2, y-lw/2, width-lw, self.moveHeight+lw)
sc = self.get_style_context()
found, color = sc.lookup_color("p_bg_selected")
cr.set_source_rgba (color.red, color.green, color.blue, .15)
cr.fill_preserve()
cr.set_source_rgb (color.red, color.green, color.blue)
cr.stroke() | unknown | codeparrot/codeparrot-clean | ||
"""
This script is used to deploy the ODrive python tools to PyPi
so that users can install them easily with
"pip install odrive"
To install the package and its dependencies locally, run:
sudo pip install -r requirements.txt
To build and package the python tools into a tar archive:
python setup.py sdist
Warning: Before you proceed, be aware that you can upload a
specific version only once ever. After that you need to increment
the hotfix number. Deleting the release manually on the PyPi
website does not help.
Use TestPyPi while developing.
To build, package and upload the python tools to TestPyPi, run:
python setup.py sdist upload -r pypitest
To make a real release ensure you're at the release commit
and then run the above command without the "test" (so just "pypi").
To install a prerelease version from test index:
(extra-index-url is there because some packages don't upload to test server)
sudo pip install --pre --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ --no-cache-dir odrive
PyPi access requires that you have set up ~/.pypirc with your
PyPi credentials and that your account has the rights
to publish packages with the name odrive.
"""
# Set to true to make the current release
is_release = True
# Set to true to make an official post-release, rather than dev of new version
is_post_release = True
post_rel_num = 0
# To test higher numbered releases, bump to the next rev
devnum = 0
bump_rev = not is_post_release and not is_release
# TODO: add additional y/n prompt to prevent from erroneous upload
from setuptools import setup
import os
import sys
if sys.version_info < (3, 3):
import exceptions
PermissionError = exceptions.OSError
creating_package = "sdist" in sys.argv
# Load version from Git tag
import odrive.version
version = odrive.version.get_version_str(
git_only=creating_package,
is_post_release=is_post_release,
bump_rev=bump_rev,
release_override=is_release)
# If we're currently creating the package we need to autogenerate
# a file that contains the version string
if creating_package:
if is_post_release:
version += str(post_rel_num)
elif (devnum > 0):
version += str(devnum)
version_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'odrive', 'version.txt')
with open(version_file_path, mode='w') as version_file:
version_file.write(version)
# TODO: find a better place for this
if not creating_package:
import platform
if platform.system() == 'Linux':
try:
odrive.version.setup_udev_rules(None)
except Exception:
print("Warning: could not set up udev rules. Run `sudo odrivetool udev-setup` to try again.")
try:
setup(
name = 'odrive',
packages = ['odrive', 'odrive.dfuse', 'odrive.pyfibre.fibre'],
scripts = ['odrivetool', 'odrivetool.bat', 'odrive_demo.py'],
version = version,
description = 'Control utilities for the ODrive high performance motor controller',
author = 'Oskar Weigl',
author_email = 'oskar.weigl@odriverobotics.com',
license='MIT',
url = 'https://github.com/madcowswe/ODrive',
keywords = ['odrive', 'motor', 'motor control'],
install_requires = [
'ipython', # Used to do the interactive parts of the odrivetool
'PyUSB', # Only required for DFU. Normal communication happens through libfibre.
'requests', # Used to by DFU to load firmware files
'IntelHex', # Used to by DFU to download firmware from github
'matplotlib', # Required to run the liveplotter
'monotonic', # For compatibility with older python versions
'setuptools', # ubuntu-latest on GitHub Actions fails to install odrive without this dependency
'pywin32 >= 222; platform_system == "Windows"' # Required for fancy terminal features on Windows
],
package_data={'': [
'version.txt',
'pyfibre/fibre/*.so',
'pyfibre/fibre/*.dll',
'pyfibre/fibre/*.dylib'
]},
classifiers = [],
)
# TODO: include README
finally:
# clean up
if creating_package:
os.remove(version_file_path) | unknown | codeparrot/codeparrot-clean | ||
import contextlib
from pathlib import Path
import re
import uuid
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
from pandas.io.excel import (
ExcelWriter,
_OpenpyxlWriter,
)
from pandas.io.excel._openpyxl import OpenpyxlReader
openpyxl = pytest.importorskip("openpyxl")
@pytest.fixture
def ext():
return ".xlsx"
@pytest.fixture
def tmp_excel(ext, tmp_path):
tmp = tmp_path / f"{uuid.uuid4()}{ext}"
tmp.touch()
return str(tmp)
def test_to_excel_styleconverter():
from openpyxl import styles
hstyle = {
"font": {"color": "00FF0000", "bold": True},
"borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"},
"alignment": {"horizontal": "center", "vertical": "top"},
"fill": {"patternType": "solid", "fgColor": {"rgb": "006666FF", "tint": 0.3}},
"number_format": {"format_code": "0.00"},
"protection": {"locked": True, "hidden": False},
}
font_color = styles.Color("00FF0000")
font = styles.Font(bold=True, color=font_color)
side = styles.Side(style=styles.borders.BORDER_THIN)
border = styles.Border(top=side, right=side, bottom=side, left=side)
alignment = styles.Alignment(horizontal="center", vertical="top")
fill_color = styles.Color(rgb="006666FF", tint=0.3)
fill = styles.PatternFill(patternType="solid", fgColor=fill_color)
number_format = "0.00"
protection = styles.Protection(locked=True, hidden=False)
kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
assert kw["font"] == font
assert kw["border"] == border
assert kw["alignment"] == alignment
assert kw["fill"] == fill
assert kw["number_format"] == number_format
assert kw["protection"] == protection
def test_write_cells_merge_styled(tmp_excel):
from pandas.io.formats.excel import ExcelCell
sheet_name = "merge_styled"
sty_b1 = {"font": {"color": "00FF0000"}}
sty_a2 = {"font": {"color": "0000FF00"}}
initial_cells = [
ExcelCell(col=1, row=0, val=42, style=sty_b1),
ExcelCell(col=0, row=1, val=99, style=sty_a2),
]
sty_merged = {"font": {"color": "000000FF", "bold": True}}
sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
openpyxl_sty_merged = sty_kwargs["font"]
merge_cells = [
ExcelCell(
col=0, row=0, val="pandas", mergestart=1, mergeend=1, style=sty_merged
)
]
with _OpenpyxlWriter(tmp_excel) as writer:
writer._write_cells(initial_cells, sheet_name=sheet_name)
writer._write_cells(merge_cells, sheet_name=sheet_name)
wks = writer.sheets[sheet_name]
xcell_b1 = wks["B1"]
xcell_a2 = wks["A2"]
assert xcell_b1.font == openpyxl_sty_merged
assert xcell_a2.font == openpyxl_sty_merged
@pytest.mark.parametrize("iso_dates", [True, False])
def test_engine_kwargs_write(tmp_excel, iso_dates):
# GH 42286 GH 43445
engine_kwargs = {"iso_dates": iso_dates}
with ExcelWriter(
tmp_excel, engine="openpyxl", engine_kwargs=engine_kwargs
) as writer:
assert writer.book.iso_dates == iso_dates
# ExcelWriter won't allow us to close without writing something
DataFrame().to_excel(writer)
def test_engine_kwargs_append_invalid(tmp_excel):
# GH 43445
# test whether an invalid engine kwargs actually raises
DataFrame(["hello", "world"]).to_excel(tmp_excel)
with pytest.raises(
TypeError,
match=re.escape(
"load_workbook() got an unexpected keyword argument 'apple_banana'"
),
):
with ExcelWriter(
tmp_excel,
engine="openpyxl",
mode="a",
engine_kwargs={"apple_banana": "fruit"},
) as writer:
# ExcelWriter needs us to write something to close properly
DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2")
@pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")])
def test_engine_kwargs_append_data_only(tmp_excel, data_only, expected):
# GH 43445
# tests whether the data_only engine_kwarg actually works well for
# openpyxl's load_workbook
DataFrame(["=1+1"]).to_excel(tmp_excel)
with ExcelWriter(
tmp_excel, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only}
) as writer:
assert writer.sheets["Sheet1"]["B2"].value == expected
# ExcelWriter needs us to writer something to close properly?
DataFrame().to_excel(writer, sheet_name="Sheet2")
# ensure that data_only also works for reading
# and that formulas/values roundtrip
assert (
pd.read_excel(
tmp_excel,
sheet_name="Sheet1",
engine="openpyxl",
engine_kwargs={"data_only": data_only},
).iloc[0, 1]
== expected
)
@pytest.mark.parametrize("kwarg_name", ["read_only", "data_only"])
@pytest.mark.parametrize("kwarg_value", [True, False])
def test_engine_kwargs_append_reader(datapath, ext, kwarg_name, kwarg_value):
# GH 55027
# test that `read_only` and `data_only` can be passed to
# `openpyxl.reader.excel.load_workbook` via `engine_kwargs`
filename = datapath("io", "data", "excel", "test1" + ext)
with contextlib.closing(
OpenpyxlReader(filename, engine_kwargs={kwarg_name: kwarg_value})
) as reader:
assert getattr(reader.book, kwarg_name) == kwarg_value
@pytest.mark.parametrize(
"mode,expected", [("w", ["baz"]), ("a", ["foo", "bar", "baz"])]
)
def test_write_append_mode(tmp_excel, mode, expected):
df = DataFrame([1], columns=["baz"])
wb = openpyxl.Workbook()
wb.worksheets[0].title = "foo"
wb.worksheets[0]["A1"].value = "foo"
wb.create_sheet("bar")
wb.worksheets[1]["A1"].value = "bar"
wb.save(tmp_excel)
with ExcelWriter(tmp_excel, engine="openpyxl", mode=mode) as writer:
df.to_excel(writer, sheet_name="baz", index=False)
with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb2:
result = [sheet.title for sheet in wb2.worksheets]
assert result == expected
for index, cell_value in enumerate(expected):
assert wb2.worksheets[index]["A1"].value == cell_value
@pytest.mark.parametrize(
"if_sheet_exists,num_sheets,expected",
[
("new", 2, ["apple", "banana"]),
("replace", 1, ["pear"]),
("overlay", 1, ["pear", "banana"]),
],
)
def test_if_sheet_exists_append_modes(tmp_excel, if_sheet_exists, num_sheets, expected):
# GH 40230
df1 = DataFrame({"fruit": ["apple", "banana"]})
df2 = DataFrame({"fruit": ["pear"]})
df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="foo", index=False)
with ExcelWriter(
tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists
) as writer:
df2.to_excel(writer, sheet_name="foo", index=False)
with contextlib.closing(openpyxl.load_workbook(tmp_excel)) as wb:
assert len(wb.sheetnames) == num_sheets
assert wb.sheetnames[0] == "foo"
result = pd.read_excel(wb, "foo", engine="openpyxl")
assert list(result["fruit"]) == expected
if len(wb.sheetnames) == 2:
result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl")
tm.assert_frame_equal(result, df2)
@pytest.mark.parametrize(
"startrow, startcol, greeting, goodbye",
[
(0, 0, ["poop", "world"], ["goodbye", "people"]),
(0, 1, ["hello", "world"], ["poop", "people"]),
(1, 0, ["hello", "poop"], ["goodbye", "people"]),
(1, 1, ["hello", "world"], ["goodbye", "poop"]),
],
)
def test_append_overlay_startrow_startcol(
tmp_excel, startrow, startcol, greeting, goodbye
):
df1 = DataFrame({"greeting": ["hello", "world"], "goodbye": ["goodbye", "people"]})
df2 = DataFrame(["poop"])
df1.to_excel(tmp_excel, engine="openpyxl", sheet_name="poo", index=False)
with ExcelWriter(
tmp_excel, engine="openpyxl", mode="a", if_sheet_exists="overlay"
) as writer:
# use startrow+1 because we don't have a header
df2.to_excel(
writer,
index=False,
header=False,
startrow=startrow + 1,
startcol=startcol,
sheet_name="poo",
)
result = pd.read_excel(tmp_excel, sheet_name="poo", engine="openpyxl")
expected = DataFrame({"greeting": greeting, "goodbye": goodbye})
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"if_sheet_exists,msg",
[
(
"invalid",
"'invalid' is not valid for if_sheet_exists. Valid options "
"are 'error', 'new', 'replace' and 'overlay'.",
),
(
"error",
"Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",
),
(
None,
"Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",
),
],
)
def test_if_sheet_exists_raises(tmp_excel, if_sheet_exists, msg):
# GH 40230
df = DataFrame({"fruit": ["pear"]})
df.to_excel(tmp_excel, sheet_name="foo", engine="openpyxl")
with pytest.raises(ValueError, match=re.escape(msg)):
with ExcelWriter(
tmp_excel, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists
) as writer:
df.to_excel(writer, sheet_name="foo")
def test_to_excel_with_openpyxl_engine(tmp_excel):
# GH 29854
df1 = DataFrame({"A": np.linspace(1, 10, 10)})
df2 = DataFrame({"B": np.linspace(1, 20, 10)})
df = pd.concat([df1, df2], axis=1)
styled = df.style.map(
lambda val: f"color: {'red' if val < 0 else 'black'}"
).highlight_max()
styled.to_excel(tmp_excel, engine="openpyxl")
@pytest.mark.parametrize("read_only", [True, False])
def test_read_workbook(datapath, ext, read_only):
# GH 39528
filename = datapath("io", "data", "excel", "test1" + ext)
with contextlib.closing(
openpyxl.load_workbook(filename, read_only=read_only)
) as wb:
result = pd.read_excel(wb, engine="openpyxl")
expected = pd.read_excel(filename)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"header, expected_data",
[
(
0,
{
"Title": [np.nan, "A", 1, 2, 3],
"Unnamed: 1": [np.nan, "B", 4, 5, 6],
"Unnamed: 2": [np.nan, "C", 7, 8, 9],
},
),
(2, {"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}),
],
)
@pytest.mark.parametrize(
"filename", ["dimension_missing", "dimension_small", "dimension_large"]
)
# When read_only is None, use read_excel instead of a workbook
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_with_bad_dimension(
datapath, ext, header, expected_data, filename, read_only
):
# GH 38956, 39001 - no/incorrect dimension information
path = datapath("io", "data", "excel", f"{filename}{ext}")
if read_only is None:
result = pd.read_excel(path, header=header)
else:
with contextlib.closing(
openpyxl.load_workbook(path, read_only=read_only)
) as wb:
result = pd.read_excel(wb, engine="openpyxl", header=header)
expected = DataFrame(expected_data)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"filename", ["dimension_missing", "dimension_small", "dimension_large"]
)
def test_read_with_bad_dimension_skiprows_callable_all(datapath, ext, filename):
# GH 64027
path = datapath("io", "data", "excel", f"{filename}{ext}")
result = pd.read_excel(path, skiprows=lambda _: True, nrows=1)
expected = DataFrame()
tm.assert_frame_equal(result, expected)
def test_append_mode_file(tmp_excel):
# GH 39576
df = DataFrame()
df.to_excel(tmp_excel, engine="openpyxl")
with ExcelWriter(
tmp_excel, mode="a", engine="openpyxl", if_sheet_exists="new"
) as writer:
df.to_excel(writer)
# make sure that zip files are not concatenated by making sure that
# "docProps/app.xml" only occurs twice in the file
data = Path(tmp_excel).read_bytes()
first = data.find(b"docProps/app.xml")
second = data.find(b"docProps/app.xml", first + 1)
third = data.find(b"docProps/app.xml", second + 1)
assert second != -1 and third == -1
# When read_only is None, use read_excel instead of a workbook
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_with_empty_trailing_rows(datapath, ext, read_only):
# GH 39181
path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}")
if read_only is None:
result = pd.read_excel(path)
else:
with contextlib.closing(
openpyxl.load_workbook(path, read_only=read_only)
) as wb:
result = pd.read_excel(wb, engine="openpyxl")
expected = DataFrame(
{
"Title": [np.nan, "A", 1, 2, 3],
"Unnamed: 1": [np.nan, "B", 4, 5, 6],
"Unnamed: 2": [np.nan, "C", 7, 8, 9],
}
)
tm.assert_frame_equal(result, expected)
# When read_only is None, use read_excel instead of a workbook
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_empty_with_blank_row(datapath, ext, read_only):
# GH 39547 - empty excel file with a row that has no data
path = datapath("io", "data", "excel", f"empty_with_blank_row{ext}")
if read_only is None:
result = pd.read_excel(path)
else:
with contextlib.closing(
openpyxl.load_workbook(path, read_only=read_only)
) as wb:
result = pd.read_excel(wb, engine="openpyxl")
expected = DataFrame()
tm.assert_frame_equal(result, expected)
def test_book_and_sheets_consistent(tmp_excel):
# GH#45687 - Ensure sheets is updated if user modifies book
with ExcelWriter(tmp_excel, engine="openpyxl") as writer:
assert writer.sheets == {}
sheet = writer.book.create_sheet("test_name", 0)
assert writer.sheets == {"test_name": sheet}
def test_ints_spelled_with_decimals(datapath, ext):
# GH 46988 - openpyxl returns this sheet with floats
path = datapath("io", "data", "excel", f"ints_spelled_with_decimals{ext}")
result = pd.read_excel(path)
expected = DataFrame(range(2, 12), columns=[1])
tm.assert_frame_equal(result, expected)
def test_read_multiindex_header_no_index_names(datapath, ext):
# GH#47487
path = datapath("io", "data", "excel", f"multiindex_no_index_names{ext}")
result = pd.read_excel(path, index_col=[0, 1, 2], header=[0, 1, 2])
expected = DataFrame(
[[np.nan, "x", "x", "x"], ["x", np.nan, np.nan, np.nan]],
columns=pd.MultiIndex.from_tuples(
[("X", "Y", "A1"), ("X", "Y", "A2"), ("XX", "YY", "B1"), ("XX", "YY", "B2")]
),
index=pd.MultiIndex.from_tuples([("A", "AA", "AAA"), ("A", "BB", "BBB")]),
)
tm.assert_frame_equal(result, expected) | python | github | https://github.com/pandas-dev/pandas | pandas/tests/io/excel/test_openpyxl.py |
"""
This is a straightforward Python wrapper for ssdeep by Jesse Kornblum,
which is a library for computing Context Triggered Piecewise Hashes (CTPH).
"""
import os
import six
from ssdeep.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from ssdeep.binding import Binding
binding = Binding()
ffi = binding.ffi
class BaseError(Exception):
"""The base for all other Exceptions"""
pass
class InternalError(BaseError):
"""Raised if lib returns internal error"""
pass
class Hash(object):
"""
Hashlib like object. It is only supported with ssdeep/libfuzzy >= 2.10.
:raises InternalError: If lib returns internal error
:raises NotImplementedError: Required functions are not available
"""
def __init__(self):
self._state = ffi.NULL
if not hasattr(binding.lib, "fuzzy_new"):
raise NotImplementedError("Only supported with ssdeep >= 2.10")
self._state = binding.lib.fuzzy_new()
if self._state == ffi.NULL:
raise InternalError("Unable to create state object")
def update(self, buf, encoding="utf-8"):
"""
Feed the data contained in the given buffer to the state.
:param String|Byte buf: The data to be hashed
:param String encoding: Encoding is used if buf is String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not Bytes, String or Unicode
"""
if self._state == ffi.NULL:
raise InternalError("State object is NULL")
if isinstance(buf, six.text_type):
buf = buf.encode(encoding)
if not isinstance(buf, six.binary_type):
raise TypeError(
"Argument must be of string, unicode or bytes type not "
"'%r'" % type(buf)
)
if binding.lib.fuzzy_update(self._state, buf, len(buf)) != 0:
binding.lib.fuzzy_free(self._state)
raise InternalError("Invalid state object")
def digest(self, elimseq=False, notrunc=False):
"""
Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
"""
if self._state == ffi.NULL:
raise InternalError("State object is NULL")
flags = (binding.lib.FUZZY_FLAG_ELIMSEQ if elimseq else 0) | \
(binding.lib.FUZZY_FLAG_NOTRUNC if notrunc else 0)
result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
if binding.lib.fuzzy_digest(self._state, result, flags) != 0:
raise InternalError("Function returned an unexpected error code")
return ffi.string(result).decode("ascii")
def __del__(self):
if self._state != ffi.NULL:
binding.lib.fuzzy_free(self._state)
class PseudoHash(object):
"""
Hashlib like object. Use this class only if Hash() isn't supported by your
ssdeep/libfuzzy library. This class stores the provided data in memory, so
be careful when hashing large files.
"""
def __init__(self):
self._data = b""
def update(self, buf, encoding="utf-8"):
"""
Feed the data contained in the given buffer to the state.
:param String|Byte buf: The data to be hashed
:param String encoding: Encoding is used if buf is String
:raises TypeError: If buf is not Bytes, String or Unicode
"""
if isinstance(buf, six.text_type):
buf = buf.encode(encoding)
if not isinstance(buf, six.binary_type):
raise TypeError(
"Argument must be of string, unicode or bytes type not "
"'%r'" % type(buf)
)
self._data = self._data + buf
def digest(self, elimseq=False, notrunc=False):
"""
Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
"""
return hash(self._data)
def compare(sig1, sig2):
"""
Computes the match score between two fuzzy hash signatures.
Returns a value from zero to 100 indicating the match score of the
two signatures. A match score of zero indicates the signatures
did not match.
:param Bytes|String sig1: First fuzzy hash signature
:param Bytes|String sig2: Second fuzzy hash signature
:return: Match score (0-100)
:rtype: Integer
:raises InternalError: If lib returns an internal error
:raises TypeError: If sig is not String, Unicode or Bytes
"""
if isinstance(sig1, six.text_type):
sig1 = sig1.encode("ascii")
if isinstance(sig2, six.text_type):
sig2 = sig2.encode("ascii")
if not isinstance(sig1, six.binary_type):
raise TypeError(
"First argument must be of string, unicode or bytes type not "
"'%s'" % type(sig1)
)
if not isinstance(sig2, six.binary_type):
raise TypeError(
"Second argument must be of string, unicode or bytes type not "
"'%r'" % type(sig2)
)
res = binding.lib.fuzzy_compare(sig1, sig2)
if res < 0:
raise InternalError("Function returned an unexpected error code")
return res
def hash(buf, encoding="utf-8"):
"""
Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes
"""
if isinstance(buf, six.text_type):
buf = buf.encode(encoding)
if not isinstance(buf, six.binary_type):
raise TypeError(
"Argument must be of string, unicode or bytes type not "
"'%r'" % type(buf)
)
# allocate memory for result
result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
if binding.lib.fuzzy_hash_buf(buf, len(buf), result) != 0:
raise InternalError("Function returned an unexpected error code")
return ffi.string(result).decode("ascii")
def hash_from_file(filename):
"""
Compute the fuzzy hash of a file.
Opens, reads, and hashes the contents of the file 'filename'
:param String|Bytes filename: The name of the file to be hashed
:return: The fuzzy hash of the file
:rtype: String
:raises IOError: If Python is unable to read the file
:raises InternalError: If lib returns an internal error
"""
if not os.path.exists(filename):
raise IOError("Path not found")
if not os.path.isfile(filename):
raise IOError("File not found")
if not os.access(filename, os.R_OK):
raise IOError("File is not readable")
result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
if binding.lib.fuzzy_hash_filename(filename.encode("utf-8"), result) != 0:
raise InternalError("Function returned an unexpected error code")
return ffi.string(result).decode("ascii") | unknown | codeparrot/codeparrot-clean | ||
from test.support import verbose
import unittest
import locale
import sys
import codecs
class BaseLocalizedTest(unittest.TestCase):
#
# Base class for tests using a real locale
#
@classmethod
def setUpClass(cls):
if sys.platform == 'darwin':
import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
if int(os.uname().release.split('.')[0]) < 10:
# The locale test work fine on OSX 10.6, I (ronaldoussoren)
# haven't had time yet to verify if tests work on OSX 10.5
# (10.4 is known to be bad)
raise unittest.SkipTest("Locale support on MacOSX is minimal")
elif sys.platform.startswith("win"):
tlocs = ("En", "English")
else:
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1",
"en_US.US-ASCII", "en_US")
try:
oldlocale = locale.setlocale(locale.LC_NUMERIC)
for tloc in tlocs:
try:
locale.setlocale(locale.LC_NUMERIC, tloc)
except locale.Error:
continue
break
else:
raise unittest.SkipTest("Test locale not supported "
"(tried %s)" % (', '.join(tlocs)))
cls.enUS_locale = tloc
finally:
locale.setlocale(locale.LC_NUMERIC, oldlocale)
def setUp(self):
oldlocale = locale.setlocale(self.locale_type)
self.addCleanup(locale.setlocale, self.locale_type, oldlocale)
locale.setlocale(self.locale_type, self.enUS_locale)
if verbose:
print("testing with %r..." % self.enUS_locale, end=' ', flush=True)
class BaseCookedTest(unittest.TestCase):
#
# Base class for tests using cooked localeconv() values
#
def setUp(self):
locale._override_localeconv = self.cooked_values
def tearDown(self):
locale._override_localeconv = {}
class CCookedTest(BaseCookedTest):
# A cooked "C" locale
cooked_values = {
'currency_symbol': '',
'decimal_point': '.',
'frac_digits': 127,
'grouping': [],
'int_curr_symbol': '',
'int_frac_digits': 127,
'mon_decimal_point': '',
'mon_grouping': [],
'mon_thousands_sep': '',
'n_cs_precedes': 127,
'n_sep_by_space': 127,
'n_sign_posn': 127,
'negative_sign': '',
'p_cs_precedes': 127,
'p_sep_by_space': 127,
'p_sign_posn': 127,
'positive_sign': '',
'thousands_sep': ''
}
class EnUSCookedTest(BaseCookedTest):
# A cooked "en_US" locale
cooked_values = {
'currency_symbol': '$',
'decimal_point': '.',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'USD ',
'int_frac_digits': 2,
'mon_decimal_point': '.',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ',',
'n_cs_precedes': 1,
'n_sep_by_space': 0,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 1,
'p_sep_by_space': 0,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ','
}
class FrFRCookedTest(BaseCookedTest):
# A cooked "fr_FR" locale with a space character as decimal separator
# and a non-ASCII currency symbol.
cooked_values = {
'currency_symbol': '\u20ac',
'decimal_point': ',',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'EUR ',
'int_frac_digits': 2,
'mon_decimal_point': ',',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ' ',
'n_cs_precedes': 0,
'n_sep_by_space': 1,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 0,
'p_sep_by_space': 1,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ' '
}
class BaseFormattingTest(object):
#
# Utility functions for formatting tests
#
def _test_formatfunc(self, format, value, out, func, **format_opts):
self.assertEqual(
func(format, value, **format_opts), out)
def _test_format(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format, **format_opts)
def _test_format_string(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format_string, **format_opts)
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
class EnUSNumberFormatting(BaseFormattingTest):
# XXX there is a grouping + padding bug when the thousands separator
# is empty but the grouping array contains values (e.g. Solaris 10)
def setUp(self):
self.sep = locale.localeconv()['thousands_sep']
def test_grouping(self):
self._test_format("%f", 1024, grouping=1, out='1%s024.000000' % self.sep)
self._test_format("%f", 102, grouping=1, out='102.000000')
self._test_format("%f", -42, grouping=1, out='-42.000000')
self._test_format("%+f", -42, grouping=1, out='-42.000000')
def test_grouping_and_padding(self):
self._test_format("%20.f", -42, grouping=1, out='-42'.rjust(20))
if self.sep:
self._test_format("%+10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).rjust(10))
self._test_format("%-10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).ljust(10))
def test_integer_grouping(self):
self._test_format("%d", 4200, grouping=True, out='4%s200' % self.sep)
self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep)
self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep)
def test_integer_grouping_and_padding(self):
self._test_format("%10d", 4200, grouping=True,
out=('4%s200' % self.sep).rjust(10))
self._test_format("%-10d", -4200, grouping=True,
out=('-4%s200' % self.sep).ljust(10))
def test_simple(self):
self._test_format("%f", 1024, grouping=0, out='1024.000000')
self._test_format("%f", 102, grouping=0, out='102.000000')
self._test_format("%f", -42, grouping=0, out='-42.000000')
self._test_format("%+f", -42, grouping=0, out='-42.000000')
def test_padding(self):
self._test_format("%20.f", -42, grouping=0, out='-42'.rjust(20))
self._test_format("%+10.f", -4200, grouping=0, out='-4200'.rjust(10))
self._test_format("%-10.f", 4200, grouping=0, out='4200'.ljust(10))
def test_complex_formatting(self):
# Spaces in formatting string
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
# Dots in formatting string
self._test_format_string(".%f.", 1000.0, out='.1000.000000.')
# Padding
if self.sep:
self._test_format_string("--> %10.2f", 4200, grouping=1,
out='--> ' + ('4%s200.00' % self.sep).rjust(10))
# Asterisk formats
self._test_format_string("%10.*f", (2, 1000), grouping=0,
out='1000.00'.rjust(10))
if self.sep:
self._test_format_string("%*.*f", (10, 2, 1000), grouping=1,
out=('1%s000.00' % self.sep).rjust(10))
# Test more-in-one
if self.sep:
self._test_format_string("int %i float %.2f str %s",
(1000, 1000.0, 'str'), grouping=1,
out='int 1%s000 float 1%s000.00 str str' %
(self.sep, self.sep))
class TestFormatPatternArg(unittest.TestCase):
# Test handling of pattern argument of format
def test_onlyOnePattern(self):
# Issue 2522: accept exactly one % pattern, and no extra chars.
self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo')
self.assertRaises(ValueError, locale.format, " %f", 'foo')
self.assertRaises(ValueError, locale.format, "%fg", 'foo')
self.assertRaises(ValueError, locale.format, "%^g", 'foo')
self.assertRaises(ValueError, locale.format, "%f%%", 'foo')
class TestLocaleFormatString(unittest.TestCase):
"""General tests on locale.format_string"""
def test_percent_escape(self):
self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0)
self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)),
'%d %f%%d' % (1, 1.0))
self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}),
('%(foo)s %%d' % {'foo': 'bar'}))
def test_mapping(self):
self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}),
('%(foo)s bing.' % {'foo': 'bar'}))
self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}),
('%(foo)s' % {'foo': 'bar'}))
class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
# Test number formatting with a real English locale.
locale_type = locale.LC_NUMERIC
def setUp(self):
BaseLocalizedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting):
# Test number formatting with a cooked "en_US" locale.
def setUp(self):
EnUSCookedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
def test_currency(self):
self._test_currency(50000, "$50000.00")
self._test_currency(50000, "$50,000.00", grouping=True)
self._test_currency(50000, "USD 50,000.00",
grouping=True, international=True)
class TestCNumberFormatting(CCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "C" locale.
def test_grouping(self):
self._test_format("%.2f", 12345.67, grouping=True, out='12345.67')
def test_grouping_and_padding(self):
self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67')
class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "fr_FR" locale.
def test_decimal_point(self):
self._test_format("%.2f", 12345.67, out='12345,67')
def test_grouping(self):
self._test_format("%.2f", 345.67, grouping=True, out='345,67')
self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67')
def test_grouping_and_padding(self):
self._test_format("%6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67')
self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67')
self._test_format("%-6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ')
self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ')
def test_integer_grouping(self):
self._test_format("%d", 200, grouping=True, out='200')
self._test_format("%d", 4200, grouping=True, out='4 200')
def test_integer_grouping_and_padding(self):
self._test_format("%4d", 4200, grouping=True, out='4 200')
self._test_format("%5d", 4200, grouping=True, out='4 200')
self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10))
self._test_format("%-4d", 4200, grouping=True, out='4 200')
self._test_format("%-5d", 4200, grouping=True, out='4 200')
self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10))
def test_currency(self):
euro = '\u20ac'
self._test_currency(50000, "50000,00 " + euro)
self._test_currency(50000, "50 000,00 " + euro, grouping=True)
# XXX is the trailing space a bug?
self._test_currency(50000, "50 000,00 EUR ",
grouping=True, international=True)
class TestCollation(unittest.TestCase):
# Test string collation functions
def test_strcoll(self):
self.assertLess(locale.strcoll('a', 'b'), 0)
self.assertEqual(locale.strcoll('a', 'a'), 0)
self.assertGreater(locale.strcoll('b', 'a'), 0)
def test_strxfrm(self):
self.assertLess(locale.strxfrm('a'), locale.strxfrm('b'))
class TestEnUSCollation(BaseLocalizedTest, TestCollation):
# Test string collation functions with a real English locale
locale_type = locale.LC_ALL
def setUp(self):
enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name
if enc not in ('utf-8', 'iso8859-1', 'cp1252'):
raise unittest.SkipTest('encoding not suitable')
if enc != 'iso8859-1' and (sys.platform == 'darwin' or
sys.platform.startswith('freebsd')):
raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs')
BaseLocalizedTest.setUp(self)
def test_strcoll_with_diacritic(self):
self.assertLess(locale.strcoll('à', 'b'), 0)
def test_strxfrm_with_diacritic(self):
self.assertLess(locale.strxfrm('à'), locale.strxfrm('b'))
class NormalizeTest(unittest.TestCase):
def check(self, localename, expected):
self.assertEqual(locale.normalize(localename), expected, msg=localename)
def test_locale_alias(self):
for localename, alias in locale.locale_alias.items():
with self.subTest(locale=(localename, alias)):
self.check(localename, alias)
def test_empty(self):
self.check('', '')
def test_c(self):
self.check('c', 'C')
self.check('posix', 'C')
def test_english(self):
self.check('en', 'en_US.ISO8859-1')
self.check('EN', 'en_US.ISO8859-1')
self.check('en.iso88591', 'en_US.ISO8859-1')
self.check('en_US', 'en_US.ISO8859-1')
self.check('en_us', 'en_US.ISO8859-1')
self.check('en_GB', 'en_GB.ISO8859-1')
self.check('en_US.UTF-8', 'en_US.UTF-8')
self.check('en_US.utf8', 'en_US.UTF-8')
self.check('en_US:UTF-8', 'en_US.UTF-8')
self.check('en_US.ISO8859-1', 'en_US.ISO8859-1')
self.check('en_US.US-ASCII', 'en_US.ISO8859-1')
self.check('en_US.88591', 'en_US.ISO8859-1')
self.check('en_US.885915', 'en_US.ISO8859-15')
self.check('english', 'en_EN.ISO8859-1')
self.check('english_uk.ascii', 'en_GB.ISO8859-1')
def test_hyphenated_encoding(self):
self.check('az_AZ.iso88599e', 'az_AZ.ISO8859-9E')
self.check('az_AZ.ISO8859-9E', 'az_AZ.ISO8859-9E')
self.check('tt_RU.koi8c', 'tt_RU.KOI8-C')
self.check('tt_RU.KOI8-C', 'tt_RU.KOI8-C')
self.check('lo_LA.cp1133', 'lo_LA.IBM-CP1133')
self.check('lo_LA.ibmcp1133', 'lo_LA.IBM-CP1133')
self.check('lo_LA.IBM-CP1133', 'lo_LA.IBM-CP1133')
self.check('uk_ua.microsoftcp1251', 'uk_UA.CP1251')
self.check('uk_ua.microsoft-cp1251', 'uk_UA.CP1251')
self.check('ka_ge.georgianacademy', 'ka_GE.GEORGIAN-ACADEMY')
self.check('ka_GE.GEORGIAN-ACADEMY', 'ka_GE.GEORGIAN-ACADEMY')
self.check('cs_CZ.iso88592', 'cs_CZ.ISO8859-2')
self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2')
def test_euro_modifier(self):
self.check('de_DE@euro', 'de_DE.ISO8859-15')
self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15')
self.check('de_DE.utf8@euro', 'de_DE.UTF-8')
def test_latin_modifier(self):
self.check('be_BY.UTF-8@latin', 'be_BY.UTF-8@latin')
self.check('sr_RS.UTF-8@latin', 'sr_RS.UTF-8@latin')
self.check('sr_RS.UTF-8@latn', 'sr_RS.UTF-8@latin')
def test_valencia_modifier(self):
self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia')
self.check('ca_ES@valencia', 'ca_ES.ISO8859-15@valencia')
self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia')
def test_devanagari_modifier(self):
self.check('ks_IN.UTF-8@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks_IN@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks@devanagari', 'ks_IN.UTF-8@devanagari')
self.check('ks_IN.UTF-8', 'ks_IN.UTF-8')
self.check('ks_IN', 'ks_IN.UTF-8')
self.check('ks', 'ks_IN.UTF-8')
self.check('sd_IN.UTF-8@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd_IN@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd@devanagari', 'sd_IN.UTF-8@devanagari')
self.check('sd_IN.UTF-8', 'sd_IN.UTF-8')
self.check('sd_IN', 'sd_IN.UTF-8')
self.check('sd', 'sd_IN.UTF-8')
def test_euc_encoding(self):
self.check('ja_jp.euc', 'ja_JP.eucJP')
self.check('ja_jp.eucjp', 'ja_JP.eucJP')
self.check('ko_kr.euc', 'ko_KR.eucKR')
self.check('ko_kr.euckr', 'ko_KR.eucKR')
self.check('zh_cn.euc', 'zh_CN.eucCN')
self.check('zh_tw.euc', 'zh_TW.eucTW')
self.check('zh_tw.euctw', 'zh_TW.eucTW')
def test_japanese(self):
self.check('ja', 'ja_JP.eucJP')
self.check('ja.jis', 'ja_JP.JIS7')
self.check('ja.sjis', 'ja_JP.SJIS')
self.check('ja_jp', 'ja_JP.eucJP')
self.check('ja_jp.ajec', 'ja_JP.eucJP')
self.check('ja_jp.euc', 'ja_JP.eucJP')
self.check('ja_jp.eucjp', 'ja_JP.eucJP')
self.check('ja_jp.iso-2022-jp', 'ja_JP.JIS7')
self.check('ja_jp.iso2022jp', 'ja_JP.JIS7')
self.check('ja_jp.jis', 'ja_JP.JIS7')
self.check('ja_jp.jis7', 'ja_JP.JIS7')
self.check('ja_jp.mscode', 'ja_JP.SJIS')
self.check('ja_jp.pck', 'ja_JP.SJIS')
self.check('ja_jp.sjis', 'ja_JP.SJIS')
self.check('ja_jp.ujis', 'ja_JP.eucJP')
self.check('ja_jp.utf8', 'ja_JP.UTF-8')
self.check('japan', 'ja_JP.eucJP')
self.check('japanese', 'ja_JP.eucJP')
self.check('japanese-euc', 'ja_JP.eucJP')
self.check('japanese.euc', 'ja_JP.eucJP')
self.check('japanese.sjis', 'ja_JP.SJIS')
self.check('jp_jp', 'ja_JP.eucJP')
class TestMiscellaneous(unittest.TestCase):
def test_getpreferredencoding(self):
# Invoke getpreferredencoding to make sure it does not cause exceptions.
enc = locale.getpreferredencoding()
if enc:
# If encoding non-empty, make sure it is valid
codecs.lookup(enc)
def test_strcoll_3303(self):
# test crasher from bug #3303
self.assertRaises(TypeError, locale.strcoll, "a", None)
self.assertRaises(TypeError, locale.strcoll, b"a", None)
def test_setlocale_category(self):
locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_TIME)
locale.setlocale(locale.LC_CTYPE)
locale.setlocale(locale.LC_COLLATE)
locale.setlocale(locale.LC_MONETARY)
locale.setlocale(locale.LC_NUMERIC)
# crasher from bug #7419
self.assertRaises(locale.Error, locale.setlocale, 12345)
def test_getsetlocale_issue1813(self):
# Issue #1813: setting and getting the locale under a Turkish locale
oldlocale = locale.setlocale(locale.LC_CTYPE)
self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
try:
locale.setlocale(locale.LC_CTYPE, 'tr_TR')
except locale.Error:
# Unsupported locale on this system
self.skipTest('test needs Turkish locale')
loc = locale.getlocale(locale.LC_CTYPE)
if verbose:
print('got locale %a' % (loc,))
locale.setlocale(locale.LC_CTYPE, loc)
self.assertEqual(loc, locale.getlocale(locale.LC_CTYPE))
def test_invalid_locale_format_in_localetuple(self):
with self.assertRaises(TypeError):
locale.setlocale(locale.LC_ALL, b'fi_FI')
def test_invalid_iterable_in_localetuple(self):
with self.assertRaises(TypeError):
locale.setlocale(locale.LC_ALL, (b'not', b'valid'))
if __name__ == '__main__':
unittest.main() | unknown | codeparrot/codeparrot-clean | ||
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
* An event generated on the server intended for streaming to the client
* as part of the SSE streaming technique.
*
* @implements \IteratorAggregate<string>
*
* @author Yonel Ceruto <open@yceruto.dev>
*/
class ServerEvent implements \IteratorAggregate
{
/**
* @param string|iterable<string> $data The event data field for the message
* @param string|null $type The event type
* @param int|null $retry The number of milliseconds the client should wait
* before reconnecting in case of network failure
* @param string|null $id The event ID to set the EventSource object's last event ID value
* @param string|null $comment The event comment
*/
public function __construct(
private string|iterable $data,
private ?string $type = null,
private ?int $retry = null,
private ?string $id = null,
private ?string $comment = null,
) {
}
public function getData(): iterable|string
{
return $this->data;
}
/**
* @return $this
*/
public function setData(iterable|string $data): static
{
$this->data = $data;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
/**
* @return $this
*/
public function setType(string $type): static
{
$this->type = $type;
return $this;
}
public function getRetry(): ?int
{
return $this->retry;
}
/**
* @return $this
*/
public function setRetry(?int $retry): static
{
$this->retry = $retry;
return $this;
}
public function getId(): ?string
{
return $this->id;
}
/**
* @return $this
*/
public function setId(string $id): static
{
$this->id = $id;
return $this;
}
public function getComment(): ?string
{
return $this->comment;
}
public function setComment(string $comment): static
{
$this->comment = $comment;
return $this;
}
/**
* @return \Traversable<string>
*/
public function getIterator(): \Traversable
{
static $lastRetry = null;
$head = '';
if ($this->comment) {
$head .= \sprintf(': %s', $this->comment)."\n";
}
if ($this->id) {
$head .= \sprintf('id: %s', $this->id)."\n";
}
if ($this->retry > 0 && $this->retry !== $lastRetry) {
$head .= \sprintf('retry: %s', $lastRetry = $this->retry)."\n";
}
if ($this->type) {
$head .= \sprintf('event: %s', $this->type)."\n";
}
yield $head;
if (is_iterable($this->data)) {
foreach ($this->data as $data) {
yield \sprintf('data: %s', $data)."\n";
}
} elseif ('' !== $this->data) {
yield \sprintf('data: %s', $this->data)."\n";
}
yield "\n";
}
} | php | github | https://github.com/symfony/symfony | src/Symfony/Component/HttpFoundation/ServerEvent.php |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
Test.Summary = '''
Test a basic regex_revalidate
'''
## Test description:
# Load up cache, ensure fresh
# Create regex reval rule, config reload:
# ensure item is staled only once.
# Add a new rule, config reload:
# ensure item isn't restaled again, but rule still in effect.
#
# If the rule disappears from regex_revalidate.conf its still loaded!!
# A rule's expiry can't be changed after the fact!
Test.SkipUnless(
Condition.PluginExists('regex_revalidate.so'),
Condition.PluginExists('xdebug.so')
)
Test.ContinueOnFail = False
# configure origin server
server = Test.MakeOriginServer("server")
# Define ATS and configure
ts = Test.MakeATSProcess("ts", command="traffic_manager", select_ports=True)
#**testname is required**
#testName = "regex_reval"
# default root
request_header_0 = {"headers":
"GET / HTTP/1.1\r\n" +
"Host: www.example.com\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "",
}
response_header_0 = {"headers":
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
"Cache-Control: max-age=300\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "xxx",
}
# cache item path1
request_header_1 = {"headers":
"GET /path1 HTTP/1.1\r\n" +
"Host: www.example.com\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": ""
}
response_header_1 = {"headers":
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
'Etag: "path1"\r\n' +
"Cache-Control: max-age=600,public\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "abc"
}
# cache item path1a
request_header_2 = {"headers":
"GET /path1a HTTP/1.1\r\n" +
"Host: www.example.com\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": ""
}
response_header_2 = {"headers":
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
'Etag: "path1a"\r\n' +
"Cache-Control: max-age=600,public\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "cde"
}
# cache item path2a
request_header_3 = {"headers":
"GET /path2a HTTP/1.1\r\n" +
"Host: www.example.com\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": ""
}
response_header_3 = {"headers":
"HTTP/1.1 200 OK\r\n" +
"Connection: close\r\n" +
'Etag: "path2a"\r\n' +
"Cache-Control: max-age=900,public\r\n" +
"\r\n",
"timestamp": "1469733493.993",
"body": "efg"
}
server.addResponse("sessionlog.json", request_header_0, response_header_0)
server.addResponse("sessionlog.json", request_header_1, response_header_1)
server.addResponse("sessionlog.json", request_header_2, response_header_2)
server.addResponse("sessionlog.json", request_header_3, response_header_3)
# Configure ATS server
ts.Disk.plugin_config.AddLine('xdebug.so')
ts.Disk.plugin_config.AddLine(
'regex_revalidate.so -d -c regex_revalidate.conf'
)
regex_revalidate_conf_path = os.path.join(ts.Variables.CONFIGDIR, 'regex_revalidate.conf')
curl_and_args = 'curl -s -D - -v -H "x-debug: x-cache" -H "Host: www.example.com"'
path1_rule = 'path1 {}\n'.format(int(time.time()) + 600)
# Define first revistion for when trafficserver starts
ts.Disk.File(regex_revalidate_conf_path, typename="ats:config").AddLines([
"# Empty\n"
])
ts.Disk.remap_config.AddLine(
'map / http://127.0.0.1:{}'.format(server.Variables.Port)
)
# minimal configuration
ts.Disk.records_config.update({
'proxy.config.diags.debug.enabled': 1,
'proxy.config.diags.debug.tags': 'regex_revalidate',
# 'proxy.config.diags.debug.enabled': 0,
'proxy.config.http.cache.http': 1,
'proxy.config.http.wait_for_cache': 1,
'proxy.config.http.insert_age_in_response': 0,
'proxy.config.http.response_via_str': 3,
})
# 0 Test - Load cache (miss) (path1)
tr = Test.AddTestRun("Cache miss path1")
tr.Processes.Default.StartBefore(server)
tr.Processes.Default.StartBefore(Test.Processes.ts)
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-miss.gold"
tr.StillRunningAfter = ts
# 1 Test - Load cache (miss) for later test (path1a)
tr = Test.AddTestRun("Cache miss path1a")
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1a'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-miss.gold"
tr.StillRunningAfter = ts
# 2 Test - Load cache (miss) for later test (path2a)
tr = Test.AddTestRun("Cache miss path2a")
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path2a'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-miss.gold"
tr.StillRunningAfter = ts
# 3 Test - Cache hit path1
tr = Test.AddTestRun("Cache hit fresh path1")
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-hit.gold"
tr.StillRunningAfter = ts
# 4 Stage - Reload new regex_revalidate
tr = Test.AddTestRun("Reload config add path1")
tr.Disk.File(regex_revalidate_conf_path, typename="ats:config").AddLines([
path1_rule
])
tr.StillRunningAfter = ts
tr.StillRunningAfter = server
tr.Processes.Default.Command = 'traffic_ctl config reload'
# Need to copy over the environment so traffic_ctl knows where to find the unix domain socket
tr.Processes.Default.Env = ts.Env
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.TimeOut = 5
tr.TimeOut = 5
# 5 Test - Revalidate path1
tr = Test.AddTestRun("Revalidate stale path1")
tr.DelayStart = 5
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-stale.gold"
tr.StillRunningAfter = ts
# 6 Test - Cache hit (path1)
tr = Test.AddTestRun("Cache hit fresh path1")
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-hit.gold"
tr.StillRunningAfter = ts
# 7 Stage - Reload new regex_revalidate
tr = Test.AddTestRun("Reload config add path2")
tr.Disk.File(regex_revalidate_conf_path, typename="ats:config").AddLines([
path1_rule,
'path2 {}\n'.format(int(time.time()) + 700)
])
tr.StillRunningAfter = ts
tr.StillRunningAfter = server
tr.Processes.Default.Command = 'traffic_ctl config reload'
# Need to copy over the environment so traffic_ctl knows where to find the unix domain socket
tr.Processes.Default.Env = ts.Env
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.TimeOut = 5
tr.TimeOut = 5
# 8 Test - Cache hit (path1)
tr = Test.AddTestRun("Cache hit fresh path1")
tr.DelayStart = 5
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-hit.gold"
tr.StillRunningAfter = ts
# 9 Test - Cache stale (check rule is still loaded) (path1a)
tr = Test.AddTestRun("Revalidate stale path1a")
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path1a'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-stale.gold"
tr.StillRunningAfter = ts
# The C version of regex_revalidate doesn't allow an existing rule to
# be changed by a reload.
# 10 Stage - regex_revalidate rewrite rule early expire
tr = Test.AddTestRun("Reload config change path2")
tr.Disk.File(regex_revalidate_conf_path, typename="ats:config").AddLines([
path1_rule,
'path2 {}\n'.format(int(time.time()) - 100),
])
tr.StillRunningAfter = ts
tr.StillRunningAfter = server
tr.Processes.Default.Command = 'traffic_ctl config reload'
# Need to copy over the environment so traffic_ctl knows where to find the unix domain socket
tr.Processes.Default.Env = ts.Env
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.TimeOut = 5
tr.TimeOut = 5
# 11 Test - Cache hit (path2a)
tr = Test.AddTestRun("Cache hit stale path2a")
tr.DelayStart = 5
tr.Processes.Default.Command = curl_and_args + ' http://127.0.0.1:{}/path2a'.format(ts.Variables.port)
tr.Processes.Default.ReturnCode = 0
tr.Processes.Default.Streams.stdout = "gold/regex_reval-stale.gold"
tr.StillRunningAfter = ts | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# Copyright (c) 2011 Blue Pines Technologies LLC, Brad Carleton
# www.bluepines.org
# Copyright (c) 2012 42 Lines Inc., Jim Browne
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.route53 import exception
import random
import uuid
import xml.sax
import boto
from boto.connection import AWSAuthConnection
from boto import handler
import boto.jsonresponse
from boto.route53.record import ResourceRecordSets
from boto.route53.zone import Zone
from boto.compat import six, urllib
HZXML = """<?xml version="1.0" encoding="UTF-8"?>
<CreateHostedZoneRequest xmlns="%(xmlns)s">
<Name>%(name)s</Name>
<CallerReference>%(caller_ref)s</CallerReference>
<HostedZoneConfig>
<Comment>%(comment)s</Comment>
</HostedZoneConfig>
</CreateHostedZoneRequest>"""
# boto.set_stream_logger('dns')
class Route53Connection(AWSAuthConnection):
DefaultHost = 'route53.amazonaws.com'
"""The default Route53 API endpoint to connect to."""
Version = '2013-04-01'
"""Route53 API version."""
XMLNameSpace = 'https://route53.amazonaws.com/doc/2013-04-01/'
"""XML schema for this Route53 API version."""
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
port=None, proxy=None, proxy_port=None,
host=DefaultHost, debug=0, security_token=None,
validate_certs=True, https_connection_factory=None,
profile_name=None):
super(Route53Connection, self).__init__(
host,
aws_access_key_id, aws_secret_access_key,
True, port, proxy, proxy_port, debug=debug,
security_token=security_token,
validate_certs=validate_certs,
https_connection_factory=https_connection_factory,
profile_name=profile_name)
def _required_auth_capability(self):
return ['route53']
def make_request(self, action, path, headers=None, data='', params=None):
if params:
pairs = []
for key, val in six.iteritems(params):
if val is None:
continue
pairs.append(key + '=' + urllib.parse.quote(str(val)))
path += '?' + '&'.join(pairs)
return super(Route53Connection, self).make_request(
action, path, headers, data,
retry_handler=self._retry_handler)
# Hosted Zones
def get_all_hosted_zones(self, start_marker=None, zone_list=None):
"""
Returns a Python data structure with information about all
Hosted Zones defined for the AWS account.
:param int start_marker: start marker to pass when fetching additional
results after a truncated list
:param list zone_list: a HostedZones list to prepend to results
"""
params = {}
if start_marker:
params = {'marker': start_marker}
response = self.make_request('GET', '/%s/hostedzone' % self.Version,
params=params)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element(list_marker='HostedZones',
item_marker=('HostedZone',))
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
if zone_list:
e['ListHostedZonesResponse']['HostedZones'].extend(zone_list)
while 'NextMarker' in e['ListHostedZonesResponse']:
next_marker = e['ListHostedZonesResponse']['NextMarker']
zone_list = e['ListHostedZonesResponse']['HostedZones']
e = self.get_all_hosted_zones(next_marker, zone_list)
return e
def get_hosted_zone(self, hosted_zone_id):
"""
Get detailed information about a particular Hosted Zone.
:type hosted_zone_id: str
:param hosted_zone_id: The unique identifier for the Hosted Zone
"""
uri = '/%s/hostedzone/%s' % (self.Version, hosted_zone_id)
response = self.make_request('GET', uri)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element(list_marker='NameServers',
item_marker=('NameServer',))
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
def get_hosted_zone_by_name(self, hosted_zone_name):
"""
Get detailed information about a particular Hosted Zone.
:type hosted_zone_name: str
:param hosted_zone_name: The fully qualified domain name for the Hosted
Zone
"""
if hosted_zone_name[-1] != '.':
hosted_zone_name += '.'
all_hosted_zones = self.get_all_hosted_zones()
for zone in all_hosted_zones['ListHostedZonesResponse']['HostedZones']:
# check that they gave us the FQDN for their zone
if zone['Name'] == hosted_zone_name:
return self.get_hosted_zone(zone['Id'].split('/')[-1])
def create_hosted_zone(self, domain_name, caller_ref=None, comment=''):
"""
Create a new Hosted Zone. Returns a Python data structure with
information about the newly created Hosted Zone.
:type domain_name: str
:param domain_name: The name of the domain. This should be a
fully-specified domain, and should end with a final period
as the last label indication. If you omit the final period,
Amazon Route 53 assumes the domain is relative to the root.
This is the name you have registered with your DNS registrar.
It is also the name you will delegate from your registrar to
the Amazon Route 53 delegation servers returned in
response to this request.A list of strings with the image
IDs wanted.
:type caller_ref: str
:param caller_ref: A unique string that identifies the request
and that allows failed CreateHostedZone requests to be retried
without the risk of executing the operation twice. If you don't
provide a value for this, boto will generate a Type 4 UUID and
use that.
:type comment: str
:param comment: Any comments you want to include about the hosted
zone.
"""
if caller_ref is None:
caller_ref = str(uuid.uuid4())
params = {'name': domain_name,
'caller_ref': caller_ref,
'comment': comment,
'xmlns': self.XMLNameSpace}
xml_body = HZXML % params
uri = '/%s/hostedzone' % self.Version
response = self.make_request('POST', uri,
{'Content-Type': 'text/xml'}, xml_body)
body = response.read()
boto.log.debug(body)
if response.status == 201:
e = boto.jsonresponse.Element(list_marker='NameServers',
item_marker=('NameServer',))
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
else:
raise exception.DNSServerError(response.status,
response.reason,
body)
def delete_hosted_zone(self, hosted_zone_id):
"""
Delete the hosted zone specified by the given id.
:type hosted_zone_id: str
:param hosted_zone_id: The hosted zone's id
"""
uri = '/%s/hostedzone/%s' % (self.Version, hosted_zone_id)
response = self.make_request('DELETE', uri)
body = response.read()
boto.log.debug(body)
if response.status not in (200, 204):
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element()
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
# Health checks
POSTHCXMLBody = """<CreateHealthCheckRequest xmlns="%(xmlns)s">
<CallerReference>%(caller_ref)s</CallerReference>
%(health_check)s
</CreateHealthCheckRequest>"""
def create_health_check(self, health_check, caller_ref=None):
"""
Create a new Health Check
:type health_check: HealthCheck
:param health_check: HealthCheck object
:type caller_ref: str
:param caller_ref: A unique string that identifies the request
and that allows failed CreateHealthCheckRequest requests to be retried
without the risk of executing the operation twice. If you don't
provide a value for this, boto will generate a Type 4 UUID and
use that.
"""
if caller_ref is None:
caller_ref = str(uuid.uuid4())
uri = '/%s/healthcheck' % self.Version
params = {'xmlns': self.XMLNameSpace,
'caller_ref': caller_ref,
'health_check': health_check.to_xml()
}
xml_body = self.POSTHCXMLBody % params
response = self.make_request('POST', uri, {'Content-Type': 'text/xml'}, xml_body)
body = response.read()
boto.log.debug(body)
if response.status == 201:
e = boto.jsonresponse.Element()
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
else:
raise exception.DNSServerError(response.status, response.reason, body)
def get_list_health_checks(self, maxitems=None, marker=None):
"""
Return a list of health checks
:type maxitems: int
:param maxitems: Maximum number of items to return
:type marker: str
:param marker: marker to get next set of items to list
"""
params = {}
if maxitems is not None:
params['maxitems'] = maxitems
if marker is not None:
params['marker'] = marker
uri = '/%s/healthcheck' % (self.Version, )
response = self.make_request('GET', uri, params=params)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element(list_marker='HealthChecks', item_marker=('HealthCheck',))
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
def delete_health_check(self, health_check_id):
"""
Delete a health check
:type health_check_id: str
:param health_check_id: ID of the health check to delete
"""
uri = '/%s/healthcheck/%s' % (self.Version, health_check_id)
response = self.make_request('DELETE', uri)
body = response.read()
boto.log.debug(body)
if response.status not in (200, 204):
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element()
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
# Resource Record Sets
def get_all_rrsets(self, hosted_zone_id, type=None,
name=None, identifier=None, maxitems=None):
"""
Retrieve the Resource Record Sets defined for this Hosted Zone.
Returns the raw XML data returned by the Route53 call.
:type hosted_zone_id: str
:param hosted_zone_id: The unique identifier for the Hosted Zone
:type type: str
:param type: The type of resource record set to begin the record
listing from. Valid choices are:
* A
* AAAA
* CNAME
* MX
* NS
* PTR
* SOA
* SPF
* SRV
* TXT
Valid values for weighted resource record sets:
* A
* AAAA
* CNAME
* TXT
Valid values for Zone Apex Aliases:
* A
* AAAA
:type name: str
:param name: The first name in the lexicographic ordering of domain
names to be retrieved
:type identifier: str
:param identifier: In a hosted zone that includes weighted resource
record sets (multiple resource record sets with the same DNS
name and type that are differentiated only by SetIdentifier),
if results were truncated for a given DNS name and type,
the value of SetIdentifier for the next resource record
set that has the current DNS name and type
:type maxitems: int
:param maxitems: The maximum number of records
"""
params = {'type': type, 'name': name,
'identifier': identifier, 'maxitems': maxitems}
uri = '/%s/hostedzone/%s/rrset' % (self.Version, hosted_zone_id)
response = self.make_request('GET', uri, params=params)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
rs = ResourceRecordSets(connection=self, hosted_zone_id=hosted_zone_id)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
def change_rrsets(self, hosted_zone_id, xml_body):
"""
Create or change the authoritative DNS information for this
Hosted Zone.
Returns a Python data structure with information about the set of
changes, including the Change ID.
:type hosted_zone_id: str
:param hosted_zone_id: The unique identifier for the Hosted Zone
:type xml_body: str
:param xml_body: The list of changes to be made, defined in the
XML schema defined by the Route53 service.
"""
uri = '/%s/hostedzone/%s/rrset' % (self.Version, hosted_zone_id)
response = self.make_request('POST', uri,
{'Content-Type': 'text/xml'},
xml_body)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element()
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
def get_change(self, change_id):
"""
Get information about a proposed set of changes, as submitted
by the change_rrsets method.
Returns a Python data structure with status information about the
changes.
:type change_id: str
:param change_id: The unique identifier for the set of changes.
This ID is returned in the response to the change_rrsets method.
"""
uri = '/%s/change/%s' % (self.Version, change_id)
response = self.make_request('GET', uri)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise exception.DNSServerError(response.status,
response.reason,
body)
e = boto.jsonresponse.Element()
h = boto.jsonresponse.XmlHandler(e, None)
h.parse(body)
return e
def create_zone(self, name):
"""
Create a new Hosted Zone. Returns a Zone object for the newly
created Hosted Zone.
:type name: str
:param name: The name of the domain. This should be a
fully-specified domain, and should end with a final period
as the last label indication. If you omit the final period,
Amazon Route 53 assumes the domain is relative to the root.
This is the name you have registered with your DNS registrar.
It is also the name you will delegate from your registrar to
the Amazon Route 53 delegation servers returned in
response to this request.
"""
zone = self.create_hosted_zone(name)
return Zone(self, zone['CreateHostedZoneResponse']['HostedZone'])
def get_zone(self, name):
"""
Returns a Zone object for the specified Hosted Zone.
:param name: The name of the domain. This should be a
fully-specified domain, and should end with a final period
as the last label indication.
"""
name = self._make_qualified(name)
for zone in self.get_zones():
if name == zone.name:
return zone
def get_zones(self):
"""
Returns a list of Zone objects, one for each of the Hosted
Zones defined for the AWS account.
:rtype: list
:returns: A list of Zone objects.
"""
zones = self.get_all_hosted_zones()
return [Zone(self, zone) for zone in
zones['ListHostedZonesResponse']['HostedZones']]
def _make_qualified(self, value):
"""
Ensure passed domain names end in a period (.) character.
This will usually make a domain fully qualified.
"""
if type(value) in [list, tuple, set]:
new_list = []
for record in value:
if record and not record[-1] == '.':
new_list.append("%s." % record)
else:
new_list.append(record)
return new_list
else:
value = value.strip()
if value and not value[-1] == '.':
value = "%s." % value
return value
def _retry_handler(self, response, i, next_sleep):
status = None
boto.log.debug("Saw HTTP status: %s" % response.status)
if response.status == 400:
code = response.getheader('Code')
if code:
# This is a case where we need to ignore a 400 error, as
# Route53 returns this. See
# http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html
if 'PriorRequestNotComplete' in code:
error = 'PriorRequestNotComplete'
elif 'Throttling' in code:
error = 'Throttling'
else:
return status
msg = "%s, retry attempt %s" % (
error,
i
)
next_sleep = min(random.random() * (2 ** i),
boto.config.get('Boto', 'max_retry_delay', 60))
i += 1
status = (msg, i, next_sleep)
return status | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for debugger functionalities in tf.Session."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import glob
import os
import shutil
import tempfile
import threading
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.util import event_pb2
from tensorflow.python.client import session
from tensorflow.python.debug.lib import debug_data
from tensorflow.python.debug.lib import debug_utils
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import parsing_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.platform import test
from tensorflow.python.training import gradient_descent
class SessionDebugTestBase(test_util.TensorFlowTestCase):
"""Base class for unit tests of tfdbg running with tf.Session."""
@classmethod
def setUpClass(cls):
if test.is_gpu_available():
cls._expected_partition_graph_count = 2
cls._expected_num_devices = 2
cls._main_device = "/job:localhost/replica:0/task:0/gpu:0"
else:
cls._expected_partition_graph_count = 1
cls._expected_num_devices = 1
cls._main_device = "/job:localhost/replica:0/task:0/cpu:0"
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
self._dump_root = tempfile.mkdtemp()
def tearDown(self):
ops.reset_default_graph()
# Tear down temporary dump directory.
if os.path.isdir(self._dump_root):
shutil.rmtree(self._dump_root)
def _debug_urls(self, run_number=None):
raise NotImplementedError(
"_debug_urls() method is not implemented in the base test class.")
def _debug_dump_dir(self, run_number=None):
raise NotImplementedError(
"_debug_dump_dir() method is not implemented in the base test class.")
def _generate_dump_from_simple_addition_graph(self):
with session.Session() as sess:
u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]])
v_init_val = np.array([[2.0], [-1.0]])
# Use node names with overlapping namespace (i.e., parent directory) to
# test concurrent, non-racing directory creation.
u_name = "u"
v_name = "v"
w_name = "w"
u_init = constant_op.constant(u_init_val, shape=[2, 2])
u = variables.Variable(u_init, name=u_name)
v_init = constant_op.constant(v_init_val, shape=[2, 1])
v = variables.Variable(v_init, name=v_name)
w = math_ops.matmul(u, v, name=w_name)
u.initializer.run()
v.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_urls = "file://%s" % self._dump_root
# Add debug tensor watch for u.
debug_utils.add_debug_tensor_watch(
run_options, "%s/read" % u_name, 0, debug_urls=debug_urls)
# Add debug tensor watch for v.
debug_utils.add_debug_tensor_watch(
run_options, "%s/read" % v_name, 0, debug_urls=debug_urls)
run_metadata = config_pb2.RunMetadata()
# Invoke Session.run().
sess.run(w, options=run_options, run_metadata=run_metadata)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
simple_add_results = collections.namedtuple("SimpleAddResults", [
"u_init_val", "v_init_val", "u", "v", "w", "u_name", "v_name", "w_name",
"dump"
])
return simple_add_results(u_init_val, v_init_val, u, v, w, u_name, v_name,
w_name, dump)
def testConcurrentDumpingToPathsWithOverlappingParentDirsWorks(self):
results = self._generate_dump_from_simple_addition_graph()
self.assertTrue(results.dump.loaded_partition_graphs())
# Since global_step is not explicitly specified, it should take its default
# value: -1.
self.assertEqual(-1, results.dump.core_metadata.global_step)
self.assertGreaterEqual(results.dump.core_metadata.session_run_count, 0)
self.assertGreaterEqual(results.dump.core_metadata.executor_step_count, 0)
self.assertEqual([], results.dump.core_metadata.input_names)
self.assertEqual([results.w.name], results.dump.core_metadata.output_names)
self.assertEqual([], results.dump.core_metadata.target_nodes)
# Verify the dumped tensor values for u and v.
self.assertEqual(2, results.dump.size)
self.assertAllClose([results.u_init_val],
results.dump.get_tensors("%s/read" % results.u_name, 0,
"DebugIdentity"))
self.assertAllClose([results.v_init_val],
results.dump.get_tensors("%s/read" % results.v_name, 0,
"DebugIdentity"))
self.assertGreaterEqual(
results.dump.get_rel_timestamps("%s/read" % results.u_name, 0,
"DebugIdentity")[0], 0)
self.assertGreaterEqual(
results.dump.get_rel_timestamps("%s/read" % results.v_name, 0,
"DebugIdentity")[0], 0)
self.assertGreater(
results.dump.get_dump_sizes_bytes("%s/read" % results.u_name, 0,
"DebugIdentity")[0], 0)
self.assertGreater(
results.dump.get_dump_sizes_bytes("%s/read" % results.v_name, 0,
"DebugIdentity")[0], 0)
def testGetOpTypeWorks(self):
results = self._generate_dump_from_simple_addition_graph()
self.assertEqual(results.u.op.type,
results.dump.node_op_type(results.u_name))
self.assertIn(results.v.op.type, results.dump.node_op_type(results.v_name))
self.assertIn(results.w.op.type, results.dump.node_op_type(results.w_name))
with self.assertRaisesRegexp(
ValueError, "Node 'foo_bar' does not exist in partition graphs."):
results.dump.node_op_type("foo_bar")
def testDumpStringTensorsWorks(self):
with session.Session() as sess:
str1_init_val = np.array(b"abc")
str2_init_val = np.array(b"def")
str1_init = constant_op.constant(str1_init_val)
str2_init = constant_op.constant(str2_init_val)
str1_name = "str1"
str2_name = "str2"
str1 = variables.Variable(str1_init, name=str1_name)
str2 = variables.Variable(str2_init, name=str2_name)
# Concatenate str1 and str2
str_concat = math_ops.add(str1, str2, name="str_concat")
str1.initializer.run()
str2.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_urls = self._debug_urls()
# Add debug tensor watch for u.
debug_utils.add_debug_tensor_watch(
run_options, "%s/read" % str1_name, 0, debug_urls=debug_urls)
# Add debug tensor watch for v.
debug_utils.add_debug_tensor_watch(
run_options, "%s/read" % str2_name, 0, debug_urls=debug_urls)
run_metadata = config_pb2.RunMetadata()
sess.run(str_concat, options=run_options, run_metadata=run_metadata)
# String ops are located on CPU.
self.assertEqual(1, len(run_metadata.partition_graphs))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertIn(str1_name, dump.nodes())
self.assertIn(str2_name, dump.nodes())
self.assertEqual(2, dump.size)
self.assertEqual([str1_init_val],
dump.get_tensors("%s/read" % str1_name, 0,
"DebugIdentity"))
self.assertEqual([str2_init_val],
dump.get_tensors("%s/read" % str2_name, 0,
"DebugIdentity"))
self.assertGreaterEqual(
dump.get_rel_timestamps("%s/read" % str1_name, 0, "DebugIdentity")[0],
0)
self.assertGreaterEqual(
dump.get_rel_timestamps("%s/read" % str2_name, 0, "DebugIdentity")[0],
0)
self.assertGreater(
dump.get_dump_sizes_bytes("%s/read" % str1_name, 0,
"DebugIdentity")[0], 0)
self.assertGreater(
dump.get_dump_sizes_bytes("%s/read" % str2_name, 0,
"DebugIdentity")[0], 0)
def testDumpUninitializedVariable(self):
op_namespace = "testDumpUninitializedVariable"
with session.Session() as sess:
u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]])
s_init_val = b"str1"
u_name = "%s/u" % op_namespace
s_name = "%s/s" % op_namespace
u_init = constant_op.constant(u_init_val, shape=[2, 2])
u = variables.Variable(u_init, name=u_name)
s_init = constant_op.constant(s_init_val)
s = variables.Variable(s_init, name=s_name)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_urls = self._debug_urls()
# Add debug tensor watch for u.
debug_utils.add_debug_tensor_watch(
run_options, "%s" % u_name, 0, debug_urls=debug_urls)
debug_utils.add_debug_tensor_watch(
run_options, "%s" % s_name, 0, debug_urls=debug_urls)
run_metadata = config_pb2.RunMetadata()
# Initialize u and s.
sess.run(variables.global_variables_initializer(),
options=run_options,
run_metadata=run_metadata)
# Verify the dump file for the uninitialized value of u.
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertEqual(2, dump.size)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
# Verify that the variable is properly initialized by the run() call.
u_vals = dump.get_tensors(u_name, 0, "DebugIdentity")
s_vals = dump.get_tensors(s_name, 0, "DebugIdentity")
self.assertEqual(1, len(u_vals))
self.assertIsNone(u_vals[0])
self.assertEqual(1, len(s_vals))
self.assertIsNone(s_vals[0])
# Call run() again, to check that u is initialized properly.
self.assertAllClose(u_init_val, sess.run(u))
self.assertEqual(s_init_val, sess.run(s))
def testDebugWhileLoopGeneratesMultipleDumps(self):
with session.Session() as sess:
num_iter = 10
# "u" is the Variable being updated in the loop.
u_name = "testDumpToFileWhileLoop/u"
u_namespace = u_name.split("/")[0]
u_init_val = np.array(11.0)
u_init = constant_op.constant(u_init_val)
u = variables.Variable(u_init, name=u_name)
# "v" is the increment.
v_name = "testDumpToFileWhileLoop/v"
v_namespace = v_name.split("/")[0]
v_init_val = np.array(2.0)
v_init = constant_op.constant(v_init_val)
v = variables.Variable(v_init, name=v_name)
u.initializer.run()
v.initializer.run()
i = constant_op.constant(0, name="testDumpToFileWhileLoop/i")
def cond(i):
return math_ops.less(i, num_iter)
def body(i):
new_u = state_ops.assign_add(u, v)
new_i = math_ops.add(i, 1)
op = control_flow_ops.group(new_u)
new_i = control_flow_ops.with_dependencies([op], new_i)
return [new_i]
loop = control_flow_ops.while_loop(cond, body, [i], parallel_iterations=1)
# Create RunOptions for debug-watching tensors
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_urls = self._debug_urls()
# Add debug tensor watch for u.
debug_utils.add_debug_tensor_watch(
run_options, u_name, 0, debug_urls=debug_urls)
# Add debug tensor watch for v.
debug_utils.add_debug_tensor_watch(
run_options, "%s/read" % v_name, 0, debug_urls=debug_urls)
# Add debug tensor watch for while/Identity.
debug_utils.add_debug_tensor_watch(
run_options, "while/Identity", 0, debug_urls=debug_urls)
# Add debug tensor watch for while/Add/y.
debug_utils.add_debug_tensor_watch(
run_options, "while/Add/y", 0, debug_urls=debug_urls)
run_metadata = config_pb2.RunMetadata()
r = sess.run(loop, options=run_options, run_metadata=run_metadata)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
self.assertEqual(num_iter, r)
u_val_final = sess.run(u)
self.assertAllClose(u_init_val + num_iter * v_init_val, u_val_final)
# Verify dump files
self.assertTrue(os.path.isdir(self._dump_root))
self.assertTrue(os.path.isdir(os.path.join(self._dump_root, u_namespace)))
self.assertTrue(
os.path.isdir(os.path.join(self._dump_root, v_namespace, "v")))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Expected dumped tensors: u, v/read, 10 iterations of while/Identity,
# and 10 iterations of while/Add/y.
self.assertEqual(1 + 1 + num_iter + num_iter, dump.size)
# Verify tensor values.
self.assertAllClose([u_init_val],
dump.get_tensors(u_name, 0, "DebugIdentity"))
self.assertAllClose([v_init_val],
dump.get_tensors("%s/read" % v_name, 0,
"DebugIdentity"))
while_id_tensors = dump.get_tensors("while/Identity", 0, "DebugIdentity")
self.assertEqual(10, len(while_id_tensors))
for k in xrange(len(while_id_tensors)):
self.assertAllClose(np.array(k), while_id_tensors[k])
# Verify ascending timestamps from the while loops.
while_id_rel_timestamps = dump.get_rel_timestamps("while/Identity", 0,
"DebugIdentity")
while_id_dump_sizes_bytes = dump.get_dump_sizes_bytes("while/Identity", 0,
"DebugIdentity")
self.assertEqual(10, len(while_id_rel_timestamps))
prev_rel_time = 0
prev_dump_size_bytes = while_id_dump_sizes_bytes[0]
for rel_time, dump_size_bytes in zip(while_id_rel_timestamps,
while_id_dump_sizes_bytes):
self.assertGreaterEqual(rel_time, prev_rel_time)
self.assertEqual(dump_size_bytes, prev_dump_size_bytes)
prev_rel_time = rel_time
prev_dump_size_bytes = dump_size_bytes
# Test querying debug watch keys from node name.
watch_keys = dump.debug_watch_keys("while/Identity")
self.assertEqual(["while/Identity:0:DebugIdentity"], watch_keys)
# Test querying debug datum instances from debug watch key.
self.assertEqual(10, len(dump.watch_key_to_data(watch_keys[0])))
self.assertEqual([], dump.watch_key_to_data("foo"))
def testDebugWhileLoopWatchingWholeGraphWorks(self):
with session.Session() as sess:
loop_body = lambda i: math_ops.add(i, 2)
loop_cond = lambda i: math_ops.less(i, 16)
i = constant_op.constant(10, name="i")
loop = control_flow_ops.while_loop(loop_cond, loop_body, [i])
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(run_options,
sess.graph,
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
self.assertEqual(
16, sess.run(loop, options=run_options, run_metadata=run_metadata))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertEqual(
[[10]], dump.get_tensors("while/Enter", 0, "DebugIdentity"))
self.assertEqual(
[[12], [14], [16]],
dump.get_tensors("while/NextIteration", 0, "DebugIdentity"))
def testDebugCondWatchingWholeGraphWorks(self):
with session.Session() as sess:
x = variables.Variable(10.0, name="x")
y = variables.Variable(20.0, name="y")
cond = control_flow_ops.cond(
x > y, lambda: math_ops.add(x, 1), lambda: math_ops.add(y, 1))
sess.run(variables.global_variables_initializer())
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(run_options,
sess.graph,
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
self.assertEqual(
21, sess.run(cond, options=run_options, run_metadata=run_metadata))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertAllClose(
[21.0], dump.get_tensors("cond/Merge", 0, "DebugIdentity"))
def testFindNodesWithBadTensorValues(self):
with session.Session() as sess:
u_name = "testFindNodesWithBadTensorValues/u"
v_name = "testFindNodesWithBadTensorValues/v"
w_name = "testFindNodesWithBadTensorValues/w"
x_name = "testFindNodesWithBadTensorValues/x"
y_name = "testFindNodesWithBadTensorValues/y"
z_name = "testFindNodesWithBadTensorValues/z"
u_init = constant_op.constant([2.0, 4.0])
u = variables.Variable(u_init, name=u_name)
v_init = constant_op.constant([2.0, 1.0])
v = variables.Variable(v_init, name=v_name)
# Expected output: [0.0, 3.0]
w = math_ops.subtract(u, v, name=w_name)
# Expected output: [inf, 1.3333]
x = math_ops.div(u, w, name=x_name)
# Expected output: [nan, 4.0]
y = math_ops.multiply(w, x, name=y_name)
z = math_ops.multiply(y, y, name=z_name)
u.initializer.run()
v.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run(z, options=run_options, run_metadata=run_metadata)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
def has_bad_value(_, tensor):
return np.any(np.isnan(tensor)) or np.any(np.isinf(tensor))
# Find all "offending tensors".
bad_data = dump.find(has_bad_value)
# Verify that the nodes with bad values are caught through running find
# on the debug dump.
self.assertEqual(3, len(bad_data))
self.assertEqual(x_name, bad_data[0].node_name)
self.assertEqual(y_name, bad_data[1].node_name)
self.assertEqual(z_name, bad_data[2].node_name)
# Test first_n kwarg of find(): Find the first offending tensor.
first_bad_datum = dump.find(has_bad_value, first_n=1)
self.assertEqual(1, len(first_bad_datum))
self.assertEqual(x_name, first_bad_datum[0].node_name)
def _session_run_for_graph_structure_lookup(self):
with session.Session() as sess:
u_name = "testDumpGraphStructureLookup/u"
v_name = "testDumpGraphStructureLookup/v"
w_name = "testDumpGraphStructureLookup/w"
u_init = constant_op.constant([2.0, 4.0])
u = variables.Variable(u_init, name=u_name)
v = math_ops.add(u, u, name=v_name)
w = math_ops.add(v, v, name=w_name)
u.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run(w, options=run_options, run_metadata=run_metadata)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
return u_name, v_name, w_name, dump
def testGraphStructureLookupGivesDevicesAndNodesInfo(self):
u_name, _, _, dump = self._session_run_for_graph_structure_lookup()
# Test num_devices().
self.assertEqual(self._expected_num_devices, len(dump.devices()))
# Test node_device().
self.assertEqual(self._main_device, dump.node_device(u_name))
with self.assertRaisesRegexp(ValueError,
"does not exist in partition graphs"):
dump.node_device(u_name + "foo")
# Test node_exists().
self.assertTrue(dump.node_exists(u_name))
self.assertTrue(dump.node_exists(u_name + "/read"))
self.assertFalse(dump.node_exists(u_name + "/read" + "/foo"))
def testGraphStructureLookupGivesNodesAndAttributes(self):
u_name, _, _, dump = self._session_run_for_graph_structure_lookup()
u_read_name = u_name + "/read"
# Test node name list lookup of the DebugDumpDir object.
node_names = dump.nodes()
self.assertTrue(u_name in node_names)
self.assertTrue(u_read_name in node_names)
# Test querying node attributes.
u_attr = dump.node_attributes(u_name)
self.assertEqual(dtypes.float32, u_attr["dtype"].type)
self.assertEqual(1, len(u_attr["shape"].shape.dim))
self.assertEqual(2, u_attr["shape"].shape.dim[0].size)
with self.assertRaisesRegexp(ValueError, "No node named \"foo\" exists"):
dump.node_attributes("foo")
def testGraphStructureLookupGivesDebugWatchKeys(self):
u_name, v_name, w_name, dump = (
self._session_run_for_graph_structure_lookup())
# Test querying the debug watch keys with node names.
self.assertEqual(["%s:0:DebugIdentity" % u_name],
dump.debug_watch_keys(u_name))
self.assertEqual(["%s:0:DebugIdentity" % v_name],
dump.debug_watch_keys(v_name))
self.assertEqual(["%s:0:DebugIdentity" % w_name],
dump.debug_watch_keys(w_name))
self.assertEqual([], dump.debug_watch_keys("foo"))
# Test querying debug datum instances from debug watch.
u_data = dump.watch_key_to_data(dump.debug_watch_keys(u_name)[0])
self.assertEqual(1, len(u_data))
self.assertEqual(u_name, u_data[0].node_name)
self.assertEqual(0, u_data[0].output_slot)
self.assertEqual("DebugIdentity", u_data[0].debug_op)
self.assertGreaterEqual(u_data[0].timestamp, 0)
self.assertEqual([], dump.watch_key_to_data("foo"))
def testGraphStructureLookupGivesNodeInputsAndRecipients(self):
u_name, v_name, w_name, dump = (
self._session_run_for_graph_structure_lookup())
u_read_name = u_name + "/read"
# Test the inputs lookup of the DebugDumpDir object.
self.assertEqual([], dump.node_inputs(u_name))
self.assertEqual([u_name], dump.node_inputs(u_read_name))
self.assertEqual([u_read_name] * 2, dump.node_inputs(v_name))
self.assertEqual([v_name] * 2, dump.node_inputs(w_name))
self.assertEqual([], dump.node_inputs(u_name, is_control=True))
self.assertEqual([], dump.node_inputs(u_read_name, is_control=True))
self.assertEqual([], dump.node_inputs(v_name, is_control=True))
self.assertEqual([], dump.node_inputs(w_name, is_control=True))
# Test the outputs recipient lookup of the DebugDumpDir object.
self.assertTrue(u_read_name in dump.node_recipients(u_name))
self.assertEqual(2, dump.node_recipients(u_read_name).count(v_name))
self.assertEqual(2, dump.node_recipients(v_name).count(w_name))
self.assertEqual([], dump.node_recipients(u_name, is_control=True))
self.assertEqual([], dump.node_recipients(u_read_name, is_control=True))
self.assertEqual([], dump.node_recipients(v_name, is_control=True))
self.assertEqual([], dump.node_recipients(w_name, is_control=True))
# Test errors raised on invalid node names.
with self.assertRaisesRegexp(ValueError,
"does not exist in partition graphs"):
dump.node_inputs(u_name + "foo")
with self.assertRaisesRegexp(ValueError,
"does not exist in partition graphs"):
dump.node_recipients(u_name + "foo")
# Test transitive_inputs().
self.assertEqual([], dump.transitive_inputs(u_name))
self.assertEqual([u_name], dump.transitive_inputs(u_read_name))
self.assertEqual(
set([u_name, u_read_name]), set(dump.transitive_inputs(v_name)))
self.assertEqual(
set([u_name, u_read_name, v_name]), set(dump.transitive_inputs(w_name)))
with self.assertRaisesRegexp(ValueError,
"does not exist in partition graphs"):
dump.transitive_inputs(u_name + "foo")
def testGraphStructureLookupWithoutPartitionGraphsDoesNotErrorOut(self):
_, _, _, dump = self._session_run_for_graph_structure_lookup()
# Now load the dump again, without the partition graphs, so we can check
# errors are not raised because the partition graphs are loaded from the
# dump directory.
dump = debug_data.DebugDumpDir(self._dump_root, validate=False)
self.assertTrue(dump.loaded_partition_graphs())
def testCausalityCheckOnDumpsDetectsWrongTemporalOrder(self):
with session.Session() as sess:
u_name = "testDumpCausalityCheck/u"
v_name = "testDumpCausalityCheck/v"
w_name = "testDumpCausalityCheck/w"
u_init = constant_op.constant([2.0, 4.0])
u = variables.Variable(u_init, name=u_name)
v = math_ops.add(u, u, name=v_name)
w = math_ops.add(v, v, name=w_name)
u.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run(w, options=run_options, run_metadata=run_metadata)
self.assertEqual(self._expected_partition_graph_count,
len(run_metadata.partition_graphs))
# First, loading the original dump without supplying the
# partition_graphs should not cause a LookupError, validation occurs
# only with partition_graphs loaded.
debug_data.DebugDumpDir(self._dump_root)
# Now, loading the original dump with partition graphs supplied should
# succeed. The validation should pass quietly.
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Get the dump file names and compute their timestamps.
self.assertEqual(
1, len(dump.get_tensor_file_paths(u_name, 0, "DebugIdentity")))
u_file_path = dump.get_tensor_file_paths(u_name, 0, "DebugIdentity")[0]
self.assertEqual(
1, len(dump.get_tensor_file_paths(v_name, 0, "DebugIdentity")))
v_file_path = dump.get_tensor_file_paths(v_name, 0, "DebugIdentity")[0]
u_timestamp = int(u_file_path[u_file_path.rindex("_") + 1:])
v_timestamp = int(v_file_path[v_file_path.rindex("_") + 1:])
# Swap the time stamps
new_u_file_path = u_file_path[:u_file_path.rindex(
"_")] + "_%d" % v_timestamp
new_v_file_path = v_file_path[:v_file_path.rindex(
"_")] + "_%d" % u_timestamp
os.rename(u_file_path, new_u_file_path)
os.rename(v_file_path, new_v_file_path)
# Load the dump directory again. Now a ValueError is expected to be
# raised due to the timestamp swap.
with self.assertRaisesRegexp(ValueError, "Causality violated"):
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Loading the dump directory with kwarg "validate" set explicitly to
# False should get rid of the error.
dump = debug_data.DebugDumpDir(
self._dump_root,
partition_graphs=run_metadata.partition_graphs,
validate=False)
def testWatchingOnlyOneOfTwoOutputSlotsDoesNotLeadToCausalityFailure(self):
with session.Session() as sess:
x_name = "oneOfTwoSlots/x"
u_name = "oneOfTwoSlots/u"
v_name = "oneOfTwoSlots/v"
w_name = "oneOfTwoSlots/w"
y_name = "oneOfTwoSlots/y"
x = variables.Variable([1, 3, 3, 7], dtype=dtypes.int32, name=x_name)
sess.run(x.initializer)
unique_x, indices, _ = array_ops.unique_with_counts(x, name=u_name)
v = math_ops.add(unique_x, unique_x, name=v_name)
w = math_ops.add(indices, indices, name=w_name)
y = math_ops.add(w, w, name=y_name)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
# Watch only the first output slot of u, even though it has two output
# slots.
debug_utils.add_debug_tensor_watch(
run_options, u_name, 0, debug_urls=self._debug_urls())
debug_utils.add_debug_tensor_watch(
run_options, w_name, 0, debug_urls=self._debug_urls())
debug_utils.add_debug_tensor_watch(
run_options, y_name, 0, debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run([v, y], options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root,
partition_graphs=run_metadata.partition_graphs,
validate=True)
self.assertAllClose([1, 3, 7],
dump.get_tensors(u_name, 0, "DebugIdentity")[0])
def testOutputSlotWithoutOutgoingEdgeCanBeWatched(self):
"""Test watching output slots not attached to any outgoing edges."""
with session.Session() as sess:
u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]])
u = constant_op.constant(u_init_val, shape=[2, 2], name="u")
# Create a control edge from a node with an output: From u to z.
# Node u will get executed only because of the control edge. The output
# tensor u:0 is not attached to any outgoing edge in the graph. This test
# checks that the debugger can watch such a tensor.
with ops.control_dependencies([u]):
z = control_flow_ops.no_op(name="z")
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run(z, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Assert that the DebugIdentity watch on u works properly.
self.assertEqual(1, len(dump.dumped_tensor_data))
datum = dump.dumped_tensor_data[0]
self.assertEqual("u", datum.node_name)
self.assertEqual(0, datum.output_slot)
self.assertEqual("DebugIdentity", datum.debug_op)
self.assertAllClose([[5.0, 3.0], [-1.0, 0.0]], datum.get_tensor())
def testWatchingVariableUpdateOpsSeesUpdatedValues(self):
"""Watch output slots on Variable-updating ops, with no emitted edges."""
with session.Session() as sess:
u_init = constant_op.constant(10.0)
u = variables.Variable(u_init, name="gdo/u")
v_init = constant_op.constant(20.0)
v = variables.Variable(v_init, name="gdo/v")
w = math_ops.multiply(u, v, name="gdo/w")
# gdo stands for GradientDescentOptimizer.
train_op = gradient_descent.GradientDescentOptimizer(
learning_rate=0.1).minimize(
w, name="gdo/train")
u.initializer.run()
v.initializer.run()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
sess.run(train_op, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
update_u_data = dump.watch_key_to_data(
"gdo/train/update_gdo/u/ApplyGradientDescent:0:DebugIdentity")
self.assertEqual(1, len(update_u_data))
# Gradient descent on u: w = u * v, so dw / du = v.
# Updated value of u should be:
# 10.0 - learning_rate * v = 10.0 - 0.1 * 20.0 = 8.0
self.assertAllClose(8.0, update_u_data[0].get_tensor())
update_v_data = dump.watch_key_to_data(
"gdo/train/update_gdo/v/ApplyGradientDescent:0:DebugIdentity")
self.assertEqual(1, len(update_v_data))
# Gradient descent on u: w = u * v, so dw / dv = u.
# Updated value of u should be:
# 20.0 - learning_rate * u = 20.0 - 0.1 * 10.0 = 19.0
self.assertAllClose(19.0, update_v_data[0].get_tensor())
# Verify that the Variables u and v are updated properly.
self.assertAllClose(8.0, sess.run(u))
self.assertAllClose(19.0, sess.run(v))
def testAllowsWatchingUnconnectedOutputTensor(self):
"""Watch an output slot not emitting any edges.
(Not even control edges from the node.)
"""
with session.Session() as sess:
x_init = constant_op.constant([2, 2, 3, 5, 5])
x = variables.Variable(x_init, name="unconnected/x")
# The UniqueOp (tf.unique) has two output slots. Use only slot 0 in the
# graph. Let the debugger watch the unused slot 1.
unique_x, _ = array_ops.unique(x, name="unconnected/unique_x")
y = math_ops.add(unique_x, [0, 1, 2], name="unconnected/y")
x.initializer.run()
# Verify that only slot 0 of unique_x has recipients, while slot 1 of the
# same node does not have recipients.
unique_x_slot_0_recipients = []
unique_x_slot_1_recipients = []
for op in sess.graph.get_operations():
for inp in op.inputs:
if inp.name == "unconnected/unique_x:0":
unique_x_slot_0_recipients.append(op.name)
elif inp.name == "unconnected/unique_x:1":
unique_x_slot_1_recipients.append(op.name)
self.assertEqual(["unconnected/y"], unique_x_slot_0_recipients)
self.assertEqual([], unique_x_slot_1_recipients)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
run_metadata = config_pb2.RunMetadata()
result = sess.run(y, options=run_options, run_metadata=run_metadata)
self.assertAllClose([2, 4, 7], result)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Assert that the connected slot (slot 0) is dumped properly.
unique_x_slot_0_dumps = dump.watch_key_to_data(
"unconnected/unique_x:0:DebugIdentity")
self.assertEqual(1, len(unique_x_slot_0_dumps))
self.assertEqual("unconnected/unique_x",
unique_x_slot_0_dumps[0].node_name)
self.assertEqual(0, unique_x_slot_0_dumps[0].output_slot)
self.assertAllClose([2, 3, 5], unique_x_slot_0_dumps[0].get_tensor())
# Assert that the unconnected slot (slot 1) is dumped properly.
unique_x_slot_1_dumps = dump.watch_key_to_data(
"unconnected/unique_x:1:DebugIdentity")
self.assertEqual(1, len(unique_x_slot_1_dumps))
self.assertEqual("unconnected/unique_x",
unique_x_slot_1_dumps[0].node_name)
self.assertEqual(1, unique_x_slot_1_dumps[0].output_slot)
self.assertAllClose([0, 0, 1, 2, 2],
unique_x_slot_1_dumps[0].get_tensor())
def testSuccessiveDebuggingRunsIncreasesCounters(self):
"""Test repeated Session.run() calls with debugger increments counters."""
with session.Session() as sess:
ph = array_ops.placeholder(dtypes.float32, name="successive/ph")
x = array_ops.transpose(ph, name="mismatch/x")
y = array_ops.squeeze(ph, name="mismatch/y")
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options, sess.graph, debug_urls=self._debug_urls(), global_step=1)
sess.run(x, feed_dict={ph: np.array([[7.0, 8.0]])}, options=run_options)
dump1 = debug_data.DebugDumpDir(self._dump_root)
self.assertEqual(1, dump1.core_metadata.global_step)
self.assertGreaterEqual(dump1.core_metadata.session_run_count, 0)
self.assertEqual(0, dump1.core_metadata.executor_step_count)
self.assertEqual([ph.name], dump1.core_metadata.input_names)
self.assertEqual([x.name], dump1.core_metadata.output_names)
self.assertEqual([], dump1.core_metadata.target_nodes)
shutil.rmtree(self._dump_root)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options, sess.graph, debug_urls=self._debug_urls(), global_step=2)
# Calling run() with the same feed, same output and same debug watch
# options should increment both session_run_count and
# executor_step_count.
sess.run(x, feed_dict={ph: np.array([[7.0, 8.0]])}, options=run_options)
dump2 = debug_data.DebugDumpDir(self._dump_root)
self.assertEqual(2, dump2.core_metadata.global_step)
self.assertEqual(dump1.core_metadata.session_run_count + 1,
dump2.core_metadata.session_run_count)
self.assertEqual(dump1.core_metadata.executor_step_count + 1,
dump2.core_metadata.executor_step_count)
self.assertEqual([ph.name], dump2.core_metadata.input_names)
self.assertEqual([x.name], dump2.core_metadata.output_names)
self.assertEqual([], dump2.core_metadata.target_nodes)
shutil.rmtree(self._dump_root)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options, sess.graph, debug_urls=self._debug_urls(), global_step=3)
# Calling run() with a different output should increment
# session_run_count, but not executor_step_count.
sess.run(y, feed_dict={ph: np.array([[7.0, 8.0]])}, options=run_options)
dump3 = debug_data.DebugDumpDir(self._dump_root)
self.assertEqual(3, dump3.core_metadata.global_step)
self.assertEqual(dump2.core_metadata.session_run_count + 1,
dump3.core_metadata.session_run_count)
self.assertEqual(0, dump3.core_metadata.executor_step_count)
self.assertEqual([ph.name], dump3.core_metadata.input_names)
self.assertEqual([y.name], dump3.core_metadata.output_names)
self.assertEqual([], dump3.core_metadata.target_nodes)
def testDebuggingDuringOpError(self):
"""Test the debug tensor dumping when error occurs in graph runtime."""
with session.Session() as sess:
ph = array_ops.placeholder(dtypes.float32, name="mismatch/ph")
x = array_ops.transpose(ph, name="mismatch/x")
m = constant_op.constant(
np.array(
[[1.0, 2.0]], dtype=np.float32), name="mismatch/m")
y = math_ops.matmul(m, x, name="mismatch/y")
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugIdentity"],
debug_urls=self._debug_urls())
with self.assertRaises(errors.OpError):
sess.run(y,
options=run_options,
feed_dict={ph: np.array([[-3.0], [0.0]])})
dump = debug_data.DebugDumpDir(self._dump_root)
self.assertGreaterEqual(dump.core_metadata.session_run_count, 0)
self.assertGreaterEqual(dump.core_metadata.executor_step_count, 0)
self.assertEqual([ph.name], dump.core_metadata.input_names)
self.assertEqual([y.name], dump.core_metadata.output_names)
self.assertEqual([], dump.core_metadata.target_nodes)
# Despite the fact that the run() call errored out and partition_graphs
# are not available via run_metadata, the partition graphs should still
# have been loaded from the dump directory.
self.assertTrue(dump.loaded_partition_graphs())
m_dumps = dump.watch_key_to_data("mismatch/m:0:DebugIdentity")
self.assertEqual(1, len(m_dumps))
self.assertAllClose(np.array([[1.0, 2.0]]), m_dumps[0].get_tensor())
x_dumps = dump.watch_key_to_data("mismatch/x:0:DebugIdentity")
self.assertEqual(1, len(x_dumps))
self.assertAllClose(np.array([[-3.0, 0.0]]), x_dumps[0].get_tensor())
def testDebugNumericSummaryOnInitializedTensorGivesCorrectResult(self):
with session.Session() as sess:
a = variables.Variable(
[
np.nan, np.nan, 0.0, 0.0, 0.0, -1.0, -3.0, 3.0, 7.0, -np.inf,
-np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.nan, np.nan
],
dtype=np.float32,
name="numeric_summary/a")
b = variables.Variable(
[0.0] * 18, dtype=np.float32, name="numeric_summary/b")
c = math_ops.add(a, b, name="numeric_summary/c")
sess.run(variables.global_variables_initializer())
run_metadata = config_pb2.RunMetadata()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugNumericSummary"],
debug_urls=self._debug_urls())
sess.run(c, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertTrue(dump.loaded_partition_graphs())
self.assertAllClose([[
1.0, 18.0, 4.0, 2.0, 2.0, 3.0, 2.0, 5.0, -3.0, 7.0, 0.85714286,
8.97959184
]], dump.get_tensors("numeric_summary/a/read", 0, "DebugNumericSummary"))
def testDebugNumericSummaryOnUninitializedTensorGivesCorrectResult(self):
with session.Session() as sess:
a = variables.Variable(
[42], dtype=np.float32, name="numeric_summary_uninit/a")
run_metadata = config_pb2.RunMetadata()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugNumericSummary"],
debug_urls=self._debug_urls())
sess.run(a.initializer, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertTrue(dump.loaded_partition_graphs())
# DebugNumericSummary output should reflect the uninitialized state of
# the watched tensor.
numeric_summary = dump.get_tensors("numeric_summary_uninit/a", 0,
"DebugNumericSummary")[0]
self.assertAllClose([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
numeric_summary[0:8])
self.assertTrue(np.isinf(numeric_summary[8]))
self.assertGreater(numeric_summary[8], 0.0)
self.assertTrue(np.isinf(numeric_summary[9]))
self.assertLess(numeric_summary[9], 0.0)
self.assertTrue(np.isnan(numeric_summary[10]))
self.assertTrue(np.isnan(numeric_summary[11]))
def testDebugNumericSummaryFailureIsToleratedWhenOrdered(self):
with session.Session() as sess:
a = variables.Variable("1", name="a")
b = variables.Variable("3", name="b")
c = variables.Variable("2", name="c")
d = math_ops.add(a, b, name="d")
e = math_ops.add(d, c, name="e")
n = parsing_ops.string_to_number(e, name="n")
m = math_ops.add(n, n, name="m")
sess.run(variables.global_variables_initializer())
# Using DebugNumericSummary on sess.run(m) with the default
# tolerate_debug_op_creation_failures=False should error out due to the
# presence of string-dtype Tensors in the graph.
run_metadata = config_pb2.RunMetadata()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_ops=["DebugNumericSummary"],
debug_urls=self._debug_urls())
with self.assertRaises(errors.FailedPreconditionError):
sess.run(m, options=run_options, run_metadata=run_metadata)
# Using tolerate_debug_op_creation_failures=True should get rid of the
# error.
new_run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
new_run_options,
sess.graph,
debug_ops=["DebugNumericSummary"],
debug_urls=self._debug_urls(),
tolerate_debug_op_creation_failures=True)
self.assertEqual(264,
sess.run(
m,
options=new_run_options,
run_metadata=run_metadata))
# The integer-dtype Tensors in the graph should have been dumped
# properly.
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertIn("n:0:DebugNumericSummary", dump.debug_watch_keys("n"))
self.assertIn("m:0:DebugNumericSummary", dump.debug_watch_keys("m"))
def testDebugQueueOpsDoesNotoErrorOut(self):
with session.Session() as sess:
q = data_flow_ops.FIFOQueue(3, "float", name="fifo_queue")
q_init = q.enqueue_many(([101.0, 202.0, 303.0],), name="enqueue_many")
run_metadata = config_pb2.RunMetadata()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options,
sess.graph,
debug_urls=self._debug_urls())
sess.run(q_init, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertTrue(dump.loaded_partition_graphs())
self.assertIsNone(dump.get_tensors("fifo_queue", 0, "DebugIdentity")[0])
self.assertAllClose(
[101.0, 202.0, 303.0],
dump.get_tensors("enqueue_many/component_0", 0, "DebugIdentity")[0])
def testLookUpNodePythonTracebackWorks(self):
with session.Session() as sess:
u_init = constant_op.constant(10.0)
u = variables.Variable(u_init, name="traceback/u")
v_init = constant_op.constant(20.0)
v = variables.Variable(v_init, name="traceback/v")
w = math_ops.multiply(u, v, name="traceback/w")
sess.run(variables.global_variables_initializer())
run_metadata = config_pb2.RunMetadata()
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options, sess.graph, debug_urls=self._debug_urls())
sess.run(w, options=run_options, run_metadata=run_metadata)
dump = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
# Prior to setting the Python graph, attempts to do traceback lookup
# should lead to exceptions.
with self.assertRaisesRegexp(
LookupError, "Python graph is not available for traceback lookup"):
dump.node_traceback("traceback/w")
dump.set_python_graph(sess.graph)
# After setting the Python graph, attempts to look up nonexistent nodes
# should lead to exceptions.
with self.assertRaisesRegexp(KeyError,
r"Cannot find node \"foo\" in Python graph"):
dump.node_traceback("foo")
# Lookup should work with node name input.
traceback = dump.node_traceback("traceback/w")
self.assertIsInstance(traceback, list)
self.assertGreater(len(traceback), 0)
for trace in traceback:
self.assertIsInstance(trace, tuple)
# Lookup should also work with tensor name input.
traceback = dump.node_traceback("traceback/w:0")
self.assertIsInstance(traceback, list)
self.assertGreater(len(traceback), 0)
for trace in traceback:
self.assertIsInstance(trace, tuple)
class DebugConcurrentRunCallsTest(test_util.TensorFlowTestCase):
"""Test for debugging concurrent Session.run() calls."""
def _get_concurrent_debug_urls(self):
"""Abstract method to generate debug URLs for concurrent debugged runs."""
raise NotImplementedError(
"_get_concurrent_debug_urls is not implemented in the base test class")
def testDebugConcurrentVariableUpdates(self):
if test.is_gpu_available():
self.skipTest("No testing concurrent runs on a single GPU.")
with session.Session() as sess:
v = variables.Variable(30.0, name="v")
constants = []
for i in xrange(self._num_concurrent_runs):
constants.append(constant_op.constant(1.0, name="c%d" % i))
incs = [
state_ops.assign_add(
v, c, use_locking=True, name=("inc%d" % i))
for (i, c) in enumerate(constants)
]
sess.run(v.initializer)
concurrent_debug_urls = self._get_concurrent_debug_urls()
def inc_job(index):
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(
run_options, sess.graph, debug_urls=concurrent_debug_urls[index])
for _ in xrange(100):
sess.run(incs[index], options=run_options)
inc_threads = []
for index in xrange(self._num_concurrent_runs):
inc_thread = threading.Thread(target=functools.partial(inc_job, index))
inc_thread.start()
inc_threads.append(inc_thread)
for inc_thread in inc_threads:
inc_thread.join()
self.assertAllClose(30.0 + 1.0 * self._num_concurrent_runs * 100,
sess.run(v))
all_session_run_counts = []
for index in xrange(self._num_concurrent_runs):
dump = debug_data.DebugDumpDir(self._dump_roots[index])
self.assertTrue(dump.loaded_partition_graphs())
v_data = dump.get_tensors("v", 0, "DebugIdentity")
self.assertEqual(100, len(v_data))
# Examine all the core metadata files
core_metadata_files = glob.glob(
os.path.join(self._dump_roots[index], "_tfdbg_core*"))
timestamps = []
session_run_counts = []
executor_step_counts = []
for core_metadata_file in core_metadata_files:
with open(core_metadata_file, "rb") as f:
event = event_pb2.Event()
event.ParseFromString(f.read())
core_metadata = (
debug_data.extract_core_metadata_from_event_proto(event))
timestamps.append(event.wall_time)
session_run_counts.append(core_metadata.session_run_count)
executor_step_counts.append(core_metadata.executor_step_count)
all_session_run_counts.extend(session_run_counts)
# Assert that executor_step_count increases by one at a time.
executor_step_counts = zip(timestamps, executor_step_counts)
executor_step_counts = sorted(executor_step_counts, key=lambda x: x[0])
for i in xrange(len(executor_step_counts) - 1):
self.assertEquals(executor_step_counts[i][1] + 1,
executor_step_counts[i + 1][1])
# Assert that session_run_count increase monotonically.
session_run_counts = zip(timestamps, session_run_counts)
session_run_counts = sorted(session_run_counts, key=lambda x: x[0])
for i in xrange(len(session_run_counts) - 1):
self.assertGreater(session_run_counts[i + 1][1],
session_run_counts[i][1])
# Assert that the session_run_counts from the concurrent run() calls are
# all unique.
self.assertEqual(len(all_session_run_counts),
len(set(all_session_run_counts)))
if __name__ == "__main__":
googletest.main() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules"""
def main(sdk_path, test_path):
sys.path.insert(0, sdk_path)
sys.path.append(test_path + '/station')
import dev_appserver
dev_appserver.fix_sys_path()
os.environ['SERVER_NAME'] = 'testrunner.example.com'
os.environ['SERVER_PORT'] = '80'
os.environ['APPENGINE_RUNTIME'] = 'python27'
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 2:
print 'Error: Exactly 2 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = args[1]
main(SDK_PATH, TEST_PATH) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example deletes custom targeting values for a given custom targeting
key.
To determine which custom targeting keys and values exist, run
get_all_custom_targeting_keys_and_values.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
"""
# Import appropriate modules from the client library.
from googleads import dfp
KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'
def main(client, key_id):
# Initialize appropriate service.
custom_targeting_service = client.GetService(
'CustomTargetingService', version='v201502')
filter_values = [{
'key': 'keyId',
'value': {
'xsi_type': 'NumberValue',
'value': key_id
}
}]
query = 'WHERE customTargetingKeyId = :keyId'
statement = dfp.FilterStatement(query, filter_values)
deleted_custom_targeting_values = 0
# Get custom targeting values.
while True:
response = custom_targeting_service.getCustomTargetingValuesByStatement(
statement.ToStatement())
if 'results' in response:
value_ids = [value['id'] for value in response['results']]
action = {'xsi_type': 'DeleteCustomTargetingValues'}
value_query = ('WHERE customTargetingKeyId = :keyId '
'AND id IN (%s)' % ', '.join(value_ids))
value_statement = dfp.FilterStatement(value_query, filter_values)
# Delete custom targeting values.
result = custom_targeting_service.performCustomTargetingValueAction(
action, value_statement.ToStatement())
if result and int(result['numChanges']) > 0:
deleted_custom_targeting_values += int(result['numChanges'])
statement.offset += dfp.SUGGESTED_PAGE_LIMIT
else:
break
if deleted_custom_targeting_values > 0:
print ('Number of custom targeting values deleted: %s'
% deleted_custom_targeting_values)
else:
print 'No custom targeting values were deleted.'
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client, KEY_ID) | unknown | codeparrot/codeparrot-clean | ||
# (C) Copyright David Abrahams 2001. Permission to copy, use, modify, sell and
# distribute this software is granted provided this copyright notice appears in
# all copies. This software is provided "as is" without express or implied
# warranty, and with no claim as to its suitability for any purpose.
from b2.util import is_iterable
from .utility import to_seq
def difference (b, a):
""" Returns the elements of B that are not in A.
"""
assert is_iterable(b)
assert is_iterable(a)
result = []
for element in b:
if not element in a:
result.append (element)
return result
def intersection (set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result
def contains (small, large):
""" Returns true iff all elements of 'small' exist in 'large'.
"""
small = to_seq (small)
large = to_seq (large)
for s in small:
if not s in large:
return False
return True
def equal (a, b):
""" Returns True iff 'a' contains the same elements as 'b', irrespective of their order.
# TODO: Python 2.4 has a proper set class.
"""
assert is_iterable(a)
assert is_iterable(b)
return contains (a, b) and contains (b, a) | unknown | codeparrot/codeparrot-clean | ||
import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_browse as h2b, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
h2o.init(1,java_heap_GB=10)
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_delete_all_keys(self):
# FIX! should have some model keys in here too, from RF etc.
importFolderPath = 'standard'
timeoutSecs = 500
csvFilenameAll = [
"covtype.data",
"covtype20x.data",
]
# csvFilenameList = random.sample(csvFilenameAll,1)
csvFilenameList = csvFilenameAll
for trial in range(3):
for csvFilename in csvFilenameList:
csvPathname = importFolderPath + "/" + csvFilename
start = time.time()
parseResult = h2i.import_parse(bucket='home-0xdiag-datasets', path=csvPathname, timeoutSecs=500)
elapsed = time.time() - start
print csvFilename, "parsed in", elapsed, "seconds.", "%d pct. of timeout" % ((elapsed*100)/timeoutSecs), "\n"
print "Parse result['destination_key']:", parseResult['destination_key']
print "\n" + csvFilename
print "Delete all keys"
h2o.nodes[0].remove_all_keys()
print "This shouldn't see any keys"
h2i.delete_keys_at_all_nodes()
print "\nTrial", trial, "completed\n"
if __name__ == '__main__':
h2o.unit_main() | unknown | codeparrot/codeparrot-clean | ||
test_kind: js_test
selector:
roots:
- jstests/change_streams/**/*.js
exclude_files:
# Parallel Shell - we do not signal the override to end a txn when a parallel shell closes.
- jstests/change_streams/only_wake_getmore_for_relevant_changes.js
# TODO: SERVER-98064 Investigate split_large_event.js failures in change_streams_multi_stmt_txn_sharded_collections_passthrough
- jstests/change_streams/split_large_event.js
exclude_with_any_tags:
# These tests would fail with "Cowardly refusing to override write concern of command: ..."
- assumes_write_concern_unchanged
# No need to use a passthrough to add transactions to a test that already has its own
# transactions.
- uses_transactions
# These tests make assumptions about change stream results that are no longer true once operations
# get bundled into transactions.
- change_stream_does_not_expect_txns
# Exclude any tests that don't support sharding.
- assumes_against_mongod_not_mongos
- assumes_unsharded_collection
executor:
archive:
hooks:
- CheckReplDBHash
- CheckReplOplogs
- CheckMetadataConsistencyInBackground
- ValidateCollections
config:
shell_options:
global_vars:
TestData:
networkErrorAndTxnOverrideConfig:
wrapCRUDinTransactions: true
# Enable the transactions passthrough.
eval: >-
globalThis.testingReplication = true;
await import("jstests/libs/override_methods/enable_sessions.js");
await import("jstests/libs/override_methods/txn_passthrough_cmd_massage.js");
await import("jstests/libs/override_methods/network_error_and_txn_override.js");
await import("jstests/libs/override_methods/implicit_filter_eot_changestreams.js");
await import("jstests/libs/override_methods/implicitly_shard_accessed_collections.js");
# Set longer host discovery time to handle change stream resumable errors.
setShellParameter: defaultFindReplicaSetHostTimeoutMS=120000
hooks:
# The CheckReplDBHash hook waits until all operations have replicated to and have been applied
# on the secondaries, so we run the ValidateCollections hook after it to ensure we're
# validating the entire contents of the collection.
- class: CheckReplOplogs
- class: CheckReplDBHash
- class: CheckMetadataConsistencyInBackground
- class: RunQueryStats
- class: ValidateCollections
- class: CheckOrphansDeleted
- class: CleanEveryN
n: 20
fixture:
class: ShardedClusterFixture
mongos_options:
bind_ip_all: ""
set_parameters:
enableTestCommands: 1
mongod_options:
bind_ip_all: ""
set_parameters:
enableTestCommands: 1
writePeriodicNoops: 1
periodicNoopIntervalSecs: 1
num_shards: 2
num_mongos: 3 | unknown | github | https://github.com/mongodb/mongo | buildscripts/resmokeconfig/suites/change_streams_multi_stmt_txn_sharded_collections_passthrough.yml |
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from .base import HfQuantizer
if TYPE_CHECKING:
from ..modeling_utils import PreTrainedModel
from ..utils import (
is_accelerate_available,
is_kernels_available,
is_torch_available,
is_triton_available,
logging,
)
from .quantizers_utils import get_module_from_name
if is_torch_available():
import torch
from ..core_model_loading import WeightConverter
logger = logging.get_logger(__name__)
triton_kernels_hub = None
class Mxfp4HfQuantizer(HfQuantizer):
"""
FP4 quantization using fbgemm kernels
"""
requires_calibration = False
def __init__(self, quantization_config, **kwargs):
super().__init__(quantization_config, **kwargs)
self.triton_kernels_hub = None
def _lazy_import_kernels(self):
"""Lazy import and initialize kernels only when needed"""
if self.triton_kernels_hub is None:
try:
from ..integrations.hub_kernels import get_kernel
self.triton_kernels_hub = get_kernel("kernels-community/gpt-oss-triton-kernels")
except ImportError:
raise ImportError("kernels package is required for MXFP4 quantization")
return self.triton_kernels_hub
def validate_environment(self, *args, **kwargs):
if not is_torch_available():
raise ImportError(
"Using mxfp4 quantization requires torch"
"Please install the latest version of torch ( pip install --upgrade torch )"
)
if self.quantization_config.dequantize:
return
if not torch.cuda.is_available() and not torch.xpu.is_available():
if self.pre_quantized:
logger.warning_once(
"Using MXFP4 quantized models requires a GPU, we will default to dequantizing the model to bf16"
)
self.quantization_config.dequantize = True
return
else:
raise RuntimeError("Quantizing a model using MXFP4 requires a GPU")
if not is_accelerate_available():
raise ImportError("Using mxfp4 requires Accelerate: `pip install accelerate`")
if torch.xpu.is_available():
gpu_is_supported = True
kernels_available = is_triton_available("3.5.0") and is_kernels_available()
else:
compute_capability = torch.cuda.get_device_capability()
gpu_is_supported = compute_capability >= (7, 5)
kernels_available = is_triton_available("3.4.0") and is_kernels_available()
if self.pre_quantized:
# On unsupported GPUs or without kernels, we will dequantize the model to bf16
if not gpu_is_supported:
logger.warning_once(
"MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 (e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series) "
"We will default to dequantizing the model to bf16."
)
self.quantization_config.dequantize = True
return
if not kernels_available:
logger.warning_once(
"MXFP4 quantization requires Triton and kernels installed: CUDA requires Triton >= 3.4.0, XPU requires Triton >= 3.5.0, we will default to dequantizing the model to bf16"
)
self.quantization_config.dequantize = True
return
elif not gpu_is_supported:
# we can't quantize the model in this case so we raise an error
raise ValueError(
"MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 (e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series) "
)
elif not kernels_available:
# we can't quantize the model in this case so we raise an error
raise ValueError(
"MXFP4 quantization requires Triton and kernels installed: CUDA requires Triton >= 3.4.0, XPU requires Triton >= 3.5.0"
)
if not self.pre_quantized:
self._lazy_import_kernels()
device_map = kwargs.get("device_map")
if device_map is None:
logger.warning_once(
"You have loaded an FP4 model on CPU and have a CUDA/XPU device available, make sure to set "
"your model on a GPU/XPU device in order to run your model. To remove this warning, pass device_map = 'cuda' or device_map = 'xpu'. "
)
elif isinstance(device_map, dict):
if not self.pre_quantized and ("cpu" in device_map.values() or "disk" in device_map.values()):
raise ValueError(
"You are attempting to load an FP4 model with a device_map that contains a CPU or disk device."
"This is not supported when the model is quantized on the fly. "
"Please use a quantized checkpoint or remove the CPU or disk device from the device_map."
)
def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
from ..integrations import Mxfp4GptOssExperts
module, tensor_name = get_module_from_name(model, param_name)
if isinstance(module, Mxfp4GptOssExperts):
if tensor_name in ["down_proj_bias", "gate_up_proj_bias"]:
return False
return True
return False
def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
# clean cache due to triton ops
if torch.cuda.is_available():
torch.cuda.empty_cache()
elif torch.xpu.is_available():
torch.xpu.empty_cache()
def _process_model_before_weight_loading(
self,
model: "PreTrainedModel",
use_kernels: bool = False,
**kwargs,
):
from ..integrations import replace_with_mxfp4_linear
# if we are using kernels, we can't use the quantized model, since the forward pass is different and needs special handling
if use_kernels:
logger.warning_once(
"You are using full precision kernels, we will dequantize the model to bf16. "
"To use the quantized model with quantization kernels, please set use_kernels=False"
)
self.quantization_config.dequantize = True
self.modules_to_not_convert = self.get_modules_to_not_convert(
model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
)
model = replace_with_mxfp4_linear(
model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
)
def update_tp_plan(self, config):
if "GptOssConfig" in config.__class__.__name__:
if getattr(config, "base_model_tp_plan", None) is not None:
config.base_model_tp_plan.update(
{
"layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm",
"layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm",
"layers.*.mlp.experts.down_proj_blocks": "grouped_gemm",
"layers.*.mlp.experts.down_proj_scales": "grouped_gemm",
}
)
return config
def update_ep_plan(self, config):
if "GptOssConfig" in config.__class__.__name__:
if getattr(config, "base_model_ep_plan", None) is not None:
config.base_model_ep_plan.update(
{
"layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm",
"layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm",
"layers.*.mlp.experts.down_proj_blocks": "grouped_gemm",
"layers.*.mlp.experts.down_proj_scales": "grouped_gemm",
}
)
return config
def get_state_dict_and_metadata(self, model):
from ..integrations import Mxfp4GptOssExperts
state_dict = model.state_dict()
# Get num_local_experts from model config
num_local_experts = getattr(model.config, "num_local_experts", 32)
hidden_size = getattr(model.config, "hidden_size", 2880)
for name, module in model.named_modules():
if (
isinstance(module, Mxfp4GptOssExperts)
and hasattr(module, "gate_up_proj")
and hasattr(module, "down_proj")
):
state_dict[f"{name}.gate_up_proj_blocks"] = (
module.gate_up_proj.storage.layout.unswizzle_data(module.gate_up_proj.storage.data)
.transpose(-1, -2)
.reshape(num_local_experts, -1, 90, 16)
)
state_dict[f"{name}.gate_up_proj_scales"] = (
module.gate_up_proj_precision_config.weight_scale.storage.layout.unswizzle_data(
module.gate_up_proj_precision_config.weight_scale.storage.data
).transpose(-1, -2)
)
state_dict[f"{name}.down_proj_blocks"] = (
module.down_proj.storage.layout.unswizzle_data(module.down_proj.storage.data)
.transpose(-1, -2)
.reshape(num_local_experts, hidden_size, 90, -1)
)
state_dict[f"{name}.down_proj_scales"] = (
module.down_proj_precision_config.weight_scale.storage.layout.unswizzle_data(
module.down_proj_precision_config.weight_scale.storage.data
).transpose(-1, -2)
)
metadata = {}
return state_dict, metadata
def is_serializable(self):
return True
@property
def is_trainable(self) -> bool:
logger.warning_once(
"MXFP4 quantization don't support training, please consider dequantizing the model first by passing quantization_config=Mxfp4Config(dequantize=True) to .from_pretrained()"
)
return False
def get_quantize_ops(self):
from ..integrations.mxfp4 import Mxfp4Quantize
return Mxfp4Quantize(self)
def get_weight_conversions(self):
from ..integrations.mxfp4 import Mxfp4Dequantize, Mxfp4Deserialize
if self.pre_quantized:
if self.quantization_config.dequantize:
return [
WeightConverter(
source_patterns=["_blocks", "_scales"],
target_patterns="",
operations=[Mxfp4Dequantize(self)],
)
]
else:
return [
WeightConverter(
source_patterns=["_blocks", "_scales"],
target_patterns="",
operations=[Mxfp4Deserialize(self)],
)
]
return [] | python | github | https://github.com/huggingface/transformers | src/transformers/quantizers/quantizer_mxfp4.py |
# This file is being contributed to pyasn1-modules software.
#
# Created by Russ Housley with assistance from asn1ate v.0.6.0.
#
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
# Multicast Email (MULE) over Allied Communications Publication 142
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc8494.txt
from pyasn1.type import namedtype
from pyasn1.type import namedval
from pyasn1.type import tag
from pyasn1.type import univ
id_mmhs_CDT = univ.ObjectIdentifier('1.3.26.0.4406.0.4.2')
class AlgorithmID_ShortForm(univ.Integer):
pass
AlgorithmID_ShortForm.namedValues = namedval.NamedValues(
('zlibCompress', 0)
)
class ContentType_ShortForm(univ.Integer):
pass
ContentType_ShortForm.namedValues = namedval.NamedValues(
('unidentified', 0),
('external', 1),
('p1', 2),
('p3', 3),
('p7', 4),
('mule', 25)
)
class CompressedContentInfo(univ.Sequence):
pass
CompressedContentInfo.componentType = namedtype.NamedTypes(
namedtype.NamedType('unnamed', univ.Choice(componentType=namedtype.NamedTypes(
namedtype.NamedType('contentType-ShortForm',
ContentType_ShortForm().subtype(explicitTag=tag.Tag(
tag.tagClassContext, tag.tagFormatSimple, 0))),
namedtype.NamedType('contentType-OID',
univ.ObjectIdentifier().subtype(explicitTag=tag.Tag(
tag.tagClassContext, tag.tagFormatSimple, 1)))
))),
namedtype.NamedType('compressedContent',
univ.OctetString().subtype(explicitTag=tag.Tag(
tag.tagClassContext, tag.tagFormatSimple, 0)))
)
class CompressionAlgorithmIdentifier(univ.Choice):
pass
CompressionAlgorithmIdentifier.componentType = namedtype.NamedTypes(
namedtype.NamedType('algorithmID-ShortForm',
AlgorithmID_ShortForm().subtype(explicitTag=tag.Tag(
tag.tagClassContext, tag.tagFormatSimple, 0))),
namedtype.NamedType('algorithmID-OID',
univ.ObjectIdentifier().subtype(explicitTag=tag.Tag(
tag.tagClassContext, tag.tagFormatSimple, 1)))
)
class CompressedData(univ.Sequence):
pass
CompressedData.componentType = namedtype.NamedTypes(
namedtype.NamedType('compressionAlgorithm', CompressionAlgorithmIdentifier()),
namedtype.NamedType('compressedContentInfo', CompressedContentInfo())
) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks, filter, digital
class test_simple_correlator(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_00(self):
expected_result = [
0x00, 0x11, 0x22, 0x33,
0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb,
0xcc, 0xdd, 0xee, 0xff
]
# Filter taps to expand the data to oversample by 8
# Just using a RRC for some basic filter shape
taps = filter.firdes.root_raised_cosine(8, 8, 1.0, 0.5, 21)
src = blocks.vector_source_b(expected_result)
frame = digital.simple_framer(4)
unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)
expand = filter.interp_fir_filter_fff(8, taps)
b2f = blocks.char_to_float()
mult2 = blocks.multiply_const_ff(2)
sub1 = blocks.add_const_ff(-1)
op = digital.simple_correlator(4)
dst = blocks.vector_sink_b()
self.tb.connect(src, frame, unpack, b2f, mult2, sub1, expand)
self.tb.connect(expand, op, dst)
self.tb.run()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
if __name__ == '__main__':
gr_unittest.run(test_simple_correlator, "test_simple_correlator.xml") | unknown | codeparrot/codeparrot-clean | ||
{
"fooJSON": "foo_json_tfvars_value"
} | json | github | https://github.com/hashicorp/terraform | internal/command/testdata/test/tfvars_in_test_dir/alternate/vars.auto.tfvars.json |
# frozen_string_literal: true
class DlKeyedBelongsTo < ActiveRecord::Base
self.primary_key = "belongs_key"
belongs_to :destroy_async_parent,
dependent: :destroy_async,
foreign_key: :destroy_async_parent_id,
primary_key: :parent_id,
class_name: "DestroyAsyncParent"
belongs_to :destroy_async_parent_soft_delete,
dependent: :destroy_async,
ensuring_owner_was: :deleted?, class_name: "DestroyAsyncParentSoftDelete"
end | ruby | github | https://github.com/rails/rails | activerecord/test/models/dl_keyed_belongs_to.rb |
# Owner(s): ["module: nn"]
import unittest
from dataclasses import dataclass
from functools import partial
from itertools import chain, product
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.nn.utils._expanded_weights import ExpandedWeight
from torch.nn.utils._expanded_weights.expanded_weights_utils import (
forward_helper,
set_grad_sample_if_exists,
standard_kwargs,
sum_over_all_but_batch_and_last_n,
unpack_expanded_weight_or_tensor,
)
from torch.nn.utils._per_sample_grad import call_for_per_sample_grads
from torch.testing._internal.common_cuda import TEST_CUDA, tf32_off
from torch.testing._internal.common_device_type import (
instantiate_device_type_tests,
OpDTypes,
ops,
)
from torch.testing._internal.common_methods_invocations import op_db, SampleInput
from torch.testing._internal.common_modules import module_db, modules
from torch.testing._internal.common_nn import (
get_new_module_tests,
module_tests,
TestBase,
)
from torch.testing._internal.common_utils import (
freeze_rng_state,
make_tensor,
parametrize,
run_tests,
skipIfTorchDynamo,
TestCase,
)
from torch.utils._pytree import tree_map_only
class TestContext:
pass
class TestExpandedWeightHelperFunction(TestCase):
def test_forward_helper(self, device):
input = torch.randn(3, 4, device=device)
weight = torch.randn(5, 4, device=device)
bias = torch.randn(5, device=device)
for weight_batched, bias_batched in product([True, False], [True, False]):
maybe_batched_weight = weight
maybe_batched_bias = bias
if weight_batched:
maybe_batched_weight = ExpandedWeight(
weight.clone().requires_grad_(), 3, loss_reduction="sum"
)
if bias_batched:
maybe_batched_bias = ExpandedWeight(
bias.clone().requires_grad_(), 3, loss_reduction="sum"
)
args = (input, maybe_batched_weight, maybe_batched_bias)
expanded_args, expanded_kwargs = standard_kwargs(("bias",), args)
res = forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
expected = nn.functional.linear(input, weight, bias)
self.assertEqual(res, expected)
self.assertEqual(len(expanded_args), 2)
if (
expanded_args[0] is not args[0]
): # avoids property checks in assertEquals
raise AssertionError("expanded_args[0] should be args[0]")
if (
expanded_args[1] is not args[1]
): # avoids property checks in assertEquals
raise AssertionError("expanded_args[1] should be args[1]")
self.assertEqual(len(expanded_kwargs), 1)
if (
expanded_kwargs["bias"] is not args[2]
): # avoids property checks in assertEquals
raise AssertionError("expanded_kwargs['bias'] should be args[2]")
def test_forward_helper_failure_args(self, device):
weight = torch.randn(5, 4, device=device)
bias = torch.randn(5, device=device)
with self.assertRaisesRegex(
RuntimeError, r"do not support inputs that are also ExpandedWeights."
):
input = ExpandedWeight(
torch.randn(3, 4, requires_grad=True), 3, loss_reduction="sum"
)
expanded_args, expanded_kwargs = standard_kwargs(
("bias",), (input, weight, bias)
)
forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
with self.assertRaisesRegex(
RuntimeError, r"requires a Tensor as the first input"
):
expanded_args, expanded_kwargs = standard_kwargs(
("bias",), (3, weight, bias)
)
forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
with self.assertRaisesRegex(
RuntimeError, r"requires a batch dimension but got an input of size 0"
):
expanded_args, expanded_kwargs = standard_kwargs(
("bias",), (torch.tensor(3), weight, bias)
)
forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
with self.assertRaisesRegex(
RuntimeError, r"0 is not a valid batch size for Expanded Weights"
):
expanded_args, expanded_kwargs = standard_kwargs(
("bias",), (torch.randn(0, 1, 2), weight, bias)
)
forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
input = torch.randn(3, 4)
for weight_batched, bias_batched in product([True, False], [True, False]):
if not weight_batched and not bias_batched:
continue
maybe_batched_weight = weight
maybe_batched_bias = bias
if weight_batched:
maybe_batched_weight = ExpandedWeight(
weight.clone().requires_grad_(), 4, loss_reduction="sum"
)
if bias_batched:
maybe_batched_bias = ExpandedWeight(
bias.clone().requires_grad_(), 4, loss_reduction="sum"
)
with self.assertRaisesRegex(
RuntimeError,
r"Expected ExpandedWeights to have batch size matching input",
):
expanded_args, expanded_kwargs = standard_kwargs(
("bias",), (input, maybe_batched_weight, maybe_batched_bias)
)
forward_helper(nn.functional.linear, expanded_args, expanded_kwargs)
def test_set_grad_sample_if_exists(self, device):
def test_fn(a):
return grad_sample
orig_weight = torch.randn(4, device=device, requires_grad=True)
expanded_weight = ExpandedWeight(orig_weight, 3, loss_reduction="sum")
grad_sample = torch.randn(3)
set_grad_sample_if_exists(expanded_weight, test_fn)
self.assertTrue(hasattr(orig_weight, "grad_sample"))
self.assertEqual(orig_weight.grad_sample, grad_sample)
basic_tensor = torch.randn(4, device=device)
set_grad_sample_if_exists(basic_tensor, test_fn)
self.assertFalse(hasattr(basic_tensor, "grad_sample"))
non_tensor = 3
set_grad_sample_if_exists(non_tensor, test_fn)
self.assertFalse(hasattr(non_tensor, "grad_sample"))
def test_set_grad_sample_if_exists_failure(self, device):
def test_fn(a):
return True
grad_tensor = torch.randn(4, requires_grad=True, device=device)
with self.assertRaisesRegex(
RuntimeError,
r"does not support a mixture of ExpandedWeight parameters and normal Parameters",
):
set_grad_sample_if_exists(grad_tensor, test_fn)
def test_unpack_expanded_weight_or_tensor(self, device):
input = torch.randn(3, requires_grad=True, device=device)
self.assertEqual(
input,
unpack_expanded_weight_or_tensor(
ExpandedWeight(input, 3, loss_reduction="sum")
),
)
input.requires_grad_(False)
self.assertEqual(input, unpack_expanded_weight_or_tensor(input))
self.assertTrue(unpack_expanded_weight_or_tensor(4) is None)
def test_unpack_expanded_weight_or_tensor_with_custom_function(self, device):
input = torch.randn(3, requires_grad=True, device=device)
self.assertTrue(
unpack_expanded_weight_or_tensor(
ExpandedWeight(input, 3, loss_reduction="sum"), lambda x: x is input
)
)
input.requires_grad_(False)
self.assertTrue(unpack_expanded_weight_or_tensor(input, lambda x: x is input))
self.assertTrue(
unpack_expanded_weight_or_tensor(4, lambda x: x is input) is None
)
def test_unpack_expanded_weight_or_tensor_failure(self, device):
input = torch.randn(3, requires_grad=True, device=device)
with self.assertRaisesRegex(
RuntimeError,
r"does not support a mixture of ExpandedWeight parameters and normal Parameters",
):
unpack_expanded_weight_or_tensor(input)
with self.assertRaisesRegex(
RuntimeError,
r"does not support a mixture of ExpandedWeight parameters and normal Parameters",
):
unpack_expanded_weight_or_tensor(input, lambda x: x is input)
def test_sum_over_all_but_batch_and_last_n(self, device):
input = torch.randn(1, 2, 3, 4, 5, device=device)
res = sum_over_all_but_batch_and_last_n(input, 2)
expected = input.sum((1, 2))
self.assertEqual(res, expected)
res = sum_over_all_but_batch_and_last_n(input, 0)
expected = input.sum((1, 2, 3, 4))
self.assertEqual(res, expected)
res = sum_over_all_but_batch_and_last_n(input, 4)
self.assertEqual(res, input)
class TestExpandedWeightFunctional(TestCase):
def _compare_ew_and_for_loop_per_sample_grads(self, op, sample_input, reduction):
input = sample_input.input
args = sample_input.args
kwargs = sample_input.kwargs
batch_size = input.shape[0] if len(input.shape) > 1 else 1
# get per sample grads with ExpandedWeights objects
loss_reduction = "sum" if reduction == torch.sum else "mean"
(ew_input, ew_args, ew_kwargs) = make_expanded_weight(
sample_input, batch_size, loss_reduction
)
diff_input_list = (ew_input,) + tuple(ew_args) + tuple(ew_kwargs.values())
diff_input_list = [i for i in diff_input_list if is_diff_tensor(i)]
diff_input_list = [
i.orig_weight if isinstance(i, ExpandedWeight) else i
for i in diff_input_list
]
if not diff_input_list:
return
result = run_op(op, ew_input, *ew_args, **ew_kwargs)
reduction(
result
).backward() # grad doesn't work with ExpandedWeight because it calls __torch_function__
expanded_weight_grad = tuple(
i.grad_sample if hasattr(i, "grad_sample") else i.grad
for i in diff_input_list
)
# get per sample grads with for loop
func = partial(run_op, op)
per_sample_grad = for_loop_per_sample_grad(
batch_size, reduction, input, func, *args, **kwargs
)
# check equality
self.assertEqual(len(per_sample_grad), len(expanded_weight_grad))
if loss_reduction == "mean":
# don't check equality of `input.grad`s since these vanilla tensors won't be scaled
expanded_weight_grad = expanded_weight_grad[1:]
per_sample_grad = per_sample_grad[1:]
for result_grad, expected_grad in zip(expanded_weight_grad, per_sample_grad):
self.assertEqual(result_grad, expected_grad)
@ops(
filter(lambda op: op.supports_expanded_weight, op_db),
dtypes=OpDTypes.supported,
allowed_dtypes=(torch.double,),
)
def test_expanded_weight_per_sample_grad_sum(self, device, dtype, op):
sample_inputs = op.sample_inputs(device, dtype, requires_grad=True)
for sample_input in supported_inputs(op, sample_inputs):
if (
op.name == "nn.functional.embedding"
): # embedding flips its argument order for autograd tests
sample_input = SampleInput(
sample_input.args[0],
args=(sample_input.input,),
kwargs=sample_input.kwargs,
)
self._compare_ew_and_for_loop_per_sample_grads(op, sample_input, torch.sum)
@ops(
filter(lambda op: op.supports_expanded_weight, op_db),
dtypes=OpDTypes.supported,
allowed_dtypes=(torch.double,),
)
def test_expanded_weight_per_sample_grad_mean(self, device, dtype, op):
sample_inputs = op.sample_inputs(device, dtype, requires_grad=True)
for sample_input in supported_inputs(op, sample_inputs):
if (
op.name == "nn.functional.embedding"
): # embedding flips its argument order for autograd tests
sample_input = SampleInput(
sample_input.args[0],
args=(sample_input.input,),
kwargs=sample_input.kwargs,
)
self._compare_ew_and_for_loop_per_sample_grads(op, sample_input, torch.mean)
@ops(
filter(lambda op: op.supports_expanded_weight, op_db),
dtypes=OpDTypes.supported,
allowed_dtypes=(torch.double,),
)
def test_expanded_weights_per_sample_grad_input_no_grad(self, device, dtype, op):
sample_inputs = op.sample_inputs(device, dtype, requires_grad=True)
for sample_input in supported_inputs(op, sample_inputs):
if (
op.name == "nn.functional.embedding"
): # embedding flips its argument order for autograd tests
sample_input = SampleInput(
sample_input.args[0],
args=(sample_input.input,),
kwargs=sample_input.kwargs,
)
sample_input.input.requires_grad_(False)
self._compare_ew_and_for_loop_per_sample_grads(op, sample_input, torch.mean)
@skipIfTorchDynamo("Checking error message doesn't work with dynamo")
@ops(
filter(lambda op: op.supports_expanded_weight, op_db),
dtypes=OpDTypes.supported,
allowed_dtypes=(torch.double,),
)
def test_unsupported_expand_weights(self, device, dtype, op):
sample_inputs = op.sample_inputs(device, dtype, requires_grad=True)
unsupported_inputs = supported_inputs(op, sample_inputs, supported_inputs=False)
for sample_input in unsupported_inputs:
with self.assertRaisesRegex(RuntimeError, r"Expanded Weights"):
if (
op.name == "nn.functional.embedding"
): # embedding flips its argument order for autograd tests
sample_input = SampleInput(
sample_input.args[0],
args=(sample_input.input,),
kwargs=sample_input.kwargs,
)
input = sample_input.input
batch_size = input.shape[0] if len(input.shape) > 1 else 1
# get per sample grads with ExpandedWeights objects
(ew_input, ew_args, ew_kwargs) = make_expanded_weight(
sample_input, batch_size
)
result = run_op(op, ew_input, *ew_args, **ew_kwargs)
diff_input_list = (
(ew_input,) + tuple(ew_args) + tuple(ew_kwargs.values())
)
diff_input_list = [i for i in diff_input_list if is_diff_tensor(i)]
diff_input_list = [
i.orig_weight if isinstance(i, ExpandedWeight) else i
for i in diff_input_list
]
result.sum().backward() # grad doesn't work with ExpandedWeight because it calls __torch_function__
@ops(
filter(lambda op: op.supports_expanded_weight, op_db), dtypes=OpDTypes.supported
)
def test_expanded_weight_forward(self, device, dtype, op):
sample_inputs = op.sample_inputs(device, dtype)
for sample_input in supported_inputs(op, sample_inputs):
if (
op.name == "nn.functional.embedding"
): # embedding flips its argument order for autograd tests
sample_input = SampleInput(
sample_input.args[0].clone(),
args=(sample_input.input.clone(),),
kwargs=sample_input.kwargs,
)
if (
"cuda" in device
and "max_norm" in sample_input.kwargs
and "padding_idx" in sample_input.kwargs
):
self.skipTest(
"embedding is non-determinstic in this case, see issue #74679"
)
batch_size = (
sample_input.input.shape[0] if len(sample_input.input.shape) > 1 else 1
)
for loss_reduction in ["sum", "mean"]:
(ew_input, ew_args, ew_kwargs) = make_expanded_weight(
sample_input, batch_size, loss_reduction
)
expanded_weight_result = run_op(op, ew_input, *ew_args, **ew_kwargs)
normal_result = run_op(
op, sample_input.input, *sample_input.args, **sample_input.kwargs
)
self.assertEqual(expanded_weight_result, normal_result)
def test_expanded_weight_error(self, device):
batch_size = 3
sample_input = make_tensor(
(batch_size, 4), dtype=torch.float32, device=device, requires_grad=True
)
sample_weight = make_tensor(
(4), dtype=torch.float32, device=device, requires_grad=True
)
with self.assertRaisesRegex(
RuntimeError, r"Expanded Weights encountered but cannot handle function"
):
torch.add(
sample_input,
ExpandedWeight(sample_weight, batch_size, loss_reduction="sum"),
)
def _test_embedding_model(self, model, num_embedding, device):
batch_size = 32
input = torch.randint(0, num_embedding, (batch_size, 5, 5), device=device)
return self._test_model(
partial(model, num_embedding=num_embedding), batch_size, input, device
)
def _test_conv_model(
self,
model,
input_size,
num_dim,
device,
loss_reduction="sum",
atol=1e-4,
rtol=5e-5,
):
batch_size = 32
input_ending = [input_size] * num_dim
input = torch.randn([batch_size, 3] + input_ending, device=device)
return self._test_model(
partial(model, num_dim=num_dim),
batch_size,
input,
device,
loss_reduction,
atol,
rtol,
)
def _test_model(
self,
model,
batch_size,
input,
device,
loss_reduction="sum",
atol=1e-4,
rtol=5e-5,
):
model = model(10).to(device)
targets = torch.randint(0, 10, (batch_size,), device=device)
criterion = CrossEntropyLoss(reduction=loss_reduction)
result = call_for_per_sample_grads(model, loss_reduction=loss_reduction)(input)
loss = criterion(result, targets)
loss.backward()
result = []
for weight in model.parameters():
result.append(weight.grad_sample)
del weight.grad_sample
expected = []
for i in range(batch_size):
loss = criterion(model(input[i].unsqueeze(0)), targets[i].unsqueeze(0))
expected.append(
torch.autograd.grad(loss, model.parameters(), torch.ones_like(loss))
)
expected = [torch.stack(grad) for grad in zip(*expected)]
for res, exp in zip(result, expected):
self.assertEqual(res, exp, atol=atol, rtol=rtol)
def _compute_tolerances(self, device):
is_cuda_sm86 = device.startswith("cuda") and torch.cuda.get_device_capability(
0
) == (8, 6)
return (9e-3, 5e-5) if is_cuda_sm86 else (1e-4, 5e-5)
@tf32_off()
def test_cnn_model_sum(self, device):
def convnet(num_classes, num_dim):
return nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(128, num_classes, bias=True),
)
atol, rtol = self._compute_tolerances(device)
return self._test_conv_model(convnet, 28, 2, device, atol=atol, rtol=rtol)
@tf32_off()
def test_cnn_model_mean(self, device):
def convnet(num_classes, num_dim):
return nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(128, num_classes, bias=True),
)
atol, rtol = self._compute_tolerances(device)
return self._test_conv_model(
convnet, 28, 2, device, loss_reduction="mean", atol=atol, rtol=rtol
)
@parametrize("num_dim", [1, 2, 3])
@tf32_off()
def test_instance_norm_model(self, num_dim, device):
def instance_norm_model(num_classes, num_dim):
conv_layer = (
nn.Conv1d if num_dim == 1 else nn.Conv2d if num_dim == 2 else nn.Conv3d
)
norm_layer = (
nn.InstanceNorm1d
if num_dim == 1
else nn.InstanceNorm2d
if num_dim == 2
else nn.InstanceNorm3d
)
return nn.Sequential(
conv_layer(3, 32, kernel_size=3, stride=1, padding=1),
norm_layer(32, affine=True),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(32 * (7**num_dim), num_classes, bias=True),
)
atol, rtol = self._compute_tolerances(device)
return self._test_conv_model(
instance_norm_model, 7, num_dim, device, atol=atol, rtol=rtol
)
@parametrize("num_dim", [1, 2, 3])
@tf32_off()
def test_group_norm_model(self, num_dim, device):
def group_norm_model(num_classes, num_dim):
conv_layer = (
nn.Conv1d if num_dim == 1 else nn.Conv2d if num_dim == 2 else nn.Conv3d
)
return nn.Sequential(
conv_layer(3, 32, kernel_size=3, stride=1, padding=1),
nn.GroupNorm(8, 32, affine=True),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(32 * (7**num_dim), num_classes, bias=True),
)
atol, rtol = self._compute_tolerances(device)
return self._test_conv_model(
group_norm_model, 7, num_dim, device, atol=atol, rtol=rtol
)
@parametrize("num_dim", [1, 2, 3])
@tf32_off()
def test_layer_norm_model(self, num_dim, device):
def layer_norm_model(num_classes, num_dim):
conv_layer = (
nn.Conv1d if num_dim == 1 else nn.Conv2d if num_dim == 2 else nn.Conv3d
)
normalized_shape = [7] * num_dim
return nn.Sequential(
conv_layer(3, 32, kernel_size=3, stride=1, padding=1),
nn.LayerNorm(normalized_shape, elementwise_affine=True),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(32 * (7**num_dim), num_classes, bias=True),
)
atol, rtol = self._compute_tolerances(device)
return self._test_conv_model(
layer_norm_model, 7, num_dim, device, atol=atol, rtol=rtol
)
def test_embedding_model(self, device):
def embedding_model(num_classes, num_embedding):
return nn.Sequential(
nn.Embedding(num_embedding, 15),
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(375, num_classes, bias=True),
)
return self._test_embedding_model(embedding_model, 16, device)
def test_group_norm_error(self, device):
# group norm has to call native_group_norm. This checks that it hits the same errors
# that normal group norm would
N = 3
C = 5
inp = torch.randn(N, C)
with self.assertRaisesRegex(
RuntimeError, r"Expected number of channels in input to be divisible"
):
F.group_norm(inp, 2) # 5 is not divisible by 2
class TestExpandedWeightModule(TestCase):
def _do_test(
self,
module,
input,
args=None,
kwargs=None,
batch_first=True,
atol=None,
rtol=None,
):
args = args or ()
kwargs = kwargs or {}
batch_dim = 0 if batch_first else 1
batch_size = input.shape[batch_dim]
diff_input = input.dtype == torch.float or input.dtype == torch.double
if diff_input:
input.requires_grad_()
with freeze_rng_state():
# get per sample grads with ExpandedWeights context manager
actual_res = call_for_per_sample_grads(
module,
batch_size=batch_size,
loss_reduction="sum",
batch_first=batch_first,
)(input, *args, **kwargs).sum()
actual_res.backward()
actual_grads = []
for param in module.parameters():
actual_grads.append(param.grad_sample)
del param.grad_sample
if diff_input:
actual_grads.append(input.grad.clone())
input.grad = torch.zeros_like(input.grad)
# get per sample grads with a for loop
expected_res = torch.tensor(
0.0, device=input.device, dtype=actual_res.dtype
)
expected_grads = []
for i in range(batch_size):
input_slice = input.narrow(batch_dim, i, 1)
input_slice = input_slice.squeeze(batch_dim)
# h's batch dim is always the first dim. Must be contiguous for CUDA
sliced_args = tree_map_only(
torch.Tensor, lambda t: t.narrow(1, i, 1).contiguous(), args
)
diff_params = module.parameters()
if diff_input:
diff_params = chain(diff_params, (input_slice,))
res = module(
input_slice.unsqueeze(batch_dim).contiguous(),
*sliced_args,
**kwargs,
).sum()
out_grads = torch.autograd.grad(
res, diff_params, torch.ones_like(res), allow_unused=True
)
expected_grads.append(out_grads)
expected_res += res
expected_grads = [torch.stack(grad) for grad in zip(*expected_grads)]
if not batch_first:
expected_grads[-1] = expected_grads[-1].transpose(0, 1)
self.assertEqual(actual_res, expected_res, atol=atol, rtol=rtol)
[
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
for (actual, expected) in zip(actual_grads, expected_grads)
]
def _do_test_multi_input(self, module, input):
class TestModule(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, input):
return self.module(input) + self.module(input)
batch_size = input.shape[0]
diff_input = input.dtype == torch.float or input.dtype == torch.double
if diff_input:
input.requires_grad_()
with freeze_rng_state():
# get per sample grads with ExpandedWeights context manager, calling .backward() twice
test_module = TestModule(module)
actual_res = call_for_per_sample_grads(test_module, loss_reduction="sum")(
input
).sum()
actual_res.backward()
actual_grads = []
for param in module.parameters():
actual_grads.append(param.grad_sample)
del param.grad_sample
if diff_input:
actual_grads.append(input.grad.clone())
input.grad = torch.zeros_like(input.grad)
# get per sample grads with a for loop, running over the input twice
expected_grads = []
for i in range(batch_size):
input_slice = input[i]
diff_params = module.parameters()
if diff_input:
diff_params = chain(diff_params, (input_slice,))
res = module(input_slice.unsqueeze(0)).sum()
out_grads = torch.autograd.grad(
res, diff_params, torch.ones_like(res), allow_unused=True
)
expected_grads.append(out_grads)
expected_grads = tuple(torch.stack(grad) for grad in zip(*expected_grads))
expected_grads = tuple(
expected_grad
for expected_grad in expected_grads
if expected_grad is not None
)
for actual, expected in zip(actual_grads, expected_grads):
self.assertEqual(actual, 2 * expected)
def _do_test_rnn_packed_sequence(
self, module, input, args=None, kwargs=None, atol=None, rtol=None
):
args = args if args is not None else ()
kwargs = kwargs if kwargs is not None else {}
batch_size = max(tuple(input.batch_sizes)).item()
with freeze_rng_state():
# get per sample grads with ExpandedWeights context manager
actual_res = call_for_per_sample_grads(
module, batch_size=batch_size, loss_reduction="sum"
)(input, *args, **kwargs).data.sum()
actual_res.backward()
actual_grads = []
for param in module.parameters():
self.assertEqual(param.grad_sample.shape[0], batch_size)
actual_grads.append(param.grad_sample)
del param.grad_sample
input.data.grad = torch.zeros_like(input.data)
# compute the per sample grads with a for loop
expected_res = torch.zeros_like(actual_res)
expected_grads = []
padded_input, seq_sizes = torch.nn.utils.rnn.pad_packed_sequence(
input, batch_first=True
)
for i in range(len(seq_sizes)):
input_slice = padded_input[i].narrow(0, 0, seq_sizes[i])
diff_params = module.parameters()
batch_dim = 0 if module.m.batch_first else 1
res = module(input_slice.unsqueeze(batch_dim), *args, **kwargs).sum()
expected_res += res
out_grads = torch.autograd.grad(
res, diff_params, torch.ones_like(res), allow_unused=True
)
expected_grads.append(out_grads)
expected_grads = [torch.stack(grad) for grad in zip(*expected_grads)]
self.assertEqual(actual_res, expected_res, atol=atol, rtol=rtol)
[
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
for (actual, expected) in zip(actual_grads, expected_grads)
]
@modules(
filter(
lambda m_info: m_info.module_cls
in (torch.nn.RNN, torch.nn.LSTM, torch.nn.GRU),
module_db,
)
)
@tf32_off()
def test_module(self, device, dtype, module_info, training):
class RNNWrapper(torch.nn.Module):
def __init__(self, m_cons, args, kwargs):
super().__init__()
self.m = m_cons(*args, **kwargs)
def forward(self, *inps):
ret = self.m(*inps)
if not isinstance(ret, tuple):
raise AssertionError(f"expected tuple, got {type(ret)}")
return ret[0]
def batch_hidden(h):
new_h_shape = [1] * (len(h.shape) + 1)
new_h_shape[1] = 2
return h.unsqueeze(1).repeat(new_h_shape)
module_cls = module_info.module_cls
atol, rtol = (1e-3, 1e-4) if dtype == torch.float32 else (None, None)
module_inputs = module_info.module_inputs_func(
module_info,
device=device,
dtype=dtype,
requires_grad=True,
training=training,
with_packed_sequence=True,
)
for module_input in module_inputs:
if module_input.forward_input is None:
continue
args, kwargs = (
module_input.constructor_input.args,
module_input.constructor_input.kwargs,
)
m = RNNWrapper(module_cls, args, kwargs)
batch_first = m.m.batch_first
m.to(device).to(dtype)
args, kwargs = (
module_input.forward_input.args,
module_input.forward_input.kwargs,
)
# if the RNN tests use unbatched inputs--batch the inputs
input = args[0]
if isinstance(input, torch.Tensor) and input.dim() == 2:
input = input.detach()
new_input_shape = [1] * (len(input.shape) + 1)
if batch_first:
new_input_shape[0] = 2
input = input.repeat(new_input_shape)
else:
new_input_shape[1] = 2
input = input.unsqueeze(1).repeat(new_input_shape)
h = args[1] if len(args) > 1 else None
if h is not None:
h = (
batch_hidden(h)
if isinstance(h, torch.Tensor)
else tuple(batch_hidden(hx) for hx in h)
)
args = list(args)
args[1] = h
if isinstance(input, torch.nn.utils.rnn.PackedSequence):
self._do_test_rnn_packed_sequence(
m, input, args[1:], kwargs, atol=atol, rtol=rtol
)
else:
self._do_test(
m,
input,
args[1:],
kwargs,
batch_first=batch_first,
atol=atol,
rtol=rtol,
)
def test_per_sample_api_failing(self):
module = nn.Linear(10, 10)
input = torch.randn(64, 10)
with self.assertRaisesRegex(RuntimeError, r"Module passed must be nn.Module"):
call_for_per_sample_grads("fail")(input)
with self.assertRaisesRegex(
RuntimeError, r"Batch size passed must be None or an integer"
):
call_for_per_sample_grads(module, batch_size=6.4)(input)
with self.assertRaisesRegex(RuntimeError, r"Batch size must be positive"):
call_for_per_sample_grads(module, batch_size=-64)(input)
with self.assertRaisesRegex(RuntimeError, r"incorrect for multiple calls"):
loss = call_for_per_sample_grads(module)(input).sum()
loss.backward() # populate grad_sample fields
call_for_per_sample_grads(module)(input)
module = nn.Linear(10, 10) # reset to not have grad_sample fields
with self.assertRaisesRegex(
RuntimeError, r"Expected loss_reduction argument to be sum or mean"
):
call_for_per_sample_grads(module, loss_reduction="")(input)
def test_per_sample_api_compute_batch_size(self):
class CustomModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear = nn.Linear(5, 5)
def forward(self, input1, input2):
return self.linear(input1) + self.linear(input2)
module = CustomModule()
input1 = torch.randn(4, 5)
input2 = torch.randn(5, 5)
with self.assertRaisesRegex(
RuntimeError,
"found at least one input with batch size 4 and one with batch size 5",
):
call_for_per_sample_grads(module)(input1, input2)
input2 = torch.randn(4, 5)
call_for_per_sample_grads(module)(input1, input2)
module = CustomModule()
call_for_per_sample_grads(module)(input1, input2=input2)
module = CustomModule()
call_for_per_sample_grads(module)(input1=input1, input2=input2)
def test_per_sample_api_compute_batch_size_not_pytreeable(self):
@dataclass
class NonPytreeableTuple:
elem1: torch.Tensor
elem2: torch.Tensor
class CustomModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear = nn.Linear(5, 5)
def forward(self, input1, input2):
return self.linear(input1.elem1) + self.linear(input1.elem2)
input = NonPytreeableTuple(torch.randn(4, 5), torch.randn(4, 5))
model = CustomModule()
with self.assertRaisesRegex(
RuntimeError,
"ExpandedWeights cannot compute the batch size from the inputs",
):
call_for_per_sample_grads(model)(input, "")
# would prefer for it to error because input is not pytree-able but that's hard to detect
with self.assertRaisesRegex(
RuntimeError, "Expected ExpandedWeights to have batch size matching input"
):
call_for_per_sample_grads(model)(input, torch.randn(5))
model = CustomModule() # TODO: functional call bug, sam will fix
call_for_per_sample_grads(model)(input, torch.randn(4, 5))
model = CustomModule()
call_for_per_sample_grads(model, batch_size=4)(input, torch.randn(5))
class ContextManagerTests(TestBase):
def __init__(self, *args, **kwargs):
self.test_cpu = kwargs.get("test_cpu", True)
self.test_cuda = kwargs.get("test_cuda", True)
super().__init__(*args, **kwargs)
@property
def constructor_args(self):
return self._get_arg("constructor_args", False)
def test_context_manager(self, test_case, device):
kwargs = {"device": device, "dtype": torch.double}
module = self.constructor(*self.constructor_args).to(**kwargs)
if "Embedding" in self.get_name():
kwargs["dtype"] = torch.long
input = self._get_input().to(**kwargs)
if len(input.shape) == 0 or input.shape[0] == 0:
raise unittest.SkipTest(
"Can't get per sample gradients when no batch dim or batch dim is 0"
)
if self.constructor == torch.nn.Linear and len(input.shape) == 1:
raise unittest.SkipTest(
"Can't get per sample gradients for input of rank 1"
)
test_case._do_test(module, input)
def test_context_manager_multiple_inputs(self, test_case, device):
module = self.constructor(*self.constructor_args).to(device)
input = self._get_input()
if len(input.shape) == 0 or input.shape[0] == 0:
raise unittest.SkipTest(
"Can't get per sample gradients when no batch dim or batch dim is 0"
)
if self.constructor == torch.nn.Linear and len(input.shape) == 1:
raise unittest.SkipTest(
"Can't get per sample gradients for input of rank 1"
)
test_case._do_test_multi_input(module, input)
def filter_supported_tests(t):
supported_modules = [
"Linear",
"Conv1d",
"Conv2d",
"Conv3d",
"Embedding",
"LayerNorm",
"GroupNorm",
"InstanceNorm",
]
if "module_name" in t and t["module_name"] in supported_modules:
return True
# TODO: Once all of these use ModuleInfo, replace with ModuleInfo tests
# These currently use the legacy nn tests
supported_tests = [
t for t in module_tests + get_new_module_tests() if filter_supported_tests(t)
]
for test_param in supported_tests:
if "constructor" not in test_param:
name = test_param.pop("module_name")
test_param["constructor"] = getattr(nn, name)
decorator = test_param.pop("decorator", lambda test: test)
test = ContextManagerTests(**test_param)
test_name = test.get_name()
if hasattr(TestExpandedWeightModule, test_name):
raise RuntimeError("Found two tests with the same name: " + test_name)
test_name_multi_input = test.get_name() + "_multiple_inputs"
if hasattr(TestExpandedWeightModule, test_name_multi_input):
raise RuntimeError("Found two tests with the same name: " + test_name)
if test.test_cpu:
setattr(
TestExpandedWeightModule,
test_name,
decorator(lambda self, test=test: test.test_context_manager(self, "cpu")),
)
setattr(
TestExpandedWeightModule,
test_name_multi_input,
decorator(
lambda self, test=test: test.test_context_manager_multiple_inputs(
self, "cpu"
)
),
)
if TEST_CUDA and test.test_cuda:
# since this checks derivatives, only use double for precision
setattr(
TestExpandedWeightModule,
test_name + "_cuda_double",
decorator(lambda self, test=test: test.test_context_manager(self, "cuda")),
)
# ------------- HELPER FUNCTIONS -----------------
def run_op(op, input, *args, **kwargs):
r"""
OpInfo for Embedding switches the input and weight so autograd tests will only check the derivative
of the weight, not the input, which can't be differentiable since its dtype is int. Calls op,
using the special ordering that Embedding's OpInfo expects for that case.
"""
if op.name == "nn.functional.embedding":
return op(args[0], input, **kwargs)
else:
return op(input, *args, **kwargs)
def make_expanded_weight(sample_input, batch_size, loss_reduction="sum"):
def expanded_weight_or_clone(arg):
if is_diff_tensor(arg):
return ExpandedWeight(torch.clone(arg), batch_size, loss_reduction)
return clone_if_tensor(arg)
ew_input = clone_if_tensor(sample_input.input)
ew_args = tuple(expanded_weight_or_clone(arg) for arg in sample_input.args)
ew_kwargs = {
name: expanded_weight_or_clone(arg)
for (name, arg) in sample_input.kwargs.items()
}
return ew_input, ew_args, ew_kwargs
def supported_inputs(op, sample_inputs, supported_inputs=True):
r"""
ExpandedWeights currently does not support some use cases when there's no batch dimension or
operations that would cause inter-batch operations. Removes all of the cases it cannot deal with
"""
def filter_fn(input):
convolutions = [
"nn.functional.conv1d",
"nn.functional.conv2d",
"nn.functional.conv3d",
]
batched_input_size = dict(zip(convolutions, [3, 4, 5]))
if op.name == "nn.functional.linear":
is_supported_input = (
input.input.dim() > 1
) # input of rank 1 means no batch dim
elif op.name == "nn.functional.layer_norm":
normalized_shape = input.args[0]
is_supported_input = (
input.input.shape != normalized_shape
) # would cause inter-batch operations
elif op.name in convolutions:
# currently can't deal with padding computation on Python level
is_supported_input = input.input.dim() == batched_input_size[op.name]
elif op.name == "nn.functional.embedding":
idx = input.args[0]
is_supported_input = len(idx.shape) > 1 # there's no batch size
else:
is_supported_input = True
is_supported_input = (
is_supported_input and input.input.shape[0] > 0
) # 0 is not a valid batch size
return is_supported_input if supported_inputs else not is_supported_input
return [input for input in sample_inputs if filter_fn(input)]
def for_loop_per_sample_grad(batch_size, reduction, input, func, *args, **kwargs):
# get per sample grads by getting derivative for each input in a for loop
per_sample_grad = []
for i in range(batch_size):
per_sample_input = input[i]
result = reduction(func(per_sample_input.unsqueeze(0), *args, **kwargs))
diff_input_list = (per_sample_input,) + tuple(args) + tuple(kwargs.values())
diff_input_list = [
i
for i in diff_input_list
if isinstance(i, torch.Tensor) and i.requires_grad
]
per_sample_grad.append(
torch.autograd.grad(
result, diff_input_list, torch.ones_like(result), allow_unused=True
)
)
if len(per_sample_grad) == batch_size:
per_sample_grad = tuple(torch.stack(grad) for grad in zip(*per_sample_grad))
return per_sample_grad
def is_diff_tensor(t):
return isinstance(t, ExpandedWeight) or (
isinstance(t, torch.Tensor) and t.requires_grad
)
def clone_if_tensor(t):
if isinstance(t, torch.Tensor):
res = torch.clone(t).detach()
res.requires_grad_(t.requires_grad)
return res
else:
return t
instantiate_device_type_tests(TestExpandedWeightHelperFunction, globals())
instantiate_device_type_tests(TestExpandedWeightFunctional, globals())
instantiate_device_type_tests(TestExpandedWeightModule, globals())
if __name__ == "__main__":
run_tests() | python | github | https://github.com/pytorch/pytorch | test/test_expanded_weights.py |
#!/usr/bin/env python
# coding=utf-8
import libsbml
import libsbmlsim
import numpy as np
import matplotlib.pyplot as plt
from biopredyn import result
# Simulation conditions
model_file = "FEBS_antimony.xml"
start = 0.0
end = 20.0
steps = 100.0
step = (end - start) / steps
# Open SBML file
reader = libsbml.SBMLReader()
doc = reader.readSBMLFromFile(model_file)
# Simulate model with stiff solver
r_stiff = libsbmlsim.simulateSBMLFromString(
doc.toSBML(),
end,
step,
1,
0,
libsbmlsim.MTHD_RUNGE_KUTTA,
0)
stiff_result = result.TimeSeries()
stiff_result.import_from_libsbmlsim(r_stiff, 0.0)
# Simulate model with non-stiff solver
r_non_stiff = libsbmlsim.simulateSBMLFromString(
doc.toSBML(),
end,
step,
1,
0,
libsbmlsim.MTHD_ADAMS_MOULTON_2,
0)
non_stiff_result = result.TimeSeries()
names = non_stiff_result.import_from_libsbmlsim(r_non_stiff, 0.0)
# Plot results - for each species, time series produced
# by both solvers are plotted
time = np.array(stiff_result.get_time_steps()) # Same for all plots
plt.figure(1)
for s in range(len(names)):
if not str.lower(names[s]).__contains__("time"):
plt.subplot(2,2,s)
plt.title(str(names[s]))
stiff = stiff_result.get_quantities_per_species(names[s])
non_stiff = non_stiff_result.get_quantities_per_species(names[s])
plt.plot(time, stiff, label='stiff_solver')
plt.plot(time, non_stiff, label='non_stiff_solver')
plt.legend()
# Plot difference between stiff and non-stiff solutions
plt.figure(2)
plt.title("Absolute difference between stiff and non-stiff simulations")
for s in range(len(names)):
if not str.lower(names[s]).__contains__("time"):
stiff = np.array(stiff_result.get_quantities_per_species(names[s]))
non_stiff = np.array(non_stiff_result.get_quantities_per_species(names[s]))
diff = abs(stiff - non_stiff)
plt.plot(time, diff, label=str(names[s]))
plt.legend()
plt.show() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, John Dewey <john@dewey.ws>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: rabbitmq_policy
short_description: Manage the state of policies in RabbitMQ.
description:
- Manage the state of a virtual host in RabbitMQ.
version_added: "1.5"
author: "John Dewey (@retr0h)"
options:
name:
description:
- The name of the policy to manage.
required: true
default: null
vhost:
description:
- The name of the vhost to apply to.
required: false
default: /
apply_to:
description:
- What the policy applies to. Requires RabbitMQ 3.2.0 or later.
required: false
default: all
choices: [all, exchanges, queues]
version_added: "2.1"
pattern:
description:
- A regex of queues to apply the policy to.
required: true
default: null
tags:
description:
- A dict or string describing the policy.
required: true
default: null
priority:
description:
- The priority of the policy.
required: false
default: 0
node:
description:
- Erlang node name of the rabbit we wish to configure.
required: false
default: rabbit
state:
description:
- The state of the policy.
default: present
choices: [present, absent]
'''
EXAMPLES = '''
- name: ensure the default vhost contains the HA policy via a dict
rabbitmq_policy:
name: HA
pattern: .*
args:
tags:
ha-mode: all
- name: ensure the default vhost contains the HA policy
rabbitmq_policy:
name: HA
pattern: .*
tags:
ha-mode: all
'''
import json
from ansible.module_utils.basic import AnsibleModule
class RabbitMqPolicy(object):
def __init__(self, module, name):
self._module = module
self._name = name
self._vhost = module.params['vhost']
self._pattern = module.params['pattern']
self._apply_to = module.params['apply_to']
self._tags = module.params['tags']
self._priority = module.params['priority']
self._node = module.params['node']
self._rabbitmqctl = module.get_bin_path('rabbitmqctl', True)
def _exec(self, args, run_in_check_mode=False):
if not self._module.check_mode or (self._module.check_mode and run_in_check_mode):
cmd = [self._rabbitmqctl, '-q', '-n', self._node]
args.insert(1, '-p')
args.insert(2, self._vhost)
rc, out, err = self._module.run_command(cmd + args, check_rc=True)
return out.splitlines()
return list()
def list(self):
policies = self._exec(['list_policies'], True)
for policy in policies:
policy_name = policy.split('\t')[1]
if policy_name == self._name:
return True
return False
def set(self):
args = ['set_policy']
args.append(self._name)
args.append(self._pattern)
args.append(json.dumps(self._tags))
args.append('--priority')
args.append(self._priority)
if self._apply_to != 'all':
args.append('--apply-to')
args.append(self._apply_to)
return self._exec(args)
def clear(self):
return self._exec(['clear_policy', self._name])
def main():
arg_spec = dict(
name=dict(required=True),
vhost=dict(default='/'),
pattern=dict(required=True),
apply_to=dict(default='all', choices=['all', 'exchanges', 'queues']),
tags=dict(type='dict', required=True),
priority=dict(default='0'),
node=dict(default='rabbit'),
state=dict(default='present', choices=['present', 'absent']),
)
module = AnsibleModule(
argument_spec=arg_spec,
supports_check_mode=True
)
name = module.params['name']
state = module.params['state']
rabbitmq_policy = RabbitMqPolicy(module, name)
result = dict(changed=False, name=name, state=state)
if rabbitmq_policy.list():
if state == 'absent':
rabbitmq_policy.clear()
result['changed'] = True
else:
result['changed'] = False
elif state == 'present':
rabbitmq_policy.set()
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
from __future__ import print_function, division
from sympy import Basic, Expr
from .matexpr import ShapeError
class Trace(Expr):
"""Matrix Trace
Represents the trace of a matrix expression.
>>> from sympy import MatrixSymbol, Trace, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> Trace(A)
Trace(A)
See Also:
trace
"""
is_Trace = True
def __new__(cls, mat):
if not mat.is_Matrix:
raise TypeError("input to Trace, %s, is not a matrix" % str(mat))
if not mat.is_square:
raise ShapeError("Trace of a non-square matrix")
return Basic.__new__(cls, mat)
def _eval_transpose(self):
return self
@property
def arg(self):
return self.args[0]
def doit(self, **kwargs):
if kwargs.get('deep', False):
arg = self.arg.doit()
else:
arg = self.arg
try:
return arg._eval_trace()
except (AttributeError, NotImplementedError):
return Trace(arg)
def _eval_rewrite_as_Sum(self):
from sympy import Sum, Dummy
i = Dummy('i')
return Sum(self.arg[i, i], (i, 0, self.arg.rows-1)).doit()
def trace(expr):
""" Trace of a Matrix. Sum of the diagonal elements
>>> from sympy import trace, Symbol, MatrixSymbol, pprint, eye
>>> n = Symbol('n')
>>> X = MatrixSymbol('X', n, n) # A square matrix
>>> trace(2*X)
2*Trace(X)
>>> trace(eye(3))
3
See Also:
Trace
"""
return Trace(expr).doit() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env bash
# if no version string is passed as an argument, read VERSION file
if [ $# -eq 0 ]; then
VERSION="$(< VERSION)"
else
VERSION=$1
fi
# Remove leading 'v' if present
VERSION="${VERSION#v}"
# Extract MAJOR, MINOR, and REST
MAJOR="${VERSION%%.*}"
MINOR="${VERSION#*.}"; MINOR="${MINOR%%.*}"
REST="${VERSION#*.*.}"
# Format and output based on MAJOR version
if [[ "$MAJOR" == "2" ]]; then
echo "0.$MINOR.$REST"
elif [[ "$MAJOR" == "3" ]]; then
printf "0.3%02d.$REST\n" "$MINOR"
fi | unknown | github | https://github.com/prometheus/prometheus | scripts/get_module_version.sh |
/*-------------------------------------------------------------------------
*
* pg_crc32c_sse42.c
* Compute CRC-32C checksum using Intel SSE 4.2 or AVX-512 instructions.
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/port/pg_crc32c_sse42.c
*
*-------------------------------------------------------------------------
*/
#include "c.h"
#include <nmmintrin.h>
#ifdef USE_AVX512_CRC32C_WITH_RUNTIME_CHECK
#include <immintrin.h>
#endif
#include "port/pg_crc32c.h"
pg_attribute_no_sanitize_alignment()
pg_attribute_target("sse4.2")
pg_crc32c
pg_comp_crc32c_sse42(pg_crc32c crc, const void *data, size_t len)
{
const unsigned char *p = data;
const unsigned char *pend = p + len;
/*
* Process eight bytes of data at a time.
*
* NB: We do unaligned accesses here. The Intel architecture allows that,
* and performance testing didn't show any performance gain from aligning
* the begin address.
*/
#ifdef __x86_64__
while (p + 8 <= pend)
{
crc = (uint32) _mm_crc32_u64(crc, *((const uint64 *) p));
p += 8;
}
/* Process remaining full four bytes if any */
if (p + 4 <= pend)
{
crc = _mm_crc32_u32(crc, *((const unsigned int *) p));
p += 4;
}
#else
/*
* Process four bytes at a time. (The eight byte instruction is not
* available on the 32-bit x86 architecture).
*/
while (p + 4 <= pend)
{
crc = _mm_crc32_u32(crc, *((const unsigned int *) p));
p += 4;
}
#endif /* __x86_64__ */
/* Process any remaining bytes one at a time. */
while (p < pend)
{
crc = _mm_crc32_u8(crc, *p);
p++;
}
return crc;
}
#ifdef USE_AVX512_CRC32C_WITH_RUNTIME_CHECK
/*
* Note: There is no copyright notice in the following generated code.
*
* We have modified the output to
* - match our function declaration
* - match whitespace to our project style
* - add a threshold for the alignment stanza
*/
/* Generated by https://github.com/corsix/fast-crc32/ using: */
/* ./generate -i avx512_vpclmulqdq -p crc32c -a v1e */
/* MIT licensed */
#define clmul_lo(a, b) (_mm512_clmulepi64_epi128((a), (b), 0))
#define clmul_hi(a, b) (_mm512_clmulepi64_epi128((a), (b), 17))
pg_attribute_target("vpclmulqdq,avx512vl")
pg_crc32c
pg_comp_crc32c_avx512(pg_crc32c crc, const void *data, size_t len)
{
/* adjust names to match generated code */
pg_crc32c crc0 = crc;
const char *buf = data;
/* Align on cacheline boundary. The threshold is somewhat arbitrary. */
if (unlikely(len > 256))
{
for (; len && ((uintptr_t) buf & 7); --len)
crc0 = _mm_crc32_u8(crc0, *buf++);
while (((uintptr_t) buf & 56) && len >= 8)
{
crc0 = _mm_crc32_u64(crc0, *(const uint64_t *) buf);
buf += 8;
len -= 8;
}
}
if (len >= 64)
{
const char *end = buf + len;
const char *limit = buf + len - 64;
__m128i z0;
/* First vector chunk. */
__m512i x0 = _mm512_loadu_si512((const void *) buf),
y0;
__m512i k;
k = _mm512_broadcast_i32x4(_mm_setr_epi32(0x740eef02, 0, 0x9e4addf8, 0));
x0 = _mm512_xor_si512(_mm512_zextsi128_si512(_mm_cvtsi32_si128(crc0)), x0);
buf += 64;
/* Main loop. */
while (buf <= limit)
{
y0 = clmul_lo(x0, k), x0 = clmul_hi(x0, k);
x0 = _mm512_ternarylogic_epi64(x0, y0,
_mm512_loadu_si512((const void *) buf),
0x96);
buf += 64;
}
/* Reduce 512 bits to 128 bits. */
k = _mm512_setr_epi32(0x1c291d04, 0, 0xddc0152b, 0,
0x3da6d0cb, 0, 0xba4fc28e, 0,
0xf20c0dfe, 0, 0x493c7d27, 0,
0, 0, 0, 0);
y0 = clmul_lo(x0, k), k = clmul_hi(x0, k);
y0 = _mm512_xor_si512(y0, k);
z0 = _mm_ternarylogic_epi64(_mm512_castsi512_si128(y0),
_mm512_extracti32x4_epi32(y0, 1),
_mm512_extracti32x4_epi32(y0, 2),
0x96);
z0 = _mm_xor_si128(z0, _mm512_extracti32x4_epi32(x0, 3));
/* Reduce 128 bits to 32 bits, and multiply by x^32. */
crc0 = _mm_crc32_u64(0, _mm_extract_epi64(z0, 0));
crc0 = _mm_crc32_u64(crc0, _mm_extract_epi64(z0, 1));
len = end - buf;
}
return pg_comp_crc32c_sse42(crc0, buf, len);
}
#endif | c | github | https://github.com/postgres/postgres | src/port/pg_crc32c_sse42.c |
"""A module with the precisions of platform-specific `~numpy.number`s."""
from ._nbit_base import _8Bit, _16Bit, _32Bit, _64Bit, _96Bit, _128Bit
# To-be replaced with a `npt.NBitBase` subclass by numpy's mypy plugin
type _NBitByte = _8Bit
type _NBitShort = _16Bit
type _NBitIntC = _32Bit
type _NBitIntP = _32Bit | _64Bit
type _NBitInt = _NBitIntP
type _NBitLong = _32Bit | _64Bit
type _NBitLongLong = _64Bit
type _NBitHalf = _16Bit
type _NBitSingle = _32Bit
type _NBitDouble = _64Bit
type _NBitLongDouble = _64Bit | _96Bit | _128Bit | python | github | https://github.com/numpy/numpy | numpy/_typing/_nbit.py |
{
"html": {
"type": "Fragment",
"start": 0,
"end": 38,
"children": [
{
"type": "Element",
"start": 0,
"end": 38,
"name": "div",
"attributes": [
{
"type": "Attribute",
"start": 5,
"end": 9,
"name": "a",
"name_loc": {
"start": {
"line": 1,
"column": 5,
"character": 5
},
"end": {
"line": 1,
"column": 6,
"character": 6
}
},
"value": [
{
"start": 8,
"end": 8,
"type": "Text",
"raw": "",
"data": ""
}
]
},
{
"type": "Attribute",
"start": 10,
"end": 16,
"name": "b",
"name_loc": {
"start": {
"line": 1,
"column": 10,
"character": 10
},
"end": {
"line": 1,
"column": 11,
"character": 11
}
},
"value": [
{
"type": "MustacheTag",
"start": 12,
"end": 16,
"expression": {
"type": "Literal",
"start": 13,
"end": 15,
"loc": {
"start": {
"line": 1,
"column": 13
},
"end": {
"line": 1,
"column": 15
}
},
"value": "",
"raw": "''"
}
}
]
},
{
"type": "Attribute",
"start": 17,
"end": 21,
"name": "c",
"name_loc": {
"start": {
"line": 1,
"column": 17,
"character": 17
},
"end": {
"line": 1,
"column": 18,
"character": 18
}
},
"value": [
{
"start": 20,
"end": 20,
"type": "Text",
"raw": "",
"data": ""
}
]
},
{
"type": "Attribute",
"start": 22,
"end": 30,
"name": "d",
"name_loc": {
"start": {
"line": 1,
"column": 22,
"character": 22
},
"end": {
"line": 1,
"column": 23,
"character": 23
}
},
"value": [
{
"type": "MustacheTag",
"start": 25,
"end": 29,
"expression": {
"type": "Literal",
"start": 26,
"end": 28,
"loc": {
"start": {
"line": 1,
"column": 26
},
"end": {
"line": 1,
"column": 28
}
},
"value": "",
"raw": "''"
}
}
]
}
],
"children": []
}
]
}
} | json | github | https://github.com/sveltejs/svelte | packages/svelte/tests/parser-legacy/samples/attribute-empty/output.json |
data = (
'', # 0x00
'', # 0x01
'', # 0x02
'', # 0x03
'', # 0x04
'', # 0x05
'', # 0x06
'', # 0x07
'', # 0x08
'', # 0x09
'', # 0x0a
'', # 0x0b
'', # 0x0c
'', # 0x0d
'', # 0x0e
'', # 0x0f
'', # 0x10
'', # 0x11
'', # 0x12
'', # 0x13
'', # 0x14
'', # 0x15
'', # 0x16
'', # 0x17
'', # 0x18
'', # 0x19
'', # 0x1a
'', # 0x1b
'', # 0x1c
'', # 0x1d
'', # 0x1e
'', # 0x1f
'', # 0x20
'', # 0x21
'', # 0x22
'', # 0x23
'', # 0x24
'', # 0x25
'', # 0x26
'', # 0x27
'', # 0x28
'', # 0x29
'', # 0x2a
'', # 0x2b
'', # 0x2c
'', # 0x2d
'', # 0x2e
'', # 0x2f
'', # 0x30
'', # 0x31
'', # 0x32
'', # 0x33
'', # 0x34
'', # 0x35
'', # 0x36
'', # 0x37
'', # 0x38
'', # 0x39
'', # 0x3a
'', # 0x3b
'', # 0x3c
'', # 0x3d
'', # 0x3e
'', # 0x3f
'', # 0x40
'', # 0x41
'', # 0x42
'', # 0x43
'', # 0x44
'', # 0x45
'', # 0x46
'', # 0x47
'', # 0x48
'', # 0x49
'', # 0x4a
'', # 0x4b
'', # 0x4c
'', # 0x4d
'', # 0x4e
'', # 0x4f
'', # 0x50
'', # 0x51
'', # 0x52
'', # 0x53
'', # 0x54
'', # 0x55
'', # 0x56
'', # 0x57
'', # 0x58
'', # 0x59
'', # 0x5a
'', # 0x5b
'', # 0x5c
'', # 0x5d
'', # 0x5e
'', # 0x5f
'L', # 0x60
'l', # 0x61
'L', # 0x62
'P', # 0x63
'R', # 0x64
'a', # 0x65
't', # 0x66
'H', # 0x67
'h', # 0x68
'K', # 0x69
'k', # 0x6a
'Z', # 0x6b
'z', # 0x6c
'', # 0x6d
'M', # 0x6e
'A', # 0x6f
'', # 0x70
'', # 0x71
'', # 0x72
'', # 0x73
'', # 0x74
'', # 0x75
'', # 0x76
'', # 0x77
'', # 0x78
'', # 0x79
'', # 0x7a
'', # 0x7b
'', # 0x7c
'', # 0x7d
'', # 0x7e
'', # 0x7f
'', # 0x80
'', # 0x81
'', # 0x82
'', # 0x83
'', # 0x84
'', # 0x85
'', # 0x86
'', # 0x87
'', # 0x88
'', # 0x89
'', # 0x8a
'', # 0x8b
'', # 0x8c
'', # 0x8d
'', # 0x8e
'', # 0x8f
'', # 0x90
'', # 0x91
'', # 0x92
'', # 0x93
'', # 0x94
'', # 0x95
'', # 0x96
'', # 0x97
'', # 0x98
'', # 0x99
'', # 0x9a
'', # 0x9b
'', # 0x9c
'', # 0x9d
'', # 0x9e
'', # 0x9f
'', # 0xa0
'', # 0xa1
'', # 0xa2
'', # 0xa3
'', # 0xa4
'', # 0xa5
'', # 0xa6
'', # 0xa7
'', # 0xa8
'', # 0xa9
'', # 0xaa
'', # 0xab
'', # 0xac
'', # 0xad
'', # 0xae
'', # 0xaf
'', # 0xb0
'', # 0xb1
'', # 0xb2
'', # 0xb3
'', # 0xb4
'', # 0xb5
'', # 0xb6
'', # 0xb7
'', # 0xb8
'', # 0xb9
'', # 0xba
'', # 0xbb
'', # 0xbc
'', # 0xbd
'', # 0xbe
'', # 0xbf
'', # 0xc0
'', # 0xc1
'', # 0xc2
'', # 0xc3
'', # 0xc4
'', # 0xc5
'', # 0xc6
'', # 0xc7
'', # 0xc8
'', # 0xc9
'', # 0xca
'', # 0xcb
'', # 0xcc
'', # 0xcd
'', # 0xce
'', # 0xcf
'', # 0xd0
'', # 0xd1
'', # 0xd2
'', # 0xd3
'', # 0xd4
'', # 0xd5
'', # 0xd6
'', # 0xd7
'', # 0xd8
'', # 0xd9
'', # 0xda
'', # 0xdb
'', # 0xdc
'', # 0xdd
'', # 0xde
'', # 0xdf
'', # 0xe0
'', # 0xe1
'', # 0xe2
'', # 0xe3
'', # 0xe4
'', # 0xe5
'', # 0xe6
'', # 0xe7
'', # 0xe8
'', # 0xe9
'', # 0xea
'', # 0xeb
'', # 0xec
'', # 0xed
'', # 0xee
'', # 0xef
'', # 0xf0
'', # 0xf1
'', # 0xf2
'', # 0xf3
'', # 0xf4
'', # 0xf5
'', # 0xf6
'', # 0xf7
'', # 0xf8
'', # 0xf9
'', # 0xfa
'', # 0xfb
'', # 0xfc
'', # 0xfd
'', # 0xfe
) | unknown | codeparrot/codeparrot-clean | ||
# orm/dynamic.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Dynamic collection API.
Dynamic collections act like Query() objects for read operations and support
basic add/delete mutation.
"""
from .. import log, util, exc
from ..sql import operators
from . import (
attributes, object_session, util as orm_util, strategies,
object_mapper, exc as orm_exc, properties
)
from .query import Query
@log.class_logger
@properties.RelationshipProperty.strategy_for(lazy="dynamic")
class DynaLoader(strategies.AbstractRelationshipLoader):
def init_class_attribute(self, mapper):
self.is_class_level = True
if not self.uselist:
raise exc.InvalidRequestError(
"On relationship %s, 'dynamic' loaders cannot be used with "
"many-to-one/one-to-one relationships and/or "
"uselist=False." % self.parent_property)
strategies._register_attribute(
self,
mapper,
useobject=True,
uselist=True,
impl_class=DynamicAttributeImpl,
target_mapper=self.parent_property.mapper,
order_by=self.parent_property.order_by,
query_class=self.parent_property.query_class,
backref=self.parent_property.back_populates,
)
class DynamicAttributeImpl(attributes.AttributeImpl):
uses_objects = True
accepts_scalar_loader = False
supports_population = False
collection = False
def __init__(self, class_, key, typecallable,
dispatch,
target_mapper, order_by, query_class=None, **kw):
super(DynamicAttributeImpl, self).\
__init__(class_, key, typecallable, dispatch, **kw)
self.target_mapper = target_mapper
self.order_by = order_by
if not query_class:
self.query_class = AppenderQuery
elif AppenderMixin in query_class.mro():
self.query_class = query_class
else:
self.query_class = mixin_user_query(query_class)
def get(self, state, dict_, passive=attributes.PASSIVE_OFF):
if not passive & attributes.SQL_OK:
return self._get_collection_history(
state, attributes.PASSIVE_NO_INITIALIZE).added_items
else:
return self.query_class(self, state)
def get_collection(self, state, dict_, user_data=None,
passive=attributes.PASSIVE_NO_INITIALIZE):
if not passive & attributes.SQL_OK:
return self._get_collection_history(state,
passive).added_items
else:
history = self._get_collection_history(state, passive)
return history.added_plus_unchanged
@util.memoized_property
def _append_token(self):
return attributes.Event(self, attributes.OP_APPEND)
@util.memoized_property
def _remove_token(self):
return attributes.Event(self, attributes.OP_REMOVE)
def fire_append_event(self, state, dict_, value, initiator,
collection_history=None):
if collection_history is None:
collection_history = self._modified_event(state, dict_)
collection_history.add_added(value)
for fn in self.dispatch.append:
value = fn(state, value, initiator or self._append_token)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), state, True)
def fire_remove_event(self, state, dict_, value, initiator,
collection_history=None):
if collection_history is None:
collection_history = self._modified_event(state, dict_)
collection_history.add_removed(value)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), state, False)
for fn in self.dispatch.remove:
fn(state, value, initiator or self._remove_token)
def _modified_event(self, state, dict_):
if self.key not in state.committed_state:
state.committed_state[self.key] = CollectionHistory(self, state)
state._modified_event(dict_,
self,
attributes.NEVER_SET)
# this is a hack to allow the fixtures.ComparableEntity fixture
# to work
dict_[self.key] = True
return state.committed_state[self.key]
def set(self, state, dict_, value, initiator,
passive=attributes.PASSIVE_OFF,
check_old=None, pop=False):
if initiator and initiator.parent_token is self.parent_token:
return
if pop and value is None:
return
self._set_iterable(state, dict_, value)
def _set_iterable(self, state, dict_, iterable, adapter=None):
new_values = list(iterable)
if state.has_identity:
old_collection = util.IdentitySet(self.get(state, dict_))
collection_history = self._modified_event(state, dict_)
if not state.has_identity:
old_collection = collection_history.added_items
else:
old_collection = old_collection.union(
collection_history.added_items)
idset = util.IdentitySet
constants = old_collection.intersection(new_values)
additions = idset(new_values).difference(constants)
removals = old_collection.difference(constants)
for member in new_values:
if member in additions:
self.fire_append_event(state, dict_, member, None,
collection_history=collection_history)
for member in removals:
self.fire_remove_event(state, dict_, member, None,
collection_history=collection_history)
def delete(self, *args, **kwargs):
raise NotImplementedError()
def set_committed_value(self, state, dict_, value):
raise NotImplementedError("Dynamic attributes don't support "
"collection population.")
def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF):
c = self._get_collection_history(state, passive)
return c.as_history()
def get_all_pending(self, state, dict_,
passive=attributes.PASSIVE_NO_INITIALIZE):
c = self._get_collection_history(
state, passive)
return [
(attributes.instance_state(x), x)
for x in
c.all_items
]
def _get_collection_history(self, state, passive=attributes.PASSIVE_OFF):
if self.key in state.committed_state:
c = state.committed_state[self.key]
else:
c = CollectionHistory(self, state)
if state.has_identity and (passive & attributes.INIT_OK):
return CollectionHistory(self, state, apply_to=c)
else:
return c
def append(self, state, dict_, value, initiator,
passive=attributes.PASSIVE_OFF):
if initiator is not self:
self.fire_append_event(state, dict_, value, initiator)
def remove(self, state, dict_, value, initiator,
passive=attributes.PASSIVE_OFF):
if initiator is not self:
self.fire_remove_event(state, dict_, value, initiator)
def pop(self, state, dict_, value, initiator,
passive=attributes.PASSIVE_OFF):
self.remove(state, dict_, value, initiator, passive=passive)
class AppenderMixin(object):
query_class = None
def __init__(self, attr, state):
super(AppenderMixin, self).__init__(attr.target_mapper, None)
self.instance = instance = state.obj()
self.attr = attr
mapper = object_mapper(instance)
prop = mapper._props[self.attr.key]
self._criterion = prop._with_parent(
instance,
alias_secondary=False)
if self.attr.order_by:
self._order_by = self.attr.order_by
def session(self):
sess = object_session(self.instance)
if sess is not None and self.autoflush and sess.autoflush \
and self.instance in sess:
sess.flush()
if not orm_util.has_identity(self.instance):
return None
else:
return sess
session = property(session, lambda s, x: None)
def __iter__(self):
sess = self.session
if sess is None:
return iter(self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).added_items)
else:
return iter(self._clone(sess))
def __getitem__(self, index):
sess = self.session
if sess is None:
return self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).indexed(index)
else:
return self._clone(sess).__getitem__(index)
def count(self):
sess = self.session
if sess is None:
return len(self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).added_items)
else:
return self._clone(sess).count()
def _clone(self, sess=None):
# note we're returning an entirely new Query class instance
# here without any assignment capabilities; the class of this
# query is determined by the session.
instance = self.instance
if sess is None:
sess = object_session(instance)
if sess is None:
raise orm_exc.DetachedInstanceError(
"Parent instance %s is not bound to a Session, and no "
"contextual session is established; lazy load operation "
"of attribute '%s' cannot proceed" % (
orm_util.instance_str(instance), self.attr.key))
if self.query_class:
query = self.query_class(self.attr.target_mapper, session=sess)
else:
query = sess.query(self.attr.target_mapper)
query._criterion = self._criterion
query._order_by = self._order_by
return query
def extend(self, iterator):
for item in iterator:
self.attr.append(
attributes.instance_state(self.instance),
attributes.instance_dict(self.instance), item, None)
def append(self, item):
self.attr.append(
attributes.instance_state(self.instance),
attributes.instance_dict(self.instance), item, None)
def remove(self, item):
self.attr.remove(
attributes.instance_state(self.instance),
attributes.instance_dict(self.instance), item, None)
class AppenderQuery(AppenderMixin, Query):
"""A dynamic query that supports basic collection storage operations."""
def mixin_user_query(cls):
"""Return a new class with AppenderQuery functionality layered over."""
name = 'Appender' + cls.__name__
return type(name, (AppenderMixin, cls), {'query_class': cls})
class CollectionHistory(object):
"""Overrides AttributeHistory to receive append/remove events directly."""
def __init__(self, attr, state, apply_to=None):
if apply_to:
coll = AppenderQuery(attr, state).autoflush(False)
self.unchanged_items = util.OrderedIdentitySet(coll)
self.added_items = apply_to.added_items
self.deleted_items = apply_to.deleted_items
self._reconcile_collection = True
else:
self.deleted_items = util.OrderedIdentitySet()
self.added_items = util.OrderedIdentitySet()
self.unchanged_items = util.OrderedIdentitySet()
self._reconcile_collection = False
@property
def added_plus_unchanged(self):
return list(self.added_items.union(self.unchanged_items))
@property
def all_items(self):
return list(self.added_items.union(
self.unchanged_items).union(self.deleted_items))
def as_history(self):
if self._reconcile_collection:
added = self.added_items.difference(self.unchanged_items)
deleted = self.deleted_items.intersection(self.unchanged_items)
unchanged = self.unchanged_items.difference(deleted)
else:
added, unchanged, deleted = self.added_items,\
self.unchanged_items,\
self.deleted_items
return attributes.History(
list(added),
list(unchanged),
list(deleted),
)
def indexed(self, index):
return list(self.added_items)[index]
def add_added(self, value):
self.added_items.add(value)
def add_removed(self, value):
if value in self.added_items:
self.added_items.remove(value)
else:
self.deleted_items.add(value) | unknown | codeparrot/codeparrot-clean | ||
/*---------------------------------------------------------------------------
*
* Ryu floating-point output for double precision.
*
* Portions Copyright (c) 2018-2026, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/common/d2s_full_table.h
*
* This is a modification of code taken from github.com/ulfjack/ryu under the
* terms of the Boost license (not the Apache license). The original copyright
* notice follows:
*
* Copyright 2018 Ulf Adams
*
* The contents of this file may be used under the terms of the Apache
* License, Version 2.0.
*
* (See accompanying file LICENSE-Apache or copy at
* http://www.apache.org/licenses/LICENSE-2.0)
*
* Alternatively, the contents of this file may be used under the terms of the
* Boost Software License, Version 1.0.
*
* (See accompanying file LICENSE-Boost or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*
* Unless required by applicable law or agreed to in writing, this software is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.
*
*---------------------------------------------------------------------------
*/
#ifndef RYU_D2S_FULL_TABLE_H
#define RYU_D2S_FULL_TABLE_H
/*
* These tables are generated (by the upstream) using PrintDoubleLookupTable
* from the upstream sources at github.com/ulfjack/ryu, and then modified (by
* us) by adding UINT64CONST.
*/
static const uint64 DOUBLE_POW5_INV_SPLIT[292][2] = {
{UINT64CONST(1), UINT64CONST(288230376151711744)}, {UINT64CONST(3689348814741910324), UINT64CONST(230584300921369395)},
{UINT64CONST(2951479051793528259), UINT64CONST(184467440737095516)}, {UINT64CONST(17118578500402463900), UINT64CONST(147573952589676412)},
{UINT64CONST(12632330341676300947), UINT64CONST(236118324143482260)}, {UINT64CONST(10105864273341040758), UINT64CONST(188894659314785808)},
{UINT64CONST(15463389048156653253), UINT64CONST(151115727451828646)}, {UINT64CONST(17362724847566824558), UINT64CONST(241785163922925834)},
{UINT64CONST(17579528692795369969), UINT64CONST(193428131138340667)}, {UINT64CONST(6684925324752475329), UINT64CONST(154742504910672534)},
{UINT64CONST(18074578149087781173), UINT64CONST(247588007857076054)}, {UINT64CONST(18149011334012135262), UINT64CONST(198070406285660843)},
{UINT64CONST(3451162622983977240), UINT64CONST(158456325028528675)}, {UINT64CONST(5521860196774363583), UINT64CONST(253530120045645880)},
{UINT64CONST(4417488157419490867), UINT64CONST(202824096036516704)}, {UINT64CONST(7223339340677503017), UINT64CONST(162259276829213363)},
{UINT64CONST(7867994130342094503), UINT64CONST(259614842926741381)}, {UINT64CONST(2605046489531765280), UINT64CONST(207691874341393105)},
{UINT64CONST(2084037191625412224), UINT64CONST(166153499473114484)}, {UINT64CONST(10713157136084480204), UINT64CONST(265845599156983174)},
{UINT64CONST(12259874523609494487), UINT64CONST(212676479325586539)}, {UINT64CONST(13497248433629505913), UINT64CONST(170141183460469231)},
{UINT64CONST(14216899864323388813), UINT64CONST(272225893536750770)}, {UINT64CONST(11373519891458711051), UINT64CONST(217780714829400616)},
{UINT64CONST(5409467098425058518), UINT64CONST(174224571863520493)}, {UINT64CONST(4965798542738183305), UINT64CONST(278759314981632789)},
{UINT64CONST(7661987648932456967), UINT64CONST(223007451985306231)}, {UINT64CONST(2440241304404055250), UINT64CONST(178405961588244985)},
{UINT64CONST(3904386087046488400), UINT64CONST(285449538541191976)}, {UINT64CONST(17880904128604832013), UINT64CONST(228359630832953580)},
{UINT64CONST(14304723302883865611), UINT64CONST(182687704666362864)}, {UINT64CONST(15133127457049002812), UINT64CONST(146150163733090291)},
{UINT64CONST(16834306301794583852), UINT64CONST(233840261972944466)}, {UINT64CONST(9778096226693756759), UINT64CONST(187072209578355573)},
{UINT64CONST(15201174610838826053), UINT64CONST(149657767662684458)}, {UINT64CONST(2185786488890659746), UINT64CONST(239452428260295134)},
{UINT64CONST(5437978005854438120), UINT64CONST(191561942608236107)}, {UINT64CONST(15418428848909281466), UINT64CONST(153249554086588885)},
{UINT64CONST(6222742084545298729), UINT64CONST(245199286538542217)}, {UINT64CONST(16046240111861969953), UINT64CONST(196159429230833773)},
{UINT64CONST(1768945645263844993), UINT64CONST(156927543384667019)}, {UINT64CONST(10209010661905972635), UINT64CONST(251084069415467230)},
{UINT64CONST(8167208529524778108), UINT64CONST(200867255532373784)}, {UINT64CONST(10223115638361732810), UINT64CONST(160693804425899027)},
{UINT64CONST(1599589762411131202), UINT64CONST(257110087081438444)}, {UINT64CONST(4969020624670815285), UINT64CONST(205688069665150755)},
{UINT64CONST(3975216499736652228), UINT64CONST(164550455732120604)}, {UINT64CONST(13739044029062464211), UINT64CONST(263280729171392966)},
{UINT64CONST(7301886408508061046), UINT64CONST(210624583337114373)}, {UINT64CONST(13220206756290269483), UINT64CONST(168499666669691498)},
{UINT64CONST(17462981995322520850), UINT64CONST(269599466671506397)}, {UINT64CONST(6591687966774196033), UINT64CONST(215679573337205118)},
{UINT64CONST(12652048002903177473), UINT64CONST(172543658669764094)}, {UINT64CONST(9175230360419352987), UINT64CONST(276069853871622551)},
{UINT64CONST(3650835473593572067), UINT64CONST(220855883097298041)}, {UINT64CONST(17678063637842498946), UINT64CONST(176684706477838432)},
{UINT64CONST(13527506561580357021), UINT64CONST(282695530364541492)}, {UINT64CONST(3443307619780464970), UINT64CONST(226156424291633194)},
{UINT64CONST(6443994910566282300), UINT64CONST(180925139433306555)}, {UINT64CONST(5155195928453025840), UINT64CONST(144740111546645244)},
{UINT64CONST(15627011115008661990), UINT64CONST(231584178474632390)}, {UINT64CONST(12501608892006929592), UINT64CONST(185267342779705912)},
{UINT64CONST(2622589484121723027), UINT64CONST(148213874223764730)}, {UINT64CONST(4196143174594756843), UINT64CONST(237142198758023568)},
{UINT64CONST(10735612169159626121), UINT64CONST(189713759006418854)}, {UINT64CONST(12277838550069611220), UINT64CONST(151771007205135083)},
{UINT64CONST(15955192865369467629), UINT64CONST(242833611528216133)}, {UINT64CONST(1696107848069843133), UINT64CONST(194266889222572907)},
{UINT64CONST(12424932722681605476), UINT64CONST(155413511378058325)}, {UINT64CONST(1433148282581017146), UINT64CONST(248661618204893321)},
{UINT64CONST(15903913885032455010), UINT64CONST(198929294563914656)}, {UINT64CONST(9033782293284053685), UINT64CONST(159143435651131725)},
{UINT64CONST(14454051669254485895), UINT64CONST(254629497041810760)}, {UINT64CONST(11563241335403588716), UINT64CONST(203703597633448608)},
{UINT64CONST(16629290697806691620), UINT64CONST(162962878106758886)}, {UINT64CONST(781423413297334329), UINT64CONST(260740604970814219)},
{UINT64CONST(4314487545379777786), UINT64CONST(208592483976651375)}, {UINT64CONST(3451590036303822229), UINT64CONST(166873987181321100)},
{UINT64CONST(5522544058086115566), UINT64CONST(266998379490113760)}, {UINT64CONST(4418035246468892453), UINT64CONST(213598703592091008)},
{UINT64CONST(10913125826658934609), UINT64CONST(170878962873672806)}, {UINT64CONST(10082303693170474728), UINT64CONST(273406340597876490)},
{UINT64CONST(8065842954536379782), UINT64CONST(218725072478301192)}, {UINT64CONST(17520720807854834795), UINT64CONST(174980057982640953)},
{UINT64CONST(5897060404116273733), UINT64CONST(279968092772225526)}, {UINT64CONST(1028299508551108663), UINT64CONST(223974474217780421)},
{UINT64CONST(15580034865808528224), UINT64CONST(179179579374224336)}, {UINT64CONST(17549358155809824511), UINT64CONST(286687326998758938)},
{UINT64CONST(2971440080422128639), UINT64CONST(229349861599007151)}, {UINT64CONST(17134547323305344204), UINT64CONST(183479889279205720)},
{UINT64CONST(13707637858644275364), UINT64CONST(146783911423364576)}, {UINT64CONST(14553522944347019935), UINT64CONST(234854258277383322)},
{UINT64CONST(4264120725993795302), UINT64CONST(187883406621906658)}, {UINT64CONST(10789994210278856888), UINT64CONST(150306725297525326)},
{UINT64CONST(9885293106962350374), UINT64CONST(240490760476040522)}, {UINT64CONST(529536856086059653), UINT64CONST(192392608380832418)},
{UINT64CONST(7802327114352668369), UINT64CONST(153914086704665934)}, {UINT64CONST(1415676938738538420), UINT64CONST(246262538727465495)},
{UINT64CONST(1132541550990830736), UINT64CONST(197010030981972396)}, {UINT64CONST(15663428499760305882), UINT64CONST(157608024785577916)},
{UINT64CONST(17682787970132668764), UINT64CONST(252172839656924666)}, {UINT64CONST(10456881561364224688), UINT64CONST(201738271725539733)},
{UINT64CONST(15744202878575200397), UINT64CONST(161390617380431786)}, {UINT64CONST(17812026976236499989), UINT64CONST(258224987808690858)},
{UINT64CONST(3181575136763469022), UINT64CONST(206579990246952687)}, {UINT64CONST(13613306553636506187), UINT64CONST(165263992197562149)},
{UINT64CONST(10713244041592678929), UINT64CONST(264422387516099439)}, {UINT64CONST(12259944048016053467), UINT64CONST(211537910012879551)},
{UINT64CONST(6118606423670932450), UINT64CONST(169230328010303641)}, {UINT64CONST(2411072648389671274), UINT64CONST(270768524816485826)},
{UINT64CONST(16686253377679378312), UINT64CONST(216614819853188660)}, {UINT64CONST(13349002702143502650), UINT64CONST(173291855882550928)},
{UINT64CONST(17669055508687693916), UINT64CONST(277266969412081485)}, {UINT64CONST(14135244406950155133), UINT64CONST(221813575529665188)},
{UINT64CONST(240149081334393137), UINT64CONST(177450860423732151)}, {UINT64CONST(11452284974360759988), UINT64CONST(283921376677971441)},
{UINT64CONST(5472479164746697667), UINT64CONST(227137101342377153)}, {UINT64CONST(11756680961281178780), UINT64CONST(181709681073901722)},
{UINT64CONST(2026647139541122378), UINT64CONST(145367744859121378)}, {UINT64CONST(18000030682233437097), UINT64CONST(232588391774594204)},
{UINT64CONST(18089373360528660001), UINT64CONST(186070713419675363)}, {UINT64CONST(3403452244197197031), UINT64CONST(148856570735740291)},
{UINT64CONST(16513570034941246220), UINT64CONST(238170513177184465)}, {UINT64CONST(13210856027952996976), UINT64CONST(190536410541747572)},
{UINT64CONST(3189987192878576934), UINT64CONST(152429128433398058)}, {UINT64CONST(1414630693863812771), UINT64CONST(243886605493436893)},
{UINT64CONST(8510402184574870864), UINT64CONST(195109284394749514)}, {UINT64CONST(10497670562401807014), UINT64CONST(156087427515799611)},
{UINT64CONST(9417575270359070576), UINT64CONST(249739884025279378)}, {UINT64CONST(14912757845771077107), UINT64CONST(199791907220223502)},
{UINT64CONST(4551508647133041040), UINT64CONST(159833525776178802)}, {UINT64CONST(10971762650154775986), UINT64CONST(255733641241886083)},
{UINT64CONST(16156107749607641435), UINT64CONST(204586912993508866)}, {UINT64CONST(9235537384944202825), UINT64CONST(163669530394807093)},
{UINT64CONST(11087511001168814197), UINT64CONST(261871248631691349)}, {UINT64CONST(12559357615676961681), UINT64CONST(209496998905353079)},
{UINT64CONST(13736834907283479668), UINT64CONST(167597599124282463)}, {UINT64CONST(18289587036911657145), UINT64CONST(268156158598851941)},
{UINT64CONST(10942320814787415393), UINT64CONST(214524926879081553)}, {UINT64CONST(16132554281313752961), UINT64CONST(171619941503265242)},
{UINT64CONST(11054691591134363444), UINT64CONST(274591906405224388)}, {UINT64CONST(16222450902391311402), UINT64CONST(219673525124179510)},
{UINT64CONST(12977960721913049122), UINT64CONST(175738820099343608)}, {UINT64CONST(17075388340318968271), UINT64CONST(281182112158949773)},
{UINT64CONST(2592264228029443648), UINT64CONST(224945689727159819)}, {UINT64CONST(5763160197165465241), UINT64CONST(179956551781727855)},
{UINT64CONST(9221056315464744386), UINT64CONST(287930482850764568)}, {UINT64CONST(14755542681855616155), UINT64CONST(230344386280611654)},
{UINT64CONST(15493782960226403247), UINT64CONST(184275509024489323)}, {UINT64CONST(1326979923955391628), UINT64CONST(147420407219591459)},
{UINT64CONST(9501865507812447252), UINT64CONST(235872651551346334)}, {UINT64CONST(11290841220991868125), UINT64CONST(188698121241077067)},
{UINT64CONST(1653975347309673853), UINT64CONST(150958496992861654)}, {UINT64CONST(10025058185179298811), UINT64CONST(241533595188578646)},
{UINT64CONST(4330697733401528726), UINT64CONST(193226876150862917)}, {UINT64CONST(14532604630946953951), UINT64CONST(154581500920690333)},
{UINT64CONST(1116074521063664381), UINT64CONST(247330401473104534)}, {UINT64CONST(4582208431592841828), UINT64CONST(197864321178483627)},
{UINT64CONST(14733813189500004432), UINT64CONST(158291456942786901)}, {UINT64CONST(16195403473716186445), UINT64CONST(253266331108459042)},
{UINT64CONST(5577625149489128510), UINT64CONST(202613064886767234)}, {UINT64CONST(8151448934333213131), UINT64CONST(162090451909413787)},
{UINT64CONST(16731667109675051333), UINT64CONST(259344723055062059)}, {UINT64CONST(17074682502481951390), UINT64CONST(207475778444049647)},
{UINT64CONST(6281048372501740465), UINT64CONST(165980622755239718)}, {UINT64CONST(6360328581260874421), UINT64CONST(265568996408383549)},
{UINT64CONST(8777611679750609860), UINT64CONST(212455197126706839)}, {UINT64CONST(10711438158542398211), UINT64CONST(169964157701365471)},
{UINT64CONST(9759603424184016492), UINT64CONST(271942652322184754)}, {UINT64CONST(11497031554089123517), UINT64CONST(217554121857747803)},
{UINT64CONST(16576322872755119460), UINT64CONST(174043297486198242)}, {UINT64CONST(11764721337440549842), UINT64CONST(278469275977917188)},
{UINT64CONST(16790474699436260520), UINT64CONST(222775420782333750)}, {UINT64CONST(13432379759549008416), UINT64CONST(178220336625867000)},
{UINT64CONST(3045063541568861850), UINT64CONST(285152538601387201)}, {UINT64CONST(17193446092222730773), UINT64CONST(228122030881109760)},
{UINT64CONST(13754756873778184618), UINT64CONST(182497624704887808)}, {UINT64CONST(18382503128506368341), UINT64CONST(145998099763910246)},
{UINT64CONST(3586563302416817083), UINT64CONST(233596959622256395)}, {UINT64CONST(2869250641933453667), UINT64CONST(186877567697805116)},
{UINT64CONST(17052795772514404226), UINT64CONST(149502054158244092)}, {UINT64CONST(12527077977055405469), UINT64CONST(239203286653190548)},
{UINT64CONST(17400360011128145022), UINT64CONST(191362629322552438)}, {UINT64CONST(2852241564676785048), UINT64CONST(153090103458041951)},
{UINT64CONST(15631632947708587046), UINT64CONST(244944165532867121)}, {UINT64CONST(8815957543424959314), UINT64CONST(195955332426293697)},
{UINT64CONST(18120812478965698421), UINT64CONST(156764265941034957)}, {UINT64CONST(14235904707377476180), UINT64CONST(250822825505655932)},
{UINT64CONST(4010026136418160298), UINT64CONST(200658260404524746)}, {UINT64CONST(17965416168102169531), UINT64CONST(160526608323619796)},
{UINT64CONST(2919224165770098987), UINT64CONST(256842573317791675)}, {UINT64CONST(2335379332616079190), UINT64CONST(205474058654233340)},
{UINT64CONST(1868303466092863352), UINT64CONST(164379246923386672)}, {UINT64CONST(6678634360490491686), UINT64CONST(263006795077418675)},
{UINT64CONST(5342907488392393349), UINT64CONST(210405436061934940)}, {UINT64CONST(4274325990713914679), UINT64CONST(168324348849547952)},
{UINT64CONST(10528270399884173809), UINT64CONST(269318958159276723)}, {UINT64CONST(15801313949391159694), UINT64CONST(215455166527421378)},
{UINT64CONST(1573004715287196786), UINT64CONST(172364133221937103)}, {UINT64CONST(17274202803427156150), UINT64CONST(275782613155099364)},
{UINT64CONST(17508711057483635243), UINT64CONST(220626090524079491)}, {UINT64CONST(10317620031244997871), UINT64CONST(176500872419263593)},
{UINT64CONST(12818843235250086271), UINT64CONST(282401395870821749)}, {UINT64CONST(13944423402941979340), UINT64CONST(225921116696657399)},
{UINT64CONST(14844887537095493795), UINT64CONST(180736893357325919)}, {UINT64CONST(15565258844418305359), UINT64CONST(144589514685860735)},
{UINT64CONST(6457670077359736959), UINT64CONST(231343223497377177)}, {UINT64CONST(16234182506113520537), UINT64CONST(185074578797901741)},
{UINT64CONST(9297997190148906106), UINT64CONST(148059663038321393)}, {UINT64CONST(11187446689496339446), UINT64CONST(236895460861314229)},
{UINT64CONST(12639306166338981880), UINT64CONST(189516368689051383)}, {UINT64CONST(17490142562555006151), UINT64CONST(151613094951241106)},
{UINT64CONST(2158786396894637579), UINT64CONST(242580951921985771)}, {UINT64CONST(16484424376483351356), UINT64CONST(194064761537588616)},
{UINT64CONST(9498190686444770762), UINT64CONST(155251809230070893)}, {UINT64CONST(11507756283569722895), UINT64CONST(248402894768113429)},
{UINT64CONST(12895553841597688639), UINT64CONST(198722315814490743)}, {UINT64CONST(17695140702761971558), UINT64CONST(158977852651592594)},
{UINT64CONST(17244178680193423523), UINT64CONST(254364564242548151)}, {UINT64CONST(10105994129412828495), UINT64CONST(203491651394038521)},
{UINT64CONST(4395446488788352473), UINT64CONST(162793321115230817)}, {UINT64CONST(10722063196803274280), UINT64CONST(260469313784369307)},
{UINT64CONST(1198952927958798777), UINT64CONST(208375451027495446)}, {UINT64CONST(15716557601334680315), UINT64CONST(166700360821996356)},
{UINT64CONST(17767794532651667857), UINT64CONST(266720577315194170)}, {UINT64CONST(14214235626121334286), UINT64CONST(213376461852155336)},
{UINT64CONST(7682039686155157106), UINT64CONST(170701169481724269)}, {UINT64CONST(1223217053622520399), UINT64CONST(273121871170758831)},
{UINT64CONST(15735968901865657612), UINT64CONST(218497496936607064)}, {UINT64CONST(16278123936234436413), UINT64CONST(174797997549285651)},
{UINT64CONST(219556594781725998), UINT64CONST(279676796078857043)}, {UINT64CONST(7554342905309201445), UINT64CONST(223741436863085634)},
{UINT64CONST(9732823138989271479), UINT64CONST(178993149490468507)}, {UINT64CONST(815121763415193074), UINT64CONST(286389039184749612)},
{UINT64CONST(11720143854957885429), UINT64CONST(229111231347799689)}, {UINT64CONST(13065463898708218666), UINT64CONST(183288985078239751)},
{UINT64CONST(6763022304224664610), UINT64CONST(146631188062591801)}, {UINT64CONST(3442138057275642729), UINT64CONST(234609900900146882)},
{UINT64CONST(13821756890046245153), UINT64CONST(187687920720117505)}, {UINT64CONST(11057405512036996122), UINT64CONST(150150336576094004)},
{UINT64CONST(6623802375033462826), UINT64CONST(240240538521750407)}, {UINT64CONST(16367088344252501231), UINT64CONST(192192430817400325)},
{UINT64CONST(13093670675402000985), UINT64CONST(153753944653920260)}, {UINT64CONST(2503129006933649959), UINT64CONST(246006311446272417)},
{UINT64CONST(13070549649772650937), UINT64CONST(196805049157017933)}, {UINT64CONST(17835137349301941396), UINT64CONST(157444039325614346)},
{UINT64CONST(2710778055689733971), UINT64CONST(251910462920982955)}, {UINT64CONST(2168622444551787177), UINT64CONST(201528370336786364)},
{UINT64CONST(5424246770383340065), UINT64CONST(161222696269429091)}, {UINT64CONST(1300097203129523457), UINT64CONST(257956314031086546)},
{UINT64CONST(15797473021471260058), UINT64CONST(206365051224869236)}, {UINT64CONST(8948629602435097724), UINT64CONST(165092040979895389)},
{UINT64CONST(3249760919670425388), UINT64CONST(264147265567832623)}, {UINT64CONST(9978506365220160957), UINT64CONST(211317812454266098)},
{UINT64CONST(15361502721659949412), UINT64CONST(169054249963412878)}, {UINT64CONST(2442311466204457120), UINT64CONST(270486799941460606)},
{UINT64CONST(16711244431931206989), UINT64CONST(216389439953168484)}, {UINT64CONST(17058344360286875914), UINT64CONST(173111551962534787)},
{UINT64CONST(12535955717491360170), UINT64CONST(276978483140055660)}, {UINT64CONST(10028764573993088136), UINT64CONST(221582786512044528)},
{UINT64CONST(15401709288678291155), UINT64CONST(177266229209635622)}, {UINT64CONST(9885339602917624555), UINT64CONST(283625966735416996)},
{UINT64CONST(4218922867592189321), UINT64CONST(226900773388333597)}, {UINT64CONST(14443184738299482427), UINT64CONST(181520618710666877)},
{UINT64CONST(4175850161155765295), UINT64CONST(145216494968533502)}, {UINT64CONST(10370709072591134795), UINT64CONST(232346391949653603)},
{UINT64CONST(15675264887556728482), UINT64CONST(185877113559722882)}, {UINT64CONST(5161514280561562140), UINT64CONST(148701690847778306)},
{UINT64CONST(879725219414678777), UINT64CONST(237922705356445290)}, {UINT64CONST(703780175531743021), UINT64CONST(190338164285156232)},
{UINT64CONST(11631070584651125387), UINT64CONST(152270531428124985)}, {UINT64CONST(162968861732249003), UINT64CONST(243632850284999977)},
{UINT64CONST(11198421533611530172), UINT64CONST(194906280227999981)}, {UINT64CONST(5269388412147313814), UINT64CONST(155925024182399985)},
{UINT64CONST(8431021459435702103), UINT64CONST(249480038691839976)}, {UINT64CONST(3055468352806651359), UINT64CONST(199584030953471981)},
{UINT64CONST(17201769941212962380), UINT64CONST(159667224762777584)}, {UINT64CONST(16454785461715008838), UINT64CONST(255467559620444135)},
{UINT64CONST(13163828369372007071), UINT64CONST(204374047696355308)}, {UINT64CONST(17909760324981426303), UINT64CONST(163499238157084246)},
{UINT64CONST(2830174816776909822), UINT64CONST(261598781051334795)}, {UINT64CONST(2264139853421527858), UINT64CONST(209279024841067836)},
{UINT64CONST(16568707141704863579), UINT64CONST(167423219872854268)}, {UINT64CONST(4373838538276319787), UINT64CONST(267877151796566830)},
{UINT64CONST(3499070830621055830), UINT64CONST(214301721437253464)}, {UINT64CONST(6488605479238754987), UINT64CONST(171441377149802771)},
{UINT64CONST(3003071137298187333), UINT64CONST(274306203439684434)}, {UINT64CONST(6091805724580460189), UINT64CONST(219444962751747547)},
{UINT64CONST(15941491023890099121), UINT64CONST(175555970201398037)}, {UINT64CONST(10748990379256517301), UINT64CONST(280889552322236860)},
{UINT64CONST(8599192303405213841), UINT64CONST(224711641857789488)}, {UINT64CONST(14258051472207991719), UINT64CONST(179769313486231590)}
};
static const uint64 DOUBLE_POW5_SPLIT[326][2] = {
{UINT64CONST(0), UINT64CONST(72057594037927936)}, {UINT64CONST(0), UINT64CONST(90071992547409920)},
{UINT64CONST(0), UINT64CONST(112589990684262400)}, {UINT64CONST(0), UINT64CONST(140737488355328000)},
{UINT64CONST(0), UINT64CONST(87960930222080000)}, {UINT64CONST(0), UINT64CONST(109951162777600000)},
{UINT64CONST(0), UINT64CONST(137438953472000000)}, {UINT64CONST(0), UINT64CONST(85899345920000000)},
{UINT64CONST(0), UINT64CONST(107374182400000000)}, {UINT64CONST(0), UINT64CONST(134217728000000000)},
{UINT64CONST(0), UINT64CONST(83886080000000000)}, {UINT64CONST(0), UINT64CONST(104857600000000000)},
{UINT64CONST(0), UINT64CONST(131072000000000000)}, {UINT64CONST(0), UINT64CONST(81920000000000000)},
{UINT64CONST(0), UINT64CONST(102400000000000000)}, {UINT64CONST(0), UINT64CONST(128000000000000000)},
{UINT64CONST(0), UINT64CONST(80000000000000000)}, {UINT64CONST(0), UINT64CONST(100000000000000000)},
{UINT64CONST(0), UINT64CONST(125000000000000000)}, {UINT64CONST(0), UINT64CONST(78125000000000000)},
{UINT64CONST(0), UINT64CONST(97656250000000000)}, {UINT64CONST(0), UINT64CONST(122070312500000000)},
{UINT64CONST(0), UINT64CONST(76293945312500000)}, {UINT64CONST(0), UINT64CONST(95367431640625000)},
{UINT64CONST(0), UINT64CONST(119209289550781250)}, {UINT64CONST(4611686018427387904), UINT64CONST(74505805969238281)},
{UINT64CONST(10376293541461622784), UINT64CONST(93132257461547851)}, {UINT64CONST(8358680908399640576), UINT64CONST(116415321826934814)},
{UINT64CONST(612489549322387456), UINT64CONST(72759576141834259)}, {UINT64CONST(14600669991935148032), UINT64CONST(90949470177292823)},
{UINT64CONST(13639151471491547136), UINT64CONST(113686837721616029)}, {UINT64CONST(3213881284082270208), UINT64CONST(142108547152020037)},
{UINT64CONST(4314518811765112832), UINT64CONST(88817841970012523)}, {UINT64CONST(781462496279003136), UINT64CONST(111022302462515654)},
{UINT64CONST(10200200157203529728), UINT64CONST(138777878078144567)}, {UINT64CONST(13292654125893287936), UINT64CONST(86736173798840354)},
{UINT64CONST(7392445620511834112), UINT64CONST(108420217248550443)}, {UINT64CONST(4628871007212404736), UINT64CONST(135525271560688054)},
{UINT64CONST(16728102434789916672), UINT64CONST(84703294725430033)}, {UINT64CONST(7075069988205232128), UINT64CONST(105879118406787542)},
{UINT64CONST(18067209522111315968), UINT64CONST(132348898008484427)}, {UINT64CONST(8986162942105878528), UINT64CONST(82718061255302767)},
{UINT64CONST(6621017659204960256), UINT64CONST(103397576569128459)}, {UINT64CONST(3664586055578812416), UINT64CONST(129246970711410574)},
{UINT64CONST(16125424340018921472), UINT64CONST(80779356694631608)}, {UINT64CONST(1710036351314100224), UINT64CONST(100974195868289511)},
{UINT64CONST(15972603494424788992), UINT64CONST(126217744835361888)}, {UINT64CONST(9982877184015493120), UINT64CONST(78886090522101180)},
{UINT64CONST(12478596480019366400), UINT64CONST(98607613152626475)}, {UINT64CONST(10986559581596820096), UINT64CONST(123259516440783094)},
{UINT64CONST(2254913720070624656), UINT64CONST(77037197775489434)}, {UINT64CONST(12042014186943056628), UINT64CONST(96296497219361792)},
{UINT64CONST(15052517733678820785), UINT64CONST(120370621524202240)}, {UINT64CONST(9407823583549262990), UINT64CONST(75231638452626400)},
{UINT64CONST(11759779479436578738), UINT64CONST(94039548065783000)}, {UINT64CONST(14699724349295723422), UINT64CONST(117549435082228750)},
{UINT64CONST(4575641699882439235), UINT64CONST(73468396926392969)}, {UINT64CONST(10331238143280436948), UINT64CONST(91835496157991211)},
{UINT64CONST(8302361660673158281), UINT64CONST(114794370197489014)}, {UINT64CONST(1154580038986672043), UINT64CONST(143492962746861268)},
{UINT64CONST(9944984561221445835), UINT64CONST(89683101716788292)}, {UINT64CONST(12431230701526807293), UINT64CONST(112103877145985365)},
{UINT64CONST(1703980321626345405), UINT64CONST(140129846432481707)}, {UINT64CONST(17205888765512323542), UINT64CONST(87581154020301066)},
{UINT64CONST(12283988920035628619), UINT64CONST(109476442525376333)}, {UINT64CONST(1519928094762372062), UINT64CONST(136845553156720417)},
{UINT64CONST(12479170105294952299), UINT64CONST(85528470722950260)}, {UINT64CONST(15598962631618690374), UINT64CONST(106910588403687825)},
{UINT64CONST(5663645234241199255), UINT64CONST(133638235504609782)}, {UINT64CONST(17374836326682913246), UINT64CONST(83523897190381113)},
{UINT64CONST(7883487353071477846), UINT64CONST(104404871487976392)}, {UINT64CONST(9854359191339347308), UINT64CONST(130506089359970490)},
{UINT64CONST(10770660513014479971), UINT64CONST(81566305849981556)}, {UINT64CONST(13463325641268099964), UINT64CONST(101957882312476945)},
{UINT64CONST(2994098996302961243), UINT64CONST(127447352890596182)}, {UINT64CONST(15706369927971514489), UINT64CONST(79654595556622613)},
{UINT64CONST(5797904354682229399), UINT64CONST(99568244445778267)}, {UINT64CONST(2635694424925398845), UINT64CONST(124460305557222834)},
{UINT64CONST(6258995034005762182), UINT64CONST(77787690973264271)}, {UINT64CONST(3212057774079814824), UINT64CONST(97234613716580339)},
{UINT64CONST(17850130272881932242), UINT64CONST(121543267145725423)}, {UINT64CONST(18073860448192289507), UINT64CONST(75964541966078389)},
{UINT64CONST(8757267504958198172), UINT64CONST(94955677457597987)}, {UINT64CONST(6334898362770359811), UINT64CONST(118694596821997484)},
{UINT64CONST(13182683513586250689), UINT64CONST(74184123013748427)}, {UINT64CONST(11866668373555425458), UINT64CONST(92730153767185534)},
{UINT64CONST(5609963430089506015), UINT64CONST(115912692208981918)}, {UINT64CONST(17341285199088104971), UINT64CONST(72445432630613698)},
{UINT64CONST(12453234462005355406), UINT64CONST(90556790788267123)}, {UINT64CONST(10954857059079306353), UINT64CONST(113195988485333904)},
{UINT64CONST(13693571323849132942), UINT64CONST(141494985606667380)}, {UINT64CONST(17781854114260483896), UINT64CONST(88434366004167112)},
{UINT64CONST(3780573569116053255), UINT64CONST(110542957505208891)}, {UINT64CONST(114030942967678664), UINT64CONST(138178696881511114)},
{UINT64CONST(4682955357782187069), UINT64CONST(86361685550944446)}, {UINT64CONST(15077066234082509644), UINT64CONST(107952106938680557)},
{UINT64CONST(5011274737320973344), UINT64CONST(134940133673350697)}, {UINT64CONST(14661261756894078100), UINT64CONST(84337583545844185)},
{UINT64CONST(4491519140835433913), UINT64CONST(105421979432305232)}, {UINT64CONST(5614398926044292391), UINT64CONST(131777474290381540)},
{UINT64CONST(12732371365632458552), UINT64CONST(82360921431488462)}, {UINT64CONST(6692092170185797382), UINT64CONST(102951151789360578)},
{UINT64CONST(17588487249587022536), UINT64CONST(128688939736700722)}, {UINT64CONST(15604490549419276989), UINT64CONST(80430587335437951)},
{UINT64CONST(14893927168346708332), UINT64CONST(100538234169297439)}, {UINT64CONST(14005722942005997511), UINT64CONST(125672792711621799)},
{UINT64CONST(15671105866394830300), UINT64CONST(78545495444763624)}, {UINT64CONST(1142138259283986260), UINT64CONST(98181869305954531)},
{UINT64CONST(15262730879387146537), UINT64CONST(122727336632443163)}, {UINT64CONST(7233363790403272633), UINT64CONST(76704585395276977)},
{UINT64CONST(13653390756431478696), UINT64CONST(95880731744096221)}, {UINT64CONST(3231680390257184658), UINT64CONST(119850914680120277)},
{UINT64CONST(4325643253124434363), UINT64CONST(74906821675075173)}, {UINT64CONST(10018740084832930858), UINT64CONST(93633527093843966)},
{UINT64CONST(3300053069186387764), UINT64CONST(117041908867304958)}, {UINT64CONST(15897591223523656064), UINT64CONST(73151193042065598)},
{UINT64CONST(10648616992549794273), UINT64CONST(91438991302581998)}, {UINT64CONST(4087399203832467033), UINT64CONST(114298739128227498)},
{UINT64CONST(14332621041645359599), UINT64CONST(142873423910284372)}, {UINT64CONST(18181260187883125557), UINT64CONST(89295889943927732)},
{UINT64CONST(4279831161144355331), UINT64CONST(111619862429909666)}, {UINT64CONST(14573160988285219972), UINT64CONST(139524828037387082)},
{UINT64CONST(13719911636105650386), UINT64CONST(87203017523366926)}, {UINT64CONST(7926517508277287175), UINT64CONST(109003771904208658)},
{UINT64CONST(684774848491833161), UINT64CONST(136254714880260823)}, {UINT64CONST(7345513307948477581), UINT64CONST(85159196800163014)},
{UINT64CONST(18405263671790372785), UINT64CONST(106448996000203767)}, {UINT64CONST(18394893571310578077), UINT64CONST(133061245000254709)},
{UINT64CONST(13802651491282805250), UINT64CONST(83163278125159193)}, {UINT64CONST(3418256308821342851), UINT64CONST(103954097656448992)},
{UINT64CONST(4272820386026678563), UINT64CONST(129942622070561240)}, {UINT64CONST(2670512741266674102), UINT64CONST(81214138794100775)},
{UINT64CONST(17173198981865506339), UINT64CONST(101517673492625968)}, {UINT64CONST(3019754653622331308), UINT64CONST(126897091865782461)},
{UINT64CONST(4193189667727651020), UINT64CONST(79310682416114038)}, {UINT64CONST(14464859121514339583), UINT64CONST(99138353020142547)},
{UINT64CONST(13469387883465536574), UINT64CONST(123922941275178184)}, {UINT64CONST(8418367427165960359), UINT64CONST(77451838296986365)},
{UINT64CONST(15134645302384838353), UINT64CONST(96814797871232956)}, {UINT64CONST(471562554271496325), UINT64CONST(121018497339041196)},
{UINT64CONST(9518098633274461011), UINT64CONST(75636560836900747)}, {UINT64CONST(7285937273165688360), UINT64CONST(94545701046125934)},
{UINT64CONST(18330793628311886258), UINT64CONST(118182126307657417)}, {UINT64CONST(4539216990053847055), UINT64CONST(73863828942285886)},
{UINT64CONST(14897393274422084627), UINT64CONST(92329786177857357)}, {UINT64CONST(4786683537745442072), UINT64CONST(115412232722321697)},
{UINT64CONST(14520892257159371055), UINT64CONST(72132645451451060)}, {UINT64CONST(18151115321449213818), UINT64CONST(90165806814313825)},
{UINT64CONST(8853836096529353561), UINT64CONST(112707258517892282)}, {UINT64CONST(1843923083806916143), UINT64CONST(140884073147365353)},
{UINT64CONST(12681666973447792349), UINT64CONST(88052545717103345)}, {UINT64CONST(2017025661527576725), UINT64CONST(110065682146379182)},
{UINT64CONST(11744654113764246714), UINT64CONST(137582102682973977)}, {UINT64CONST(422879793461572340), UINT64CONST(85988814176858736)},
{UINT64CONST(528599741826965425), UINT64CONST(107486017721073420)}, {UINT64CONST(660749677283706782), UINT64CONST(134357522151341775)},
{UINT64CONST(7330497575943398595), UINT64CONST(83973451344588609)}, {UINT64CONST(13774807988356636147), UINT64CONST(104966814180735761)},
{UINT64CONST(3383451930163631472), UINT64CONST(131208517725919702)}, {UINT64CONST(15949715511634433382), UINT64CONST(82005323578699813)},
{UINT64CONST(6102086334260878016), UINT64CONST(102506654473374767)}, {UINT64CONST(3015921899398709616), UINT64CONST(128133318091718459)},
{UINT64CONST(18025852251620051174), UINT64CONST(80083323807324036)}, {UINT64CONST(4085571240815512351), UINT64CONST(100104154759155046)},
{UINT64CONST(14330336087874166247), UINT64CONST(125130193448943807)}, {UINT64CONST(15873989082562435760), UINT64CONST(78206370905589879)},
{UINT64CONST(15230800334775656796), UINT64CONST(97757963631987349)}, {UINT64CONST(5203442363187407284), UINT64CONST(122197454539984187)},
{UINT64CONST(946308467778435600), UINT64CONST(76373409087490117)}, {UINT64CONST(5794571603150432404), UINT64CONST(95466761359362646)},
{UINT64CONST(16466586540792816313), UINT64CONST(119333451699203307)}, {UINT64CONST(7985773578781816244), UINT64CONST(74583407312002067)},
{UINT64CONST(5370530955049882401), UINT64CONST(93229259140002584)}, {UINT64CONST(6713163693812353001), UINT64CONST(116536573925003230)},
{UINT64CONST(18030785363914884337), UINT64CONST(72835358703127018)}, {UINT64CONST(13315109668038829614), UINT64CONST(91044198378908773)},
{UINT64CONST(2808829029766373305), UINT64CONST(113805247973635967)}, {UINT64CONST(17346094342490130344), UINT64CONST(142256559967044958)},
{UINT64CONST(6229622945628943561), UINT64CONST(88910349979403099)}, {UINT64CONST(3175342663608791547), UINT64CONST(111137937474253874)},
{UINT64CONST(13192550366365765242), UINT64CONST(138922421842817342)}, {UINT64CONST(3633657960551215372), UINT64CONST(86826513651760839)},
{UINT64CONST(18377130505971182927), UINT64CONST(108533142064701048)}, {UINT64CONST(4524669058754427043), UINT64CONST(135666427580876311)},
{UINT64CONST(9745447189362598758), UINT64CONST(84791517238047694)}, {UINT64CONST(2958436949848472639), UINT64CONST(105989396547559618)},
{UINT64CONST(12921418224165366607), UINT64CONST(132486745684449522)}, {UINT64CONST(12687572408530742033), UINT64CONST(82804216052780951)},
{UINT64CONST(11247779492236039638), UINT64CONST(103505270065976189)}, {UINT64CONST(224666310012885835), UINT64CONST(129381587582470237)},
{UINT64CONST(2446259452971747599), UINT64CONST(80863492239043898)}, {UINT64CONST(12281196353069460307), UINT64CONST(101079365298804872)},
{UINT64CONST(15351495441336825384), UINT64CONST(126349206623506090)}, {UINT64CONST(14206370669262903769), UINT64CONST(78968254139691306)},
{UINT64CONST(8534591299723853903), UINT64CONST(98710317674614133)}, {UINT64CONST(15279925143082205283), UINT64CONST(123387897093267666)},
{UINT64CONST(14161639232853766206), UINT64CONST(77117435683292291)}, {UINT64CONST(13090363022639819853), UINT64CONST(96396794604115364)},
{UINT64CONST(16362953778299774816), UINT64CONST(120495993255144205)}, {UINT64CONST(12532689120651053212), UINT64CONST(75309995784465128)},
{UINT64CONST(15665861400813816515), UINT64CONST(94137494730581410)}, {UINT64CONST(10358954714162494836), UINT64CONST(117671868413226763)},
{UINT64CONST(4168503687137865320), UINT64CONST(73544917758266727)}, {UINT64CONST(598943590494943747), UINT64CONST(91931147197833409)},
{UINT64CONST(5360365506546067587), UINT64CONST(114913933997291761)}, {UINT64CONST(11312142901609972388), UINT64CONST(143642417496614701)},
{UINT64CONST(9375932322719926695), UINT64CONST(89776510935384188)}, {UINT64CONST(11719915403399908368), UINT64CONST(112220638669230235)},
{UINT64CONST(10038208235822497557), UINT64CONST(140275798336537794)}, {UINT64CONST(10885566165816448877), UINT64CONST(87672373960336121)},
{UINT64CONST(18218643725697949000), UINT64CONST(109590467450420151)}, {UINT64CONST(18161618638695048346), UINT64CONST(136988084313025189)},
{UINT64CONST(13656854658398099168), UINT64CONST(85617552695640743)}, {UINT64CONST(12459382304570236056), UINT64CONST(107021940869550929)},
{UINT64CONST(1739169825430631358), UINT64CONST(133777426086938662)}, {UINT64CONST(14922039196176308311), UINT64CONST(83610891304336663)},
{UINT64CONST(14040862976792997485), UINT64CONST(104513614130420829)}, {UINT64CONST(3716020665709083144), UINT64CONST(130642017663026037)},
{UINT64CONST(4628355925281870917), UINT64CONST(81651261039391273)}, {UINT64CONST(10397130925029726550), UINT64CONST(102064076299239091)},
{UINT64CONST(8384727637859770284), UINT64CONST(127580095374048864)}, {UINT64CONST(5240454773662356427), UINT64CONST(79737559608780540)},
{UINT64CONST(6550568467077945534), UINT64CONST(99671949510975675)}, {UINT64CONST(3576524565420044014), UINT64CONST(124589936888719594)},
{UINT64CONST(6847013871814915412), UINT64CONST(77868710555449746)}, {UINT64CONST(17782139376623420074), UINT64CONST(97335888194312182)},
{UINT64CONST(13004302183924499284), UINT64CONST(121669860242890228)}, {UINT64CONST(17351060901807587860), UINT64CONST(76043662651806392)},
{UINT64CONST(3242082053549933210), UINT64CONST(95054578314757991)}, {UINT64CONST(17887660622219580224), UINT64CONST(118818222893447488)},
{UINT64CONST(11179787888887237640), UINT64CONST(74261389308404680)}, {UINT64CONST(13974734861109047050), UINT64CONST(92826736635505850)},
{UINT64CONST(8245046539531533005), UINT64CONST(116033420794382313)}, {UINT64CONST(16682369133275677888), UINT64CONST(72520887996488945)},
{UINT64CONST(7017903361312433648), UINT64CONST(90651109995611182)}, {UINT64CONST(17995751238495317868), UINT64CONST(113313887494513977)},
{UINT64CONST(8659630992836983623), UINT64CONST(141642359368142472)}, {UINT64CONST(5412269370523114764), UINT64CONST(88526474605089045)},
{UINT64CONST(11377022731581281359), UINT64CONST(110658093256361306)}, {UINT64CONST(4997906377621825891), UINT64CONST(138322616570451633)},
{UINT64CONST(14652906532082110942), UINT64CONST(86451635356532270)}, {UINT64CONST(9092761128247862869), UINT64CONST(108064544195665338)},
{UINT64CONST(2142579373455052779), UINT64CONST(135080680244581673)}, {UINT64CONST(12868327154477877747), UINT64CONST(84425425152863545)},
{UINT64CONST(2250350887815183471), UINT64CONST(105531781441079432)}, {UINT64CONST(2812938609768979339), UINT64CONST(131914726801349290)},
{UINT64CONST(6369772649532999991), UINT64CONST(82446704250843306)}, {UINT64CONST(17185587848771025797), UINT64CONST(103058380313554132)},
{UINT64CONST(3035240737254230630), UINT64CONST(128822975391942666)}, {UINT64CONST(6508711479211282048), UINT64CONST(80514359619964166)},
{UINT64CONST(17359261385868878368), UINT64CONST(100642949524955207)}, {UINT64CONST(17087390713908710056), UINT64CONST(125803686906194009)},
{UINT64CONST(3762090168551861929), UINT64CONST(78627304316371256)}, {UINT64CONST(4702612710689827411), UINT64CONST(98284130395464070)},
{UINT64CONST(15101637925217060072), UINT64CONST(122855162994330087)}, {UINT64CONST(16356052730901744401), UINT64CONST(76784476871456304)},
{UINT64CONST(1998321839917628885), UINT64CONST(95980596089320381)}, {UINT64CONST(7109588318324424010), UINT64CONST(119975745111650476)},
{UINT64CONST(13666864735807540814), UINT64CONST(74984840694781547)}, {UINT64CONST(12471894901332038114), UINT64CONST(93731050868476934)},
{UINT64CONST(6366496589810271835), UINT64CONST(117163813585596168)}, {UINT64CONST(3979060368631419896), UINT64CONST(73227383490997605)},
{UINT64CONST(9585511479216662775), UINT64CONST(91534229363747006)}, {UINT64CONST(2758517312166052660), UINT64CONST(114417786704683758)},
{UINT64CONST(12671518677062341634), UINT64CONST(143022233380854697)}, {UINT64CONST(1002170145522881665), UINT64CONST(89388895863034186)},
{UINT64CONST(10476084718758377889), UINT64CONST(111736119828792732)}, {UINT64CONST(13095105898447972362), UINT64CONST(139670149785990915)},
{UINT64CONST(5878598177316288774), UINT64CONST(87293843616244322)}, {UINT64CONST(16571619758500136775), UINT64CONST(109117304520305402)},
{UINT64CONST(11491152661270395161), UINT64CONST(136396630650381753)}, {UINT64CONST(264441385652915120), UINT64CONST(85247894156488596)},
{UINT64CONST(330551732066143900), UINT64CONST(106559867695610745)}, {UINT64CONST(5024875683510067779), UINT64CONST(133199834619513431)},
{UINT64CONST(10058076329834874218), UINT64CONST(83249896637195894)}, {UINT64CONST(3349223375438816964), UINT64CONST(104062370796494868)},
{UINT64CONST(4186529219298521205), UINT64CONST(130077963495618585)}, {UINT64CONST(14145795808130045513), UINT64CONST(81298727184761615)},
{UINT64CONST(13070558741735168987), UINT64CONST(101623408980952019)}, {UINT64CONST(11726512408741573330), UINT64CONST(127029261226190024)},
{UINT64CONST(7329070255463483331), UINT64CONST(79393288266368765)}, {UINT64CONST(13773023837756742068), UINT64CONST(99241610332960956)},
{UINT64CONST(17216279797195927585), UINT64CONST(124052012916201195)}, {UINT64CONST(8454331864033760789), UINT64CONST(77532508072625747)},
{UINT64CONST(5956228811614813082), UINT64CONST(96915635090782184)}, {UINT64CONST(7445286014518516353), UINT64CONST(121144543863477730)},
{UINT64CONST(9264989777501460624), UINT64CONST(75715339914673581)}, {UINT64CONST(16192923240304213684), UINT64CONST(94644174893341976)},
{UINT64CONST(1794409976670715490), UINT64CONST(118305218616677471)}, {UINT64CONST(8039035263060279037), UINT64CONST(73940761635423419)},
{UINT64CONST(5437108060397960892), UINT64CONST(92425952044279274)}, {UINT64CONST(16019757112352226923), UINT64CONST(115532440055349092)},
{UINT64CONST(788976158365366019), UINT64CONST(72207775034593183)}, {UINT64CONST(14821278253238871236), UINT64CONST(90259718793241478)},
{UINT64CONST(9303225779693813237), UINT64CONST(112824648491551848)}, {UINT64CONST(11629032224617266546), UINT64CONST(141030810614439810)},
{UINT64CONST(11879831158813179495), UINT64CONST(88144256634024881)}, {UINT64CONST(1014730893234310657), UINT64CONST(110180320792531102)},
{UINT64CONST(10491785653397664129), UINT64CONST(137725400990663877)}, {UINT64CONST(8863209042587234033), UINT64CONST(86078375619164923)},
{UINT64CONST(6467325284806654637), UINT64CONST(107597969523956154)}, {UINT64CONST(17307528642863094104), UINT64CONST(134497461904945192)},
{UINT64CONST(10817205401789433815), UINT64CONST(84060913690590745)}, {UINT64CONST(18133192770664180173), UINT64CONST(105076142113238431)},
{UINT64CONST(18054804944902837312), UINT64CONST(131345177641548039)}, {UINT64CONST(18201782118205355176), UINT64CONST(82090736025967524)},
{UINT64CONST(4305483574047142354), UINT64CONST(102613420032459406)}, {UINT64CONST(14605226504413703751), UINT64CONST(128266775040574257)},
{UINT64CONST(2210737537617482988), UINT64CONST(80166734400358911)}, {UINT64CONST(16598479977304017447), UINT64CONST(100208418000448638)},
{UINT64CONST(11524727934775246001), UINT64CONST(125260522500560798)}, {UINT64CONST(2591268940807140847), UINT64CONST(78287826562850499)},
{UINT64CONST(17074144231291089770), UINT64CONST(97859783203563123)}, {UINT64CONST(16730994270686474309), UINT64CONST(122324729004453904)},
{UINT64CONST(10456871419179046443), UINT64CONST(76452955627783690)}, {UINT64CONST(3847717237119032246), UINT64CONST(95566194534729613)},
{UINT64CONST(9421332564826178211), UINT64CONST(119457743168412016)}, {UINT64CONST(5888332853016361382), UINT64CONST(74661089480257510)},
{UINT64CONST(16583788103125227536), UINT64CONST(93326361850321887)}, {UINT64CONST(16118049110479146516), UINT64CONST(116657952312902359)},
{UINT64CONST(16991309721690548428), UINT64CONST(72911220195563974)}, {UINT64CONST(12015765115258409727), UINT64CONST(91139025244454968)},
{UINT64CONST(15019706394073012159), UINT64CONST(113923781555568710)}, {UINT64CONST(9551260955736489391), UINT64CONST(142404726944460888)},
{UINT64CONST(5969538097335305869), UINT64CONST(89002954340288055)}, {UINT64CONST(2850236603241744433), UINT64CONST(111253692925360069)}
};
#endif /* RYU_D2S_FULL_TABLE_H */ | c | github | https://github.com/postgres/postgres | src/common/d2s_full_table.h |
#input: code directory that contains c/c++/java source code
#output: static code profile: classification of statements based on their operators and the data types of the variables
import os, fnmatch, sys, string, xml.dom.minidom
def Arithmetic(expr, xmldoc):
itemlist = xmldoc.getElementsByTagName(expr)
# the number of arithmetic
acount = 0
for s in itemlist:
str2 = s.toxml()
if "</name>*" in str2 or "</call>*" in str2 or "*<name>" in str2 or "*<call>" in str2:
acount = acount +1
elif "</name>/" in str2 or "</call>/" in str2 or "/<name>" in str2 or "/<call>" in str2:
acount = acount +1
elif "</name>-" in str2 or "</call>-" in str2 or "-<name>" in str2 or "-<call>" in str2:
acount = acount +1
elif "</name>+" in str2 or "</call>+" in str2 or "+<name>" in str2 or "+<call>" in str2:
acount = acount +1
elif "</name>%" in str2 or "</call>%" in str2 or "%<name>" in str2 or "%<call>" in str2:
acount = acount +1
return acount
def Condition(xmldoc):
itemlist = xmldoc.getElementsByTagName('condition')
totalc = 0
for s in itemlist:
str2 = s.toxml()
if "<expr>1</expr>" not in str2 and "<expr>0</expr>" not in str2:
totalc = totalc+1
return totalc
def Loop(xmldoc):
itemlist = xmldoc.getElementsByTagName('while')
total = 0
for s in itemlist:
str2 = s.toxml()
total = total+1
itemlist = xmldoc.getElementsByTagName('for')
for s in itemlist:
str2 = s.toxml()
total = total+1
return total
def OtherContols(xmldoc):
itemlist = xmldoc.getElementsByTagName('continue')
total = 0
for s in itemlist:
str2 = s.toxml()
total = total+1
itemlist = xmldoc.getElementsByTagName('break')
for s in itemlist:
str2 = s.toxml()
total = total+1
itemlist = xmldoc.getElementsByTagName('goto')
for s in itemlist:
str2 = s.toxml()
total = total+1
itemlist = xmldoc.getElementsByTagName('return')
for s in itemlist:
str2 = s.toxml()
total = total+1
return total
def Calls(xmldoc):
itemlist = xmldoc.getElementsByTagName('call')
total = 0
for s in itemlist:
str2 = s.toxml()
total = total+1
return total
#todo
def ProfileLOC(srcdir):
return
def ComputeFuncList(xmldoc):
funclist = []
itemlist = xmldoc.getElementsByTagName('function')
for s in itemlist:
try:
xmldoc2 = xml.dom.minidom.parseString(s.toxml())
except:
if "</type> <name>" in s.toxml():
begin = s.toxml().index("</type> <name>")+14
end = s.toxml().index("</name><parameter_list>")
name = s.toxml()[begin:end]
funclist.append(name)
continue
itemlist2 = xmldoc2.getElementsByTagName('name')
counter = 0
for i in itemlist2:
if counter == 1:
name = i.toxml()[6:len(i.toxml())-7]
funclist.append(name)
counter = counter + 1
return funclist
mapping = []
def GetNameType(string, label):
temp = string
llabel = "<"+label+">"
rlabel = "</"+label+">"
begin = temp.find(llabel)
if begin == -1:
return ""
end = temp.find(rlabel)
end = end + 7
s = temp[begin:end]
mapping.append(s)
temp = temp[end:len(temp) - end +1]
if s != "":
s = GetNameType(temp, 'decl')
mapping.append(s)
return s
def pair(xmlstr, funcname):
typename = ""
name = ""
begin = xmlstr.find("<type><name>")
if begin == -1:
begin = xmlstr.find("<type> <name>")
if begin != -1:
begin = begin + 13
else:
begin = begin + 12
end = xmlstr.find("</name>")
if begin != -1 and end != -1:
typename = xmlstr[begin:end]
namebegin = xmlstr.find("</type> <name>")
offset = 14
if namebegin == -1:
namebegin = xmlstr.find("</type><name>")
offset = 13
if namebegin != -1:
namebegin = namebegin + offset
left = xmlstr[namebegin:]
nameend = left.find("</name>")
if nameend != -1:
name = left[:nameend]
name = funcname +": "+name
if typename != "" and name != "":
#print typename
#print name
#print "--------------"
return (typename, name)
return ()
def TestStmtType(string, funcname, table):
t = ""
doc = xml.dom.minidom.parseString(string)
slist = doc.getElementsByTagName('name')
namelist = []
for s in slist:
namelist.append(s.toxml()[6:len(s.toxml())- 7])
for (typename, name) in table:
i = name.find(':')
if i != -1 and name[0:i] == funcname:
for n in namelist:
if n == name [i+2:]:
if "int" in typename or "long" in typename or "char" in typename or "Boolean" in typename or "short" in typename or "byte" in typename:
if t == "":
t = "scalar"
elif typename == "double" or typename == "float" or typename == "long double":
if t == "" or t == "scalar":
t=typename
else:
t+=":"+typename
elif typename == "list" or typename == "array" or typename == "stack" or typename == "queue":
if t == "" or t == "scalar":
t = "container"
else:
t+= ":container"
else:
# user defined name
if t == "" or t == "scalar":
t = "user"
else:
t+= ":user"
#print typename
#print t
return t
def StmtTypeBasedOnDataType(xmldoc, table, funclist):
itemlist = xmldoc.getElementsByTagName('function')
count = 0
stotal = 0
ftotal = 0
ctotal = 0
dtotal = 0
utotal = 0
for item in itemlist:
funcname = funclist[count]
try:
sxmldoc = xml.dom.minidom.parseString(item.toxml())
except:
#print len(itemlist)
# find all the condition, expr_stmt, decl_stmt via string matching
source = item.toxml()
temp = source
ilist = []
while len(temp) > 0:
cbegin = temp.find("<condition>")
cend = temp.find("</condition>")
if cbegin == -1 or cend == -1:
break
cend += 12
ilist.append(temp[cbegin:cend])
temp = temp[cend:]
temp = source
while len(temp) > 0:
cbegin = temp.find("<expr_stmt>")
cend = temp.find("</expr_stmt>")
if cbegin == -1 or cend == -1:
break
cend += 12
ilist.append(temp[cbegin:cend])
temp = temp[cend:]
temp = source
while len(temp) > 0:
cbegin = temp.find("<decl_stmt>")
cend = temp.find("</decl_stmt>")
if cbegin == -1 or cend == -1:
break
cend += 12
ilist.append(temp[cbegin:cend])
temp = temp[cend:]
for i in ilist:
t = TestStmtType(i, funcname, table)
if "scalar" in t:
stotal = stotal + 1
if "float" in t:
ftotal = ftotal + 1
if "container" in t:
ctotal = ctotal + 1
if "user" in t:
utotal = utotal + 1
if "double" in t:
dtotal = dtotal + 1
sitemlist = sxmldoc.getElementsByTagName('condition')
sitemlist2 = xmldoc.getElementsByTagName('expr_stmt')
sitemlist3 = xmldoc.getElementsByTagName('decl_stmt')
for s in sitemlist2:
sitemlist.append(s)
for s2 in sitemlist3:
sitemlist.append(s2)
for sitem in sitemlist:
stritem = sitem.toxml()
t = TestStmtType(stritem, funcname, table)
if "scalar" in t:
stotal = stotal + 1
if "float" in t:
ftotal = ftotal + 1
if "double" in t:
dtotal = dtotal + 1
if "container" in t:
ctotal = ctotal + 1
if "user" in t:
utotal = utotal + 1
count = count + 1
return (stotal, ftotal, dtotal, ctotal, utotal)
#todo handle global variables
#funcname: varname, type
def BuildASimpleSymbolTable(xmldoc, funclist):
table = []
itemlist = xmldoc.getElementsByTagName('function')
current = 0
for s in itemlist:
funcname = funclist[current]
#print s.toxml()
current = current + 1
#print funcname
try:
xmldoc2 = xml.dom.minidom.parseString(s.toxml())
except:
GetNameType(s.toxml(), 'decl')
for m in mapping:
p = pair(m, funcname)
if p != ():
table.append(p)
continue
itemlist2 = xmldoc2.getElementsByTagName('decl')
for i in itemlist2:
p = pair(i.toxml(), funcname)
if p != ():
table.append(p)
return table
#output statement classification regarding computation
def ProfileComputation(arithmetic, cond, loop, othercontrols, calls):
print "\nStatement classification based on computation"
print str(arithmetic)+" - the number of arithmetic"
print str(cond)+" - the number of conditions (including loop conditions)"
print str(loop)+" - the number of loops"
print str(othercontrols)+ " - the number of goto, break, continue, return"
print str(calls)+ " - the number of calls"
return
#output statement classification regarding datatype
def ProfileDataType(profile):
print "\nStatement classification based on data types"
print str(profile[0]) + " - the number of statements with only scalar (int, long, char, Boolean, short) data type"
print str(profile[1]) + " - the number of statements with float point - single precision"
print str(profile[2]) + " - the number of statements with double"
print str(profile[3]) + " - the number of statements with containers (stack, array, list, queue)"
print str(profile[4]) + " - the number of statements with user defined data types"
return
def GetFiles(srcdir):
filelist = []
files = os.walk(srcdir)
for paths, dirs, fname in files:
for filename in fname:
d = srcdir+"\\"+filename
if os.path.exists(d):
if filename[len(filename)-3:len(filename)] == "cpp" or filename[len(filename)-1:len(filename)] == "c" or filename[len(filename)-4:len(filename)] == ".java" or filename[len(filename)-3:len(filename)] == "cxx":
if (srcdir, filename) not in filelist:
filelist.append((srcdir, filename))
if str(paths) != str(srcdir):
ftemp = GetFiles(paths)
for (d, f) in ftemp:
if (d, f) not in filelist:
filelist.append((d, f))
return filelist
def StaticCodeProfiling(srcdir):
filelist = GetFiles(srcdir)
for (d, f) in filelist:
srcml = ".\src2srcml\src2srcml.exe " + d+"\\"+ f + " -o " +f+".xml"
os.system(srcml)
print "\n####################################"
print "\n Profiling: " + f
xmldoc = xml.dom.minidom.parse(f+".xml")
#all arithmetics
totala = Arithmetic('expr', xmldoc)
#arithmetics in indices computation
indexa = Arithmetic('index', xmldoc)
a = totala - indexa
#all conditions (including loop conditions)
c = Condition(xmldoc)
#all while/for loops
l = Loop(xmldoc)
#other controls: goto, break, continue, return
otherc = OtherContols(xmldoc)
#calls
calls = Calls(xmldoc)
#TODO: profileLOC
ProfileComputation(a, c, l, otherc, calls)
funclist = ComputeFuncList(xmldoc)
table = BuildASimpleSymbolTable(xmldoc, funclist)
#scalar: integer, boolean, char; float point: double, single; containers: list, queue, stack, other user defined data structure
profile = StmtTypeBasedOnDataType(xmldoc, table, funclist)
ProfileDataType(profile)
StaticCodeProfiling(sys.argv[1]) | unknown | codeparrot/codeparrot-clean | ||
from django import template
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db import models, transaction
from django.forms.models import modelform_factory
from django.http import Http404, HttpResponse
from django.utils.encoding import force_unicode, smart_unicode
from django.utils.html import escape, conditional_escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from xadmin.plugins.ajax import JsonErrorDict
from xadmin.sites import site
from xadmin.util import lookup_field, display_for_field, label_for_field, unquote, boolean_icon
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ListAdminView
from xadmin.views.base import csrf_protect_m, filter_hook
from xadmin.views.edit import ModelFormAdminUtil
from xadmin.views.list import EMPTY_CHANGELIST_VALUE
from xadmin.layout import FormHelper
class EditablePlugin(BaseAdminPlugin):
list_editable = []
def __init__(self, admin_view):
super(EditablePlugin, self).__init__(admin_view)
self.editable_need_fields = {}
def init_request(self, *args, **kwargs):
active = bool(self.request.method == 'GET' and self.admin_view.has_change_permission() and self.list_editable)
if active:
self.model_form = self.get_model_view(ModelFormAdminUtil, self.model).form_obj
return active
def result_item(self, item, obj, field_name, row):
if self.list_editable and item.field and item.field.editable and (field_name in self.list_editable):
pk = getattr(obj, obj._meta.pk.attname)
field_label = label_for_field(field_name, obj,
model_admin=self.admin_view,
return_attr=False
)
item.wraps.insert(0, '<span class="editable-field">%s</span>')
item.btns.append((
'<a class="editable-handler" title="%s" data-editable-field="%s" data-editable-loadurl="%s">' +
'<i class="fa fa-edit"></i></a>') %
(_(u"Enter %s") % field_label, field_name, self.admin_view.model_admin_url('patch', pk) + '?fields=' + field_name))
if field_name not in self.editable_need_fields:
self.editable_need_fields[field_name] = item.field
return item
# Media
def get_media(self, media):
if self.editable_need_fields:
media = media + self.model_form.media + \
self.vendor(
'xadmin.plugin.editable.js', 'xadmin.widget.editable.css')
return media
class EditPatchView(ModelFormAdminView, ListAdminView):
def init_request(self, object_id, *args, **kwargs):
self.org_obj = self.get_object(unquote(object_id))
# For list view get new field display html
self.pk_attname = self.opts.pk.attname
if not self.has_change_permission(self.org_obj):
raise PermissionDenied
if self.org_obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') %
{'name': force_unicode(self.opts.verbose_name), 'key': escape(object_id)})
def get_new_field_html(self, f):
result = self.result_item(self.org_obj, f, {'is_display_first':
False, 'object': self.org_obj})
return mark_safe(result.text) if result.allow_tags else conditional_escape(result.text)
def _get_new_field_html(self, field_name):
try:
f, attr, value = lookup_field(field_name, self.org_obj, self)
except (AttributeError, ObjectDoesNotExist):
return EMPTY_CHANGELIST_VALUE
else:
allow_tags = False
if f is None:
allow_tags = getattr(attr, 'allow_tags', False)
boolean = getattr(attr, 'boolean', False)
if boolean:
allow_tags = True
text = boolean_icon(value)
else:
text = smart_unicode(value)
else:
if isinstance(f.rel, models.ManyToOneRel):
field_val = getattr(self.org_obj, f.name)
if field_val is None:
text = EMPTY_CHANGELIST_VALUE
else:
text = field_val
else:
text = display_for_field(value, f)
return mark_safe(text) if allow_tags else conditional_escape(text)
@filter_hook
def get(self, request, object_id):
model_fields = [f.name for f in self.opts.fields]
fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
defaults = {
"form": self.form,
"fields": fields,
"formfield_callback": self.formfield_for_dbfield,
}
form_class = modelform_factory(self.model, **defaults)
form = form_class(instance=self.org_obj)
helper = FormHelper()
helper.form_tag = False
helper.include_media = False
form.helper = helper
s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
'<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
t = template.Template(s)
c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})
return HttpResponse(t.render(c))
@filter_hook
@csrf_protect_m
@transaction.atomic
def post(self, request, object_id):
model_fields = [f.name for f in self.opts.fields]
fields = [f for f in request.POST.keys() if f in model_fields]
defaults = {
"form": self.form,
"fields": fields,
"formfield_callback": self.formfield_for_dbfield,
}
form_class = modelform_factory(self.model, **defaults)
form = form_class(
instance=self.org_obj, data=request.POST, files=request.FILES)
result = {}
if form.is_valid():
form.save(commit=True)
result['result'] = 'success'
result['new_data'] = form.cleaned_data
result['new_html'] = dict(
[(f, self.get_new_field_html(f)) for f in fields])
else:
result['result'] = 'error'
result['errors'] = JsonErrorDict(form.errors, form).as_json()
return self.render_response(result)
site.register_plugin(EditablePlugin, ListAdminView)
site.register_modelview(r'^(.+)/patch/$', EditPatchView, name='%s_%s_patch') | unknown | codeparrot/codeparrot-clean | ||
import unittest
import time
import threading
from pywin32_testutil import str2bytes # py3k-friendly helper
import win32pipe
import win32file
import win32event
import pywintypes
import winerror
import win32con
class PipeTests(unittest.TestCase):
pipename = "\\\\.\\pipe\\python_test_pipe"
def _serverThread(self, pipe_handle, event, wait_time):
# just do one connection and terminate.
hr = win32pipe.ConnectNamedPipe(pipe_handle)
self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,))
hr, got = win32file.ReadFile(pipe_handle, 100)
self.failUnlessEqual(got, str2bytes("foo\0bar"))
time.sleep(wait_time)
win32file.WriteFile(pipe_handle, str2bytes("bar\0foo"))
pipe_handle.Close()
event.set()
def startPipeServer(self, event, wait_time = 0):
openMode = win32pipe.PIPE_ACCESS_DUPLEX
pipeMode = win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.SetSecurityDescriptorDacl ( 1, None, 0 )
pipe_handle = win32pipe.CreateNamedPipe(self.pipename,
openMode,
pipeMode,
win32pipe.PIPE_UNLIMITED_INSTANCES,
0,
0,
2000,
sa)
threading.Thread(target=self._serverThread, args=(pipe_handle, event, wait_time)).start()
def testCallNamedPipe(self):
event = threading.Event()
self.startPipeServer(event)
got = win32pipe.CallNamedPipe(self.pipename,str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeBlocking(self):
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeBlockingBuffer(self):
# Like testTransactNamedPipeBlocking, but a pre-allocated buffer is
# passed (not really that useful, but it exercises the code path)
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeAsync(self):
event = threading.Event()
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
self.startPipeServer(event, 0.5)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, overlapped)
self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING)
nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True)
got = buffer[:nbytes]
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
if __name__ == '__main__':
unittest.main() | unknown | codeparrot/codeparrot-clean | ||
declare module '*.css' {
const content: string
export default content
} | typescript | github | https://github.com/tailwindlabs/tailwindcss | packages/@tailwindcss-browser/src/types.d.ts |
import { type RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export default flatRoutes() satisfies RouteConfig; | typescript | github | https://github.com/remix-run/react-router | integration/helpers/cloudflare-dev-proxy-template/app/routes.ts |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build wasip1 || js
package net
import "os/exec"
func installTestHooks() {}
func uninstallTestHooks() {}
func forceCloseSockets() {}
func addCmdInheritedHandle(cmd *exec.Cmd, fd uintptr) {} | go | github | https://github.com/golang/go | src/net/main_wasm_test.go |
import chainer
from chainercv.links import Conv2DBNActiv
from chainercv.links.model.yolo.yolo_v2 import _leaky_relu
from chainercv.links.model.yolo.yolo_v2 import _maxpool
from chainercv.links.model.yolo import YOLOv2Base
class DarknetExtractor(chainer.ChainList):
"""A Darknet based feature extractor for YOLOv2Tiny.
This is a feature extractor for
:class:`~chainercv.links.model.yolo.YOLOv2Tiny`
"""
insize = 416
grid = 13
def __init__(self):
super(DarknetExtractor, self).__init__()
# Darknet
for k in range(7):
self.append(Conv2DBNActiv(16 << k, 3, pad=1, activ=_leaky_relu))
# additional link
self.append(Conv2DBNActiv(1024, 3, pad=1, activ=_leaky_relu))
def forward(self, x):
"""Compute a feature map from a batch of images.
Args:
x (ndarray): An array holding a batch of images.
The images should be resized to :math:`416\\times 416`.
Returns:
Variable:
"""
h = x
for i, link in enumerate(self):
h = link(h)
if i < 5:
h = _maxpool(h, 2)
elif i == 5:
h = _maxpool(h, 2, stride=1)
return h
class YOLOv2Tiny(YOLOv2Base):
"""YOLOv2 tiny.
This is a model of YOLOv2 tiny a.k.a. Tiny YOLO.
This model uses :class:`~chainercv.links.model.yolo.DarknetExtractor` as
its feature extractor.
Args:
n_fg_class (int): The number of classes excluding the background.
pretrained_model (string): The weight file to be loaded.
This can take :obj:`'voc0712'`, `filepath` or :obj:`None`.
The default value is :obj:`None`.
* :obj:`'voc0712'`: Load weights trained on trainval split of \
PASCAL VOC 2007 and 2012. \
The weight file is downloaded and cached automatically. \
:obj:`n_fg_class` must be :obj:`20` or :obj:`None`. \
These weights were converted from the darknet model \
provided by `the original implementation \
<https://pjreddie.com/darknet/yolov2/>`_. \
The conversion code is \
`chainercv/examples/yolo/darknet2npz.py`.
* `filepath`: A path of npz file. In this case, :obj:`n_fg_class` \
must be specified properly.
* :obj:`None`: Do not load weights.
"""
_extractor = DarknetExtractor
_models = {
'voc0712': {
'param': {'n_fg_class': 20},
'url': 'https://chainercv-models.preferred.jp/'
'yolo_v2_tiny_voc0712_converted_2018_10_19.npz',
'cv2': True
},
}
_anchors = (
(1.19, 1.08),
(4.41, 3.42),
(11.38, 6.63),
(5.11, 9.42),
(10.52, 16.62)) | unknown | codeparrot/codeparrot-clean | ||
import unittest
from test import support
class Empty:
def __repr__(self):
return '<Empty>'
class Cmp:
def __init__(self,arg):
self.arg = arg
def __repr__(self):
return '<Cmp %s>' % self.arg
def __eq__(self, other):
return self.arg == other
class Anything:
def __eq__(self, other):
return True
def __ne__(self, other):
return False
class ComparisonTest(unittest.TestCase):
set1 = [2, 2.0, 2, 2+0j, Cmp(2.0)]
set2 = [[1], (3,), None, Empty()]
candidates = set1 + set2
def test_comparisons(self):
for a in self.candidates:
for b in self.candidates:
if ((a in self.set1) and (b in self.set1)) or a is b:
self.assertEqual(a, b)
else:
self.assertNotEqual(a, b)
def test_id_comparisons(self):
# Ensure default comparison compares id() of args
L = []
for i in range(10):
L.insert(len(L)//2, Empty())
for a in L:
for b in L:
self.assertEqual(a == b, id(a) == id(b),
'a=%r, b=%r' % (a, b))
def test_ne_defaults_to_not_eq(self):
a = Cmp(1)
b = Cmp(1)
self.assertTrue(a == b)
self.assertFalse(a != b)
def test_issue_1393(self):
x = lambda: None
self.assertEqual(x, Anything())
self.assertEqual(Anything(), x)
y = object()
self.assertEqual(y, Anything())
self.assertEqual(Anything(), y)
def test_main():
support.run_unittest(ComparisonTest)
if __name__ == '__main__':
test_main() | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
# This code has been adapted from PyBrain. See http://pybrain.org.
#
# Copyright (c) 2009, PyBrain-Developers
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of PyBrain nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import
import scipy
import scipy.linalg
from .base import Minimizer
class Xnes(Minimizer):
# TODO: document class
def __init__(self, wrt, f, args=None):
# TODO: document method
super(Xnes, self).__init__(wrt, args=args)
self._f = f
# Set some default values.
dim = self.wrt.shape[0]
log_dim = scipy.log(dim)
self.step_rate = 0.6 * (3 + log_dim) / dim / scipy.sqrt(dim)
self.batch_size = 4 + int(scipy.floor(3 * log_dim))
def set_from_info(self, info):
raise NotImplemented('nobody has found the time to implement this yet')
def extended_info(self, **kwargs):
raise NotImplemented('nobody has found the time to implement this yet')
def f(self, x, *args, **kwargs):
return -self._f(x, *args, **kwargs)
def __iter__(self):
dim = self.wrt.shape[0]
I = scipy.eye(dim)
# Square root of covariance matrix.
A = scipy.eye(dim)
center = self.wrt.copy()
n_evals = 0
best_wrt = None
best_x = float('-inf')
for i, (args, kwargs) in enumerate(self.args):
# Draw samples, evaluate and update best solution if a better one
# was found.
samples = scipy.random.standard_normal((self.batch_size, dim))
samples = scipy.dot(samples, A) + center
fitnesses = [self.f(samples[j], *args, **kwargs)
for j in range(samples.shape[0])]
fitnesses = scipy.array(fitnesses).flatten()
if fitnesses.max() > best_x:
best_loss = fitnesses.max()
self.wrt[:] = samples[fitnesses.argmax()]
# Update center and variances.
utilities = self.compute_utilities(fitnesses)
center += scipy.dot(scipy.dot(utilities, samples), A)
# TODO: vectorize this
cov_gradient = sum([u * (scipy.outer(s, s) - I)
for (s, u) in zip(samples, utilities)])
update = scipy.linalg.expm2(A * cov_gradient * self.step_rate * 0.5)
A[:] = scipy.dot(A, update)
yield dict(loss=-best_x, n_iter=i)
def compute_utilities(self, fitnesses):
n_fitnesses = fitnesses.shape[0]
ranks = scipy.zeros_like(fitnesses)
l = sorted(enumerate(fitnesses), key=lambda x: x[1])
for i, (j, _) in enumerate(l):
ranks[j] = i
# smooth reshaping
# If we do not cast to float64 here explicitly, scipy will at random
# points crash with a weird AttributeError.
utilities = -scipy.log((n_fitnesses - ranks).astype('float64'))
utilities += scipy.log(n_fitnesses / 2. + 1.0)
utilities = scipy.clip(utilities, 0, float('inf'))
utilities /= utilities.sum() # make the utilities sum to 1
utilities -= 1. / n_fitnesses # baseline
return utilities | unknown | codeparrot/codeparrot-clean | ||
#Licensed to the Apache Software Foundation (ASF) under one
#or more contributor license agreements. See the NOTICE file
#distributed with this work for additional information
#regarding copyright ownership. The ASF licenses this file
#to you under the Apache License, Version 2.0 (the
#"License"); you may not use this file except in compliance
#with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
# Various socket server and helper classes.
#
#
import os, sys, socket, threading, pprint, re, xmlrpclib, time
from select import select
from SocketServer import ThreadingMixIn, ForkingMixIn
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from random import Random
from urlparse import urlparse
Fault = xmlrpclib.Fault
from hodlib.Common.util import local_fqdn
from hodlib.Common.logger import hodDummyLogger
class hodHTTPHandler(BaseHTTPRequestHandler):
port = -1
def __init__(self, request, client_address, server, registerService):
self.registerService = registerService
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def log_message(self, *args):
"""Forget logging for now."""
pass
def do_GET(self):
self.fullUrl = "http://%s:%s%s" % (self.server.server_address[0],
self.server.server_address[1],
self.path)
parsedUrl = urlparse(self.fullUrl)
self.writeHeaders()
self.writeData(parsedUrl)
def w(self, string):
self.wfile.write("%s\n" % string)
def writeHeaders(self):
self.send_response(200, 'OK')
self.send_header('Content-type', 'text/html')
self.end_headers()
def sendWrongPage(self, userJob):
self.w('<font class="alert">')
if userJob == False:
self.w('invalid URL specified')
elif re.match("^\d+$", userJob):
self.w('invalid URL specified, job <b>%s</b> does not exist' % userJob)
elif re.match("^\w+$", userJob):
self.w('invalid URL specified, user <b>%s</b> does not exist' % userJob)
self.w('</font>')
def getServiceHosts(self, serviceInfo):
hostInfo = { 'long' : {}, 'short' : {} }
for user in serviceInfo:
for job in serviceInfo[user]:
for host in serviceInfo[user][job]:
for serviceItem in serviceInfo[user][job][host]:
serviceName = serviceItem.keys()
serviceName = serviceName[0]
if isinstance(serviceItem[serviceName], str):
hostInfo['short'][self.getJobKey(user, job, host)] = True
hostInfo['long'][self.getJobKey(user, job, host)] = True
return hostInfo
def getJobInfo(self, job, serviceInfo):
jobInfo = {}
for user in serviceInfo.keys():
for someJob in serviceInfo[user].keys():
if job == someJob:
jobInfo[user] = { job : serviceInfo[user][job] }
return jobInfo
def getJobKey(self, user, job, host):
return "%s-%s-%s" % (user, job, host)
def writeData(self, parsedUrl):
options = parsedUrl[4]
serviceInfo = self.server.service.getServiceInfo()
users = serviceInfo.keys()
users.sort()
self.w("<html>")
self.w("<body>")
self.w("<head>")
self.writeCSS()
self.w("</head>")
self.w('<font class="header2">HOD Service Registry Information</font>')
if serviceInfo == {}:
self.w('<br><br><font class="header"> No HOD clusters configured.</font>')
else:
if parsedUrl[2] == '/':
self.w(' <table class="main">')
count = 0
for user in users:
self.writeUserData(user, options, serviceInfo, count)
count = count + 1
elif parsedUrl[2][1:] in serviceInfo:
self.w(' <table class="main">')
self.writeUserData(parsedUrl[2][1:], options, serviceInfo, 0)
elif re.match("^\d+$", parsedUrl[2][1:]):
jobInfo = self.getJobInfo(parsedUrl[2][1:], serviceInfo)
if jobInfo.keys():
self.w(' <table class="main">')
for user in jobInfo.keys():
self.writeUserData(user, options, jobInfo, 0)
else:
self.sendWrongPage(parsedUrl[2][1:])
self.w(' <table class="main">')
count = 0
for user in users:
self.writeUserData(user, options, serviceInfo, count)
count = count + 1
elif re.match("^\w+$", parsedUrl[2][1:]):
self.sendWrongPage(parsedUrl[2][1:])
self.w(' <table class="main">')
count = 0
for user in users:
self.writeUserData(user, options, serviceInfo, count)
count = count + 1
else:
self.sendWrongPage(False)
self.w(' <table class="main">')
count = 0
for user in users:
self.writeUserData(user, options, serviceInfo, count)
count = count + 1
self.w('</table>')
self.w("</pre>")
self.w("</body>")
self.w("</html>")
def writeCSS(self):
self.w('<style type="text/css">')
self.w('table.main { border: 0px; padding: 1; background-color: #E1ECE0; width: 70%; margin: 10; }')
self.w('table.sub1 { background-color: #F1F1F1; padding: 0; }')
self.w('table.sub2 { background-color: #FFFFFF; padding: 0; }')
self.w('table.sub3 { border: 1px solid #EEEEEE; background-color: #FFFFFF; padding: 0; }')
self.w('td.header { border-bottom: 1px solid #CCCCCC; padding: 2;}')
self.w('td.service1 { border: 0px; background-color: #FFFFFF; padding: 2; width: 10%}')
self.w('td.service2 { border: 0px; background-color: #FFFFFF; padding: 2; width: 90%}')
self.w('td { vertical-align: top; padding: 0; }')
self.w('td.noborder { border-style: none; border-collapse: collapse; }')
self.w('tr.colored { background-color: #F1F1F1; }')
self.w('font { font-family: Helvetica, Arial, sans-serif; font-size: 10pt; color: #666666; }')
self.w('font.header { font-family: Helvetica, Arial, sans-serif; font-size: 10pt; color: #333333; font-style: bold }')
self.w('font.header2 { font-family: Helvetica, Arial, sans-serif; font-size: 16pt; color: #333333; }')
self.w('font.sml { font-family: Helvetica, Arial, sans-serif; font-size: 8pt; color: #666666; }')
self.w('font.alert { font-family: Helvetica, Arial, sans-serif; font-size: 9pt; color: #FF7A22; }')
self.w('a { font-family: Helvetica, Arial, sans-serif; text-decoration:none; font-size: 10pt; color: #111111; }')
self.w('a:visited { font-family: Helvetica, Arial, sans-serif; color:#2D4628; text-decoration:none; font-size: 10pt; }')
self.w('a:hover { font-family: Helvetica, Arial, sans-serif; color:#00A033; text-decoration:none; font-size: 10pt; }')
self.w('a.small { font-family: Helvetica, Arial, sans-serif; text-decoration:none; font-size: 8pt }')
self.w('a.small:hover { color:#822499; text-decoration:none; font-size: 8pt }')
self.w("</style>")
def writeUserData(self, user, options, serviceInfo, count):
hostInfo = self.getServiceHosts(serviceInfo)
hostKey = 'short'
if options == 'display=long':
hostKey = 'long'
if count == 0:
self.w('<tr>')
self.w('<td class="header" colspan="2">')
self.w('<font class="header">Active Users</font>')
self.w('</td>')
self.w('</tr>')
self.w('<tr>')
self.w('<td><font>%s</font></td>' % user)
self.w('<td>')
jobIDs = serviceInfo[user].keys()
jobIDs.sort()
for jobID in jobIDs:
self.w('<table class="sub1" width="100%">')
if count == 0:
self.w('<tr>')
self.w('<td class="header" colspan="2">')
self.w('<font class="header">PBS Job Identifiers</font>')
self.w('</td>')
self.w('</tr>')
self.w('<tr>')
self.w('<td><font>%s</font></td>' % jobID)
self.w('<td>')
hosts = serviceInfo[user][jobID].keys()
hosts.sort()
for host in hosts:
if hostInfo[hostKey].has_key(self.getJobKey(user, jobID, host)):
self.w('<table class="sub2" width="100%">')
if count == 0:
self.w('<tr>')
self.w('<td class="header" colspan="2">')
self.w('<font class="header">Hosts Running Services</font>')
self.w('</td>')
self.w('</tr>')
self.w('<tr>')
self.w('<td><font>%s</font></td>' % host)
self.w('<td>')
self.w('<table class="sub3" width="100%">')
self.w('<tr>')
self.w('<td colspan="2">')
self.w('<font class="header">Service Information</font>')
self.w('</td>')
self.w('</tr>')
for serviceItem in serviceInfo[user][jobID][host]:
serviceName = serviceItem.keys()
serviceName = serviceName[0]
if isinstance(serviceItem[serviceName], dict) and \
options == 'display=long':
self.w('<tr class="colored">')
self.w('<td><font>%s</font></td>' % serviceName)
self.w('<td>')
self.w('<table width="100%">')
for key in serviceItem[serviceName]:
self.w('<tr>')
self.w('<td class="service1"><font>%s</font></td>' % key)
self.w('<td class="service2"><font>%s</font></td>' % serviceItem[serviceName][key])
self.w('</tr>')
self.w('</table>')
self.w('</td>')
self.w('</tr>')
elif isinstance(serviceItem[serviceName], str):
self.w('<tr class="colored">')
self.w('<td><font class="service1">%s</font></td>' % serviceName)
self.w('<td>')
(host, port) = serviceItem[serviceName].split(':')
hostnameInfo = socket.gethostbyname_ex(host)
if serviceName.startswith('mapred'):
self.w('<a href="http://%s:%s">Hadoop Job Tracker</a>' % (hostnameInfo[0], port))
elif serviceName.startswith('hdfs'):
self.w('<a href="http://%s:%s">HDFS Name Node</a> ' % (hostnameInfo[0], port))
else:
self.w('<font class="service2">%s</font>' % serviceItem[serviceName])
self.w('</td>')
self.w('</tr>')
self.w('</table>')
self.w('</td>')
self.w('</tr>')
self.w('</table>')
count = count + 1
self.w('</td>')
self.w('</tr>')
self.w('</table>')
count = count + 1
self.w('</td>')
self.w('</tr>')
# self.w("<pre>")
# self.w(pprint.pformat(serviceInfo))
# self.w("</pre>")
class baseSocketServer:
def __init__(self, host, ports):
self.host = host
self.ports = ports
self.__stopForever = threading.Event()
self.__stopForever.clear()
self.__run = threading.Event()
self.__run.set()
self.server_address = ()
self.mThread = None
def server_bind(self):
"""server_bind() method binds to a random range of ports."""
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(self.ports) > 1:
randomPort = Random(os.getpid())
portSequence = range(self.ports[0], self.ports[1])
maxTryCount = abs(self.ports[0] - self.ports[1])
tryCount = 0
while True:
somePort = randomPort.choice(portSequence)
self.server_address = (self.host, somePort)
try:
self.socket.bind(self.server_address)
except socket.gaierror, errData:
raise socket.gaierror, errData
except:
tryCount = tryCount + 1
if tryCount > maxTryCount:
bindError = "bind failure for port range %s:%d" % (
self.ports)
raise socket.error, bindError
else:
break
else:
self.server_address = (self.host, int(self.ports[0]))
self.socket.bind(self.server_address)
if self.host == '':
self.server_address = (local_fqdn(), self.server_address[1])
def _serve_forever(self):
"""Replacement for serve_forever loop.
All baseSocketServers run within a master thread; that thread
imitates serve_forever, but checks an event (self.__stopForever)
before processing new connections.
"""
while not self.__stopForever.isSet():
(rlist, wlist, xlist) = select([self.socket], [], [],
1)
if (len(rlist) > 0 and self.socket == rlist[0]):
self.handle_request()
while not self.__run.isSet():
if self.__stopForever.isSet():
break
time.sleep(1)
self.server_close()
return True
def serve_forever(self):
"""Handle requests until stopForever event flag indicates stop."""
self.mThread = threading.Thread(name="baseSocketServer",
target=self._serve_forever)
self.mThread.start()
return self.mThread
def pause(self):
"""Temporarily stop servicing requests."""
self.__run.clear()
def cont(self):
"""Resume servicing requests."""
self.__run.set()
def stop(self):
"""Set the stopForever flag to tell serve_forever() to exit."""
self.__stopForever.set()
if self.mThread: self.mThread.join()
return True
def is_alive(self):
if self.mThread != None:
return self.mThread.isAlive()
else:
return False
class threadedHTTPServer(baseSocketServer, ThreadingMixIn, HTTPServer):
def __init__(self, host, ports):
baseSocketServer.__init__(self, host, ports)
HTTPServer.__init__(self, self.server_address, SimpleHTTPRequestHandler)
class forkingHTTPServer(baseSocketServer, ForkingMixIn, HTTPServer):
def __init__(self, host, ports):
baseSocketServer.__init__(self, host, ports)
HTTPServer.__init__(self, self.server_address, SimpleHTTPRequestHandler)
class hodHTTPServer(baseSocketServer, ThreadingMixIn, HTTPServer):
service = None
def __init__(self, host, ports, serviceobj = None):
self.service = serviceobj
baseSocketServer.__init__(self, host, ports)
HTTPServer.__init__(self, self.server_address, hodHTTPHandler)
def finish_request(self, request, client_address):
self.RequestHandlerClass(request, client_address, self, self.service)
class hodXMLRPCServer(baseSocketServer, ThreadingMixIn, SimpleXMLRPCServer):
def __init__(self, host, ports,
requestHandler=SimpleXMLRPCRequestHandler,
logRequests=False, allow_none=False, encoding=None):
baseSocketServer.__init__(self, host, ports)
SimpleXMLRPCServer.__init__(self, self.server_address, requestHandler,
logRequests)
self.register_function(self.stop, 'stop')
try:
from twisted.web import server, xmlrpc
from twisted.internet import reactor, defer
from twisted.internet.threads import deferToThread
from twisted.python import log
class twistedXMLRPC(xmlrpc.XMLRPC):
def __init__(self, logger):
xmlrpc.XMLRPC.__init__(self)
self.__XRMethods = {}
self.__numRequests = 0
self.__logger = logger
self.__pause = False
def render(self, request):
request.content.seek(0, 0)
args, functionPath = xmlrpclib.loads(request.content.read())
try:
function = self._getFunction(functionPath)
except Fault, f:
self._cbRender(f, request)
else:
request.setHeader("content-type", "text/xml")
defer.maybeDeferred(function, *args).addErrback(
self._ebRender).addCallback(self._cbRender, request)
return server.NOT_DONE_YET
def _cbRender(self, result, request):
if isinstance(result, xmlrpc.Handler):
result = result.result
if not isinstance(result, Fault):
result = (result,)
try:
s = xmlrpclib.dumps(result, methodresponse=1)
except:
f = Fault(self.FAILURE, "can't serialize output")
s = xmlrpclib.dumps(f, methodresponse=1)
request.setHeader("content-length", str(len(s)))
request.write(s)
request.finish()
def _ebRender(self, failure):
if isinstance(failure.value, Fault):
return failure.value
log.err(failure)
return Fault(self.FAILURE, "error")
def _getFunction(self, methodName):
while self.__pause:
time.sleep(1)
self.__numRequests = self.__numRequests + 1
function = None
try:
def defer_function(*args):
return deferToThread(self.__XRMethods[methodName],
*args)
function = defer_function
self.__logger.info(
"[%s] processing defered XML-RPC call to: %s ..." %
(self.__numRequests, methodName))
except KeyError:
self.__logger.warn(
"[%s] fault %s on XML-RPC call to %s, method not found." % (
self.__numRequests, self.NOT_FOUND, methodName))
raise xmlrpc.NoSuchFunction(self.NOT_FOUND,
"method %s not found" % methodName)
return function
def register_function(self, functionRef, methodName):
self.__XRMethods[methodName] = functionRef
def list_methods(self):
return self.__XRMethods.keys()
def num_requests(self):
return self.__numRequests
def pause(self):
self.__pause = True
def cont(self):
self.__pause = False
class twistedXMLRPCServer:
def __init__(self, host, ports, logger=None, threadPoolSize=100):
self.__host = host
self.__ports = ports
if logger == None:
logger = hodDummyLogger()
self.__logger = logger
self.server_address = ['', '']
reactor.suggestThreadPoolSize(threadPoolSize)
self.__stopForever = threading.Event()
self.__stopForever.clear()
self.__mThread = None
self.__xmlrpc = twistedXMLRPC(self.__logger)
def _serve_forever(self):
if len(self.__ports) > 1:
randomPort = Random(os.getpid())
portSequence = range(self.__ports[0], self.__ports[1])
maxTryCount = abs(self.__ports[0] - self.__ports[1])
tryCount = 0
while True:
somePort = randomPort.choice(portSequence)
self.server_address = (self.__host, int(somePort))
if self.__host == '':
self.server_address = (local_fqdn(), self.server_address[1])
try:
reactor.listenTCP(int(somePort), server.Site(
self.__xmlrpc), interface=self.__host)
reactor.run(installSignalHandlers=0)
except:
self.__logger.debug("Failed to bind to: %s:%s." % (
self.__host, somePort))
tryCount = tryCount + 1
if tryCount > maxTryCount:
self.__logger.warn("Failed to bind to: %s:%s" % (
self.__host, self.__ports))
sys.exit(1)
else:
break
else:
try:
self.server_address = (self.__host, int(self.__ports[0]))
if self.__host == '':
self.server_address = (local_fqdn(), self.server_address[1])
reactor.listenTCP(int(self.__ports[0]), server.Site(self.__xmlrpc),
interface=self.__host)
reactor.run(installSignalHandlers=0)
except:
self.__logger.warn("Failed to bind to: %s:%s."% (
self.__host, self.__ports[0]))
sys.exit(1)
def serve_forever(self):
"""Handle requests until stopForever event flag indicates stop."""
self.__mThread = threading.Thread(name="XRServer",
target=self._serve_forever)
self.__mThread.start()
if not self.__mThread.isAlive():
raise Exception("Twisted XMLRPC server thread dead.")
def register_function(self, functionRef, methodName):
self.__xmlrpc.register_function(functionRef, methodName)
def register_introspection_functions(self):
pass
def register_instance(self, instance):
for method in dir(instance):
if not method.startswith('_'):
self.register_function(getattr(instance, method), method)
def pause(self):
self.__xmlrpc.pause()
def cont(self):
self.__xmlrpc.cont()
def stop(self):
def stop_thread():
time.sleep(2)
reactor.stop()
self.__stopForever.set()
stopThread = threading.Thread(name='XRStop', target=stop_thread)
stopThread.start()
return True
def is_alive(self):
status = False
if reactor.running == 1:
status = True
return status
def status(self):
"""Return status information on running XMLRPC Server."""
stat = { 'XR server address' : self.server_address,
'XR methods' : self.system_listMethods(),
'XR server alive' : self.is_alive(),
'XR requests processed' : self.__xmlrpc.num_requests(),
'XR server stop flag' : self.__stopForever.isSet()}
return(stat)
def system_listMethods(self):
return self.__xmlrpc.list_methods()
def get_server_address(self):
waitCount = 0
while self.server_address == '':
if waitCount == 9:
break
time.sleep(1)
waitCount = waitCount + 1
return self.server_address
except ImportError:
pass | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
isshub
Github issues client
Using python with qt4
author: Pablo Alejandro Seibelt
website: www.sicarul.com.ar
"""
#Username - case sensitive, a-z A-Z 0-9 - (dash), cannot begin with dash
#Reponame - case sensitive, a-z A-Z 0-9 - (dash)
import sys
from PySide import QtGui, QtCore
import github_api
class NewIssue(QtGui.QMainWindow):
def __init__(self):
super(NewIssue, self).__init__()
self.initUI()
def showError(self, msg):
QtGui.QMessageBox.about(self, "ERROR", "%s" % msg )
def create_issue(self):
reponame = self.txt_reponame.text()
issname = self.txt_issname.text()
issdesc = self.txt_issdesc.toPlainText()
status = github_api.create_issue(reponame, issname, issdesc)
if status == "Ok":
self.close()
else:
self.showError("An error has ocurred trying to create the issue: " + status)
def initUI(self):
self.statusBar().showMessage('')
self.cw = QtGui.QWidget()
self.setCentralWidget(self.cw)
self.txt_reponame = QtGui.QLineEdit (self)
self.txt_reponame.setToolTip('The <b>new issue\'s</b> complete repository name (user/repository)')
self.txt_reponame.setText('sicarul/isshub')
self.txt_issname = QtGui.QLineEdit (self)
self.txt_issname.setToolTip('The <b>new issue\'s</b> title')
self.txt_issname.setText('Test issue')
self.txt_issdesc = QtGui.QTextEdit (self)
self.txt_issdesc.setToolTip('A description of the issue')
self.txt_issdesc.setText('This is just a test issue')
self.btn_create = QtGui.QPushButton ('Create issue',self)
self.btn_create.setToolTip('Create the issue')
self.btn_create.clicked.connect(self.create_issue)
self.hbox = QtGui.QHBoxLayout()
self.hbox.addStretch(1)
self.hbox.addWidget(self.btn_create)
self.vbox = QtGui.QVBoxLayout()
self.vbox.addWidget(self.txt_reponame)
self.vbox.addWidget(self.txt_issname)
self.vbox.addWidget(self.txt_issdesc)
self.vbox.addLayout(self.hbox)
self.vbox.addStretch(1)
self.cw.setLayout(self.vbox)
self.setGeometry(200, 200, 800, 300)
self.center()
self.setWindowTitle('isshub - New issue')
self.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
app = QtGui.QApplication(sys.argv)
ex = NewIssue()
sys.exit(app.exec_())
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
#![feature(str_split_remainder)]
#![feature(impl_trait_in_assoc_type)]
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![feature(iter_intersperse)]
mod app_page_loader_tree;
pub mod app_structure;
mod base_loader_tree;
mod bootstrap;
mod embed_js;
mod emit;
pub mod hmr_entry;
pub mod instrumentation;
pub mod middleware;
pub mod mode;
pub mod next_app;
mod next_build;
pub mod next_client;
pub mod next_client_reference;
pub mod next_config;
pub mod next_dynamic;
pub mod next_edge;
mod next_font;
mod next_image;
mod next_import_map;
pub mod next_manifests;
pub mod next_pages;
mod next_root_params;
pub mod next_server;
pub mod next_server_component;
pub mod next_server_utility;
mod next_shared;
pub mod next_telemetry;
mod page_loader;
pub mod pages_structure;
pub mod raw_ecmascript_module;
pub mod segment_config;
pub mod tracing_presets;
mod transform_options;
pub mod url_node;
pub mod util;
pub use emit::{emit_all_assets, emit_assets};
pub use next_edge::context::{
get_edge_chunking_context, get_edge_chunking_context_with_client_assets,
get_edge_compile_time_info, get_edge_resolve_options_context,
};
pub use next_import_map::get_next_package;
pub use page_loader::{PageLoaderAsset, create_page_loader_entry_module};
pub use segment_config::{parse_segment_config_from_loader_tree, parse_segment_config_from_source};
pub use util::{PathType, get_asset_path_from_pathname, pathname_for_path}; | rust | github | https://github.com/vercel/next.js | crates/next-core/src/lib.rs |
import re
import numpy as np
import pytest
from pandas.core.dtypes import generic as gt
import pandas as pd
import pandas._testing as tm
class TestABCClasses:
tuples = [[1, 2, 2], ["red", "blue", "red"]]
multi_index = pd.MultiIndex.from_arrays(tuples, names=("number", "color"))
datetime_index = pd.to_datetime(["2000/1/1", "2010/1/1"])
timedelta_index = pd.to_timedelta(np.arange(5), unit="s")
period_index = pd.period_range("2000/1/1", "2010/1/1/", freq="M")
categorical = pd.Categorical([1, 2, 3], categories=[2, 3, 1])
categorical_df = pd.DataFrame({"values": [1, 2, 3]}, index=categorical)
df = pd.DataFrame({"names": ["a", "b", "c"]}, index=multi_index)
sparse_array = pd.arrays.SparseArray(np.random.default_rng(2).standard_normal(10))
datetime_array = datetime_index.array
timedelta_array = timedelta_index.array
abc_pairs = [
("ABCMultiIndex", multi_index),
("ABCDatetimeIndex", datetime_index),
("ABCRangeIndex", pd.RangeIndex(3)),
("ABCTimedeltaIndex", timedelta_index),
("ABCIntervalIndex", pd.interval_range(start=0, end=3)),
(
"ABCPeriodArray",
pd.arrays.PeriodArray([2000, 2001, 2002], dtype="period[D]"),
),
("ABCNumpyExtensionArray", pd.arrays.NumpyExtensionArray(np.array([0, 1, 2]))),
("ABCPeriodIndex", period_index),
("ABCCategoricalIndex", categorical_df.index),
("ABCSeries", pd.Series([1, 2, 3])),
("ABCDataFrame", df),
("ABCCategorical", categorical),
("ABCDatetimeArray", datetime_array),
("ABCTimedeltaArray", timedelta_array),
]
@pytest.mark.parametrize("abctype1, inst", abc_pairs)
@pytest.mark.parametrize("abctype2, _", abc_pairs)
def test_abc_pairs_instance_check(self, abctype1, abctype2, inst, _):
# GH 38588, 46719
if abctype1 == abctype2:
assert isinstance(inst, getattr(gt, abctype2))
assert not isinstance(type(inst), getattr(gt, abctype2))
else:
assert not isinstance(inst, getattr(gt, abctype2))
@pytest.mark.parametrize("abctype1, inst", abc_pairs)
@pytest.mark.parametrize("abctype2, _", abc_pairs)
def test_abc_pairs_subclass_check(self, abctype1, abctype2, inst, _):
# GH 38588, 46719
if abctype1 == abctype2:
assert issubclass(type(inst), getattr(gt, abctype2))
with pytest.raises(
TypeError, match=re.escape("issubclass() arg 1 must be a class")
):
issubclass(inst, getattr(gt, abctype2))
else:
assert not issubclass(type(inst), getattr(gt, abctype2))
abc_subclasses = {
"ABCIndex": [
abctype
for abctype, _ in abc_pairs
if "Index" in abctype and abctype != "ABCIndex"
],
"ABCNDFrame": ["ABCSeries", "ABCDataFrame"],
"ABCExtensionArray": [
"ABCCategorical",
"ABCDatetimeArray",
"ABCPeriodArray",
"ABCTimedeltaArray",
],
}
@pytest.mark.parametrize("parent, subs", abc_subclasses.items())
@pytest.mark.parametrize("abctype, inst", abc_pairs)
def test_abc_hierarchy(self, parent, subs, abctype, inst):
# GH 38588
if abctype in subs:
assert isinstance(inst, getattr(gt, parent))
else:
assert not isinstance(inst, getattr(gt, parent))
@pytest.mark.parametrize("abctype", [e for e in gt.__dict__ if e.startswith("ABC")])
def test_abc_coverage(self, abctype):
# GH 38588
assert (
abctype in (e for e, _ in self.abc_pairs) or abctype in self.abc_subclasses
)
def test_setattr_warnings():
# GH7175 - GOTCHA: You can't use dot notation to add a column...
d = {
"one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
"two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)
with tm.assert_produces_warning(None):
# successfully add new column
# this should not raise a warning
df["three"] = df.two + 1
assert df.three.sum() > df.two.sum()
with tm.assert_produces_warning(None):
# successfully modify column in place
# this should not raise a warning
df.one += 1
assert df.one.iloc[0] == 2
with tm.assert_produces_warning(None):
# successfully add an attribute to a series
# this should not raise a warning
df.two.not_an_index = [1, 2]
with tm.assert_produces_warning(UserWarning, match="doesn't allow columns"):
# warn when setting column to nonexistent name
df.four = df.two + 2
assert df.four.sum() > df.two.sum() | python | github | https://github.com/pandas-dev/pandas | pandas/tests/dtypes/test_generic.py |
data = (
'Han ', # 0x00
'Xuan ', # 0x01
'Yan ', # 0x02
'Qiu ', # 0x03
'Quan ', # 0x04
'Lang ', # 0x05
'Li ', # 0x06
'Xiu ', # 0x07
'Fu ', # 0x08
'Liu ', # 0x09
'Ye ', # 0x0a
'Xi ', # 0x0b
'Ling ', # 0x0c
'Li ', # 0x0d
'Jin ', # 0x0e
'Lian ', # 0x0f
'Suo ', # 0x10
'Chiisai ', # 0x11
'[?] ', # 0x12
'Wan ', # 0x13
'Dian ', # 0x14
'Pin ', # 0x15
'Zhan ', # 0x16
'Cui ', # 0x17
'Min ', # 0x18
'Yu ', # 0x19
'Ju ', # 0x1a
'Chen ', # 0x1b
'Lai ', # 0x1c
'Wen ', # 0x1d
'Sheng ', # 0x1e
'Wei ', # 0x1f
'Dian ', # 0x20
'Chu ', # 0x21
'Zhuo ', # 0x22
'Pei ', # 0x23
'Cheng ', # 0x24
'Hu ', # 0x25
'Qi ', # 0x26
'E ', # 0x27
'Kun ', # 0x28
'Chang ', # 0x29
'Qi ', # 0x2a
'Beng ', # 0x2b
'Wan ', # 0x2c
'Lu ', # 0x2d
'Cong ', # 0x2e
'Guan ', # 0x2f
'Yan ', # 0x30
'Diao ', # 0x31
'Bei ', # 0x32
'Lin ', # 0x33
'Qin ', # 0x34
'Pi ', # 0x35
'Pa ', # 0x36
'Que ', # 0x37
'Zhuo ', # 0x38
'Qin ', # 0x39
'Fa ', # 0x3a
'[?] ', # 0x3b
'Qiong ', # 0x3c
'Du ', # 0x3d
'Jie ', # 0x3e
'Hun ', # 0x3f
'Yu ', # 0x40
'Mao ', # 0x41
'Mei ', # 0x42
'Chun ', # 0x43
'Xuan ', # 0x44
'Ti ', # 0x45
'Xing ', # 0x46
'Dai ', # 0x47
'Rou ', # 0x48
'Min ', # 0x49
'Zhen ', # 0x4a
'Wei ', # 0x4b
'Ruan ', # 0x4c
'Huan ', # 0x4d
'Jie ', # 0x4e
'Chuan ', # 0x4f
'Jian ', # 0x50
'Zhuan ', # 0x51
'Yang ', # 0x52
'Lian ', # 0x53
'Quan ', # 0x54
'Xia ', # 0x55
'Duan ', # 0x56
'Yuan ', # 0x57
'Ye ', # 0x58
'Nao ', # 0x59
'Hu ', # 0x5a
'Ying ', # 0x5b
'Yu ', # 0x5c
'Huang ', # 0x5d
'Rui ', # 0x5e
'Se ', # 0x5f
'Liu ', # 0x60
'Shi ', # 0x61
'Rong ', # 0x62
'Suo ', # 0x63
'Yao ', # 0x64
'Wen ', # 0x65
'Wu ', # 0x66
'Jin ', # 0x67
'Jin ', # 0x68
'Ying ', # 0x69
'Ma ', # 0x6a
'Tao ', # 0x6b
'Liu ', # 0x6c
'Tang ', # 0x6d
'Li ', # 0x6e
'Lang ', # 0x6f
'Gui ', # 0x70
'Zhen ', # 0x71
'Qiang ', # 0x72
'Cuo ', # 0x73
'Jue ', # 0x74
'Zhao ', # 0x75
'Yao ', # 0x76
'Ai ', # 0x77
'Bin ', # 0x78
'Tu ', # 0x79
'Chang ', # 0x7a
'Kun ', # 0x7b
'Zhuan ', # 0x7c
'Cong ', # 0x7d
'Jin ', # 0x7e
'Yi ', # 0x7f
'Cui ', # 0x80
'Cong ', # 0x81
'Qi ', # 0x82
'Li ', # 0x83
'Ying ', # 0x84
'Suo ', # 0x85
'Qiu ', # 0x86
'Xuan ', # 0x87
'Ao ', # 0x88
'Lian ', # 0x89
'Man ', # 0x8a
'Zhang ', # 0x8b
'Yin ', # 0x8c
'[?] ', # 0x8d
'Ying ', # 0x8e
'Zhi ', # 0x8f
'Lu ', # 0x90
'Wu ', # 0x91
'Deng ', # 0x92
'Xiou ', # 0x93
'Zeng ', # 0x94
'Xun ', # 0x95
'Qu ', # 0x96
'Dang ', # 0x97
'Lin ', # 0x98
'Liao ', # 0x99
'Qiong ', # 0x9a
'Su ', # 0x9b
'Huang ', # 0x9c
'Gui ', # 0x9d
'Pu ', # 0x9e
'Jing ', # 0x9f
'Fan ', # 0xa0
'Jin ', # 0xa1
'Liu ', # 0xa2
'Ji ', # 0xa3
'[?] ', # 0xa4
'Jing ', # 0xa5
'Ai ', # 0xa6
'Bi ', # 0xa7
'Can ', # 0xa8
'Qu ', # 0xa9
'Zao ', # 0xaa
'Dang ', # 0xab
'Jiao ', # 0xac
'Gun ', # 0xad
'Tan ', # 0xae
'Hui ', # 0xaf
'Huan ', # 0xb0
'Se ', # 0xb1
'Sui ', # 0xb2
'Tian ', # 0xb3
'[?] ', # 0xb4
'Yu ', # 0xb5
'Jin ', # 0xb6
'Lu ', # 0xb7
'Bin ', # 0xb8
'Shou ', # 0xb9
'Wen ', # 0xba
'Zui ', # 0xbb
'Lan ', # 0xbc
'Xi ', # 0xbd
'Ji ', # 0xbe
'Xuan ', # 0xbf
'Ruan ', # 0xc0
'Huo ', # 0xc1
'Gai ', # 0xc2
'Lei ', # 0xc3
'Du ', # 0xc4
'Li ', # 0xc5
'Zhi ', # 0xc6
'Rou ', # 0xc7
'Li ', # 0xc8
'Zan ', # 0xc9
'Qiong ', # 0xca
'Zhe ', # 0xcb
'Gui ', # 0xcc
'Sui ', # 0xcd
'La ', # 0xce
'Long ', # 0xcf
'Lu ', # 0xd0
'Li ', # 0xd1
'Zan ', # 0xd2
'Lan ', # 0xd3
'Ying ', # 0xd4
'Mi ', # 0xd5
'Xiang ', # 0xd6
'Xi ', # 0xd7
'Guan ', # 0xd8
'Dao ', # 0xd9
'Zan ', # 0xda
'Huan ', # 0xdb
'Gua ', # 0xdc
'Bo ', # 0xdd
'Die ', # 0xde
'Bao ', # 0xdf
'Hu ', # 0xe0
'Zhi ', # 0xe1
'Piao ', # 0xe2
'Ban ', # 0xe3
'Rang ', # 0xe4
'Li ', # 0xe5
'Wa ', # 0xe6
'Dekaguramu ', # 0xe7
'Jiang ', # 0xe8
'Qian ', # 0xe9
'Fan ', # 0xea
'Pen ', # 0xeb
'Fang ', # 0xec
'Dan ', # 0xed
'Weng ', # 0xee
'Ou ', # 0xef
'Deshiguramu ', # 0xf0
'Miriguramu ', # 0xf1
'Thon ', # 0xf2
'Hu ', # 0xf3
'Ling ', # 0xf4
'Yi ', # 0xf5
'Ping ', # 0xf6
'Ci ', # 0xf7
'Hekutogura ', # 0xf8
'Juan ', # 0xf9
'Chang ', # 0xfa
'Chi ', # 0xfb
'Sarake ', # 0xfc
'Dang ', # 0xfd
'Meng ', # 0xfe
'Pou ', # 0xff
) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env bash
set -eux
ansible-playbook playbook.yml --start-at-task 'task 2' "$@" | unknown | github | https://github.com/ansible/ansible | test/integration/targets/play_iterator/runme.sh |
#!/usr/bin/python
# Copyright (c)2011-2012 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3lte.py - This script demonstrates using CORE with the ns-3 LTE model.
*** Note that this script is not currently functional, see notes below. ***
- issues connecting TapBridge with LteNetDevice
'''
import os, sys, time, optparse, datetime, math
try:
from core import pycore
except ImportError:
# hack for Fedora autoconf that uses the following pythondir:
if "/usr/lib/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.6/site-packages")
if "/usr/lib64/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.6/site-packages")
if "/usr/lib/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.7/site-packages")
if "/usr/lib64/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.7/site-packages")
from core import pycore
from core.misc import ipaddr
from corens3.obj import Ns3Session, Ns3LteNet
import ns.core
import ns.mobility
def ltesession(opt):
''' Run a test LTE session.
'''
session = Ns3Session(persistent=True, duration=opt.duration)
lte = session.addobj(cls=Ns3LteNet, name="wlan1")
lte.setsubchannels(range(25), range(50, 100))
if opt.verbose:
ascii = ns.network.AsciiTraceHelper()
stream = ascii.CreateFileStream('/tmp/ns3lte.tr')
lte.lte.EnableAsciiAll(stream)
#ns.core.LogComponentEnable("EnbNetDevice", ns.core.LOG_LEVEL_INFO)
#ns.core.LogComponentEnable("UeNetDevice", ns.core.LOG_LEVEL_INFO)
#lte.lte.EnableLogComponents()
prefix = ipaddr.IPv4Prefix("10.0.0.0/16")
mobb = None
nodes = []
for i in xrange(1, opt.numnodes + 1):
node = session.addnode(name = "n%d" % i)
mob = ns.mobility.ConstantPositionMobilityModel()
mob.SetPosition( ns.core.Vector3D(10.0 * i, 0.0, 0.0) )
if i == 1:
lte.setnodeb(node) # first node is nodeb
mobb = mob
node.newnetif(lte, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
nodes.append(node)
if i == 1:
(tmp, ns3dev) = lte.findns3dev(node)
lte.lte.AddMobility(ns3dev.GetPhy(), mob)
if i > 1:
lte.linknodeb(node, nodes[0], mob, mobb)
session.thread = session.run(vis=opt.visualize)
return session
def main():
''' Main routine when running from command-line.
'''
usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr)
parser.set_defaults(numnodes = 4, duration = 600, verbose = False, visualize=False)
parser.add_option("-d", "--duration", dest = "duration", type = int,
help = "number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int,
help = "number of nodes")
parser.add_option("-z", "--visualize", dest = "visualize",
action = "store_true", help = "enable visualizer")
parser.add_option("-v", "--verbose", dest = "verbose",
action = "store_true", help = "be more verbose")
def usage(msg = None, err = 0):
sys.stdout.write("\n")
if msg:
sys.stdout.write(msg + "\n\n")
parser.print_help()
sys.exit(err)
(opt, args) = parser.parse_args()
if opt.numnodes < 2:
usage("invalid numnodes: %s" % opt.numnodes)
for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a)
return ltesession(opt)
def cleanup():
print "shutting down session"
session.shutdown()
print "joining simulator thread (please kill it)"
session.thread.join()
if __name__ == "__main__":
session = main() | unknown | codeparrot/codeparrot-clean | ||
from __future__ import print_function
import os, sys
from nose import with_setup
import cPickle as pickle
from tacc_stats.pickler import job_pickles
from tacc_stats.pickler import job_stats, batch_acct
sys.modules['pickler.job_stats'] = job_stats
sys.modules['pickler.batch_acct'] = batch_acct
path = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(path, 'data')
def setup_func():
a = open(os.path.join(path,"cfg.py"),"w")
a.write('archive_dir = \"' + data_dir + '\"\n'
'acct_path = \"'+ data_dir +'/tacc_jobs_completed\"\n'
'host_list_dir= \"' + data_dir + '\"\n'
'pickles_dir= \"' + path + '\"\n'
'host_name_ext= \"platform.extension\"\n'
'batch_system = \"SLURM\"\n'
'seek=0\n')
a.close()
def teardown_func():
os.remove(os.path.join(path,"cfg.py"))
try:
os.remove(os.path.join(path,"cfg.pyc"))
except: pass
os.remove(os.path.join(path,'2013-10-01',"1835740"))
os.rmdir(os.path.join(path,'2013-10-01'))
os.remove(os.path.join(path,'2014-10-31',"20"))
os.rmdir(os.path.join(path,'2014-10-31'))
@with_setup(setup_func, teardown_func)
def test():
from tacc_stats.pickler.tests import cfg
pickle_options = { 'processes' : 1,
'start' : '2013-10-01',
'end' : '2014-11-01',
'pickle_dir' : cfg.pickles_dir,
'batch_system' : cfg.batch_system,
'acct_path' : cfg.acct_path,
'archive_dir' : cfg.archive_dir,
'host_list_dir' : cfg.host_list_dir,
'host_name_ext' : cfg.host_name_ext,
'seek' : cfg.seek
}
pickler = job_pickles.JobPickles(**pickle_options)
pickler.run()
assert os.path.isfile(os.path.join(path,'2013-10-01','1835740')) == True
print("Pickle file generated.")
old = pickle.load(open(os.path.join(path,'1835740_ref')))
new = pickle.load(open(os.path.join(path,'2013-10-01','1835740')))
compare_newtoold(new,old)
old = pickle.load(open(os.path.join(path,'20_ref')))
new = pickle.load(open(os.path.join(path,'2014-10-31','20')))
compare_newtoold(new,old)
@with_setup(setup_func, teardown_func)
def test_ids():
from tacc_stats.pickler.tests import cfg
pickle_options = { 'processes' : 1,
'pickle_dir' : cfg.pickles_dir,
'batch_system' : cfg.batch_system,
'acct_path' : cfg.acct_path,
'archive_dir' : cfg.archive_dir,
'host_list_dir' : cfg.host_list_dir,
'host_name_ext' : cfg.host_name_ext,
'seek' : cfg.seek
}
pickler = job_pickles.JobPickles(**pickle_options)
pickler.run(['1835740'])
pickler.run(['20'])
assert os.path.isfile(os.path.join(path,'2013-10-01','1835740')) == True
print("Pickle file generated.")
old = pickle.load(open(os.path.join(path,'1835740_ref')))
new = pickle.load(open(os.path.join(path,'2013-10-01','1835740')))
compare_newtoold(new,old)
old = pickle.load(open(os.path.join(path,'20_ref')))
new = pickle.load(open(os.path.join(path,'2014-10-31','20')))
compare_newtoold(new,old)
def compare_newtoold(new,old):
assert new.id == old.id
for i in range(len(old.times)):
assert new.times[i] == old.times[i]
for i in range(len(old.hosts.keys())):
assert old.hosts.keys()[i] == new.hosts.keys()[i]
print('id, keys, and times match.')
for host_name, host in old.hosts.iteritems():
for type_name, type_stats in host.stats.iteritems():
if type_name =='ib': continue
for dev_name, dev_stats in type_stats.iteritems():
for i in range(len(dev_stats)):
for j in range(len(dev_stats[i])):
if new.hosts[host_name].stats[type_name][dev_name][i][j]-dev_stats[i][j] != 0.0:
print(new.times[i],host_name,type_name,dev_name,new.hosts[host_name].stats[type_name][dev_name][i][j],dev_stats[i][j])
assert new.hosts[host_name].stats[type_name][dev_name][i][j] == dev_stats[i][j]
print('stats match.') | unknown | codeparrot/codeparrot-clean | ||
"""Utility functions, node construction macros, etc."""
# Author: Collin Winter
from itertools import islice
# Local imports
from .pgen2 import token
from .pytree import Leaf, Node
from .pygram import python_symbols as syms
from . import patcomp
###########################################################
### Common node-construction "macros"
###########################################################
def KeywordArg(keyword, value):
return Node(syms.argument,
[keyword, Leaf(token.EQUAL, u"="), value])
def LParen():
return Leaf(token.LPAR, u"(")
def RParen():
return Leaf(token.RPAR, u")")
def Assign(target, source):
"""Build an assignment statement"""
if not isinstance(target, list):
target = [target]
if not isinstance(source, list):
source.prefix = u" "
source = [source]
return Node(syms.atom,
target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source)
def Name(name, prefix=None):
"""Return a NAME leaf"""
return Leaf(token.NAME, name, prefix=prefix)
def Attr(obj, attr):
"""A node tuple for obj.attr"""
return [obj, Node(syms.trailer, [Dot(), attr])]
def Comma():
"""A comma leaf"""
return Leaf(token.COMMA, u",")
def Dot():
"""A period (.) leaf"""
return Leaf(token.DOT, u".")
def ArgList(args, lparen=LParen(), rparen=RParen()):
"""A parenthesised argument list, used by Call()"""
node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
if args:
node.insert_child(1, Node(syms.arglist, args))
return node
def Call(func_name, args=None, prefix=None):
"""A function call"""
node = Node(syms.power, [func_name, ArgList(args)])
if prefix is not None:
node.prefix = prefix
return node
def Newline():
"""A newline literal"""
return Leaf(token.NEWLINE, u"\n")
def BlankLine():
"""A blank line"""
return Leaf(token.NEWLINE, u"")
def Number(n, prefix=None):
return Leaf(token.NUMBER, n, prefix=prefix)
def Subscript(index_node):
"""A numeric or string subscript"""
return Node(syms.trailer, [Leaf(token.LBRACE, u"["),
index_node,
Leaf(token.RBRACE, u"]")])
def String(string, prefix=None):
"""A string leaf"""
return Leaf(token.STRING, string, prefix=prefix)
def ListComp(xp, fp, it, test=None):
"""A list comprehension of the form [xp for fp in it if test].
If test is None, the "if test" part is omitted.
"""
xp.prefix = u""
fp.prefix = u" "
it.prefix = u" "
for_leaf = Leaf(token.NAME, u"for")
for_leaf.prefix = u" "
in_leaf = Leaf(token.NAME, u"in")
in_leaf.prefix = u" "
inner_args = [for_leaf, fp, in_leaf, it]
if test:
test.prefix = u" "
if_leaf = Leaf(token.NAME, u"if")
if_leaf.prefix = u" "
inner_args.append(Node(syms.comp_if, [if_leaf, test]))
inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)])
return Node(syms.atom,
[Leaf(token.LBRACE, u"["),
inner,
Leaf(token.RBRACE, u"]")])
def FromImport(package_name, name_leafs):
""" Return an import statement in the form:
from package import name_leafs"""
# XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
#assert package_name == '.' or '.' not in package_name, "FromImport has "\
# "not been tested with dotted package names -- use at your own "\
# "peril!"
for leaf in name_leafs:
# Pull the leaves out of their old tree
leaf.remove()
children = [Leaf(token.NAME, u"from"),
Leaf(token.NAME, package_name, prefix=u" "),
Leaf(token.NAME, u"import", prefix=u" "),
Node(syms.import_as_names, name_leafs)]
imp = Node(syms.import_from, children)
return imp
###########################################################
### Determine whether a node represents a given literal
###########################################################
def is_tuple(node):
"""Does the node represent a tuple literal?"""
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
return True
return (isinstance(node, Node)
and len(node.children) == 3
and isinstance(node.children[0], Leaf)
and isinstance(node.children[1], Node)
and isinstance(node.children[2], Leaf)
and node.children[0].value == u"("
and node.children[2].value == u")")
def is_list(node):
"""Does the node represent a list literal?"""
return (isinstance(node, Node)
and len(node.children) > 1
and isinstance(node.children[0], Leaf)
and isinstance(node.children[-1], Leaf)
and node.children[0].value == u"["
and node.children[-1].value == u"]")
###########################################################
### Misc
###########################################################
def parenthesize(node):
return Node(syms.atom, [LParen(), node, RParen()])
consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum",
"min", "max", "enumerate"])
def attr_chain(obj, attr):
"""Follow an attribute chain.
If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
use this to iterate over all objects in the chain. Iteration is
terminated by getattr(x, attr) is None.
Args:
obj: the starting object
attr: the name of the chaining attribute
Yields:
Each successive object in the chain.
"""
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr)
p0 = """for_stmt< 'for' any 'in' node=any ':' any* >
| comp_for< 'for' any 'in' node=any any* >
"""
p1 = """
power<
( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |
'any' | 'all' | 'enumerate' | (any* trailer< '.' 'join' >) )
trailer< '(' node=any ')' >
any*
>
"""
p2 = """
power<
( 'sorted' | 'enumerate' )
trailer< '(' arglist<node=any any*> ')' >
any*
>
"""
pats_built = False
def in_special_context(node):
""" Returns true if node is in an environment where all that is required
of it is being iterable (ie, it doesn't matter if it returns a list
or an iterator).
See test_map_nochange in test_fixers.py for some examples and tests.
"""
global p0, p1, p2, pats_built
if not pats_built:
p0 = patcomp.compile_pattern(p0)
p1 = patcomp.compile_pattern(p1)
p2 = patcomp.compile_pattern(p2)
pats_built = True
patterns = [p0, p1, p2]
for pattern, parent in zip(patterns, attr_chain(node, "parent")):
results = {}
if pattern.match(parent, results) and results["node"] is node:
return True
return False
def is_probably_builtin(node):
"""
Check that something isn't an attribute or function name etc.
"""
prev = node.prev_sibling
if prev is not None and prev.type == token.DOT:
# Attribute lookup.
return False
parent = node.parent
if parent.type in (syms.funcdef, syms.classdef):
return False
if parent.type == syms.expr_stmt and parent.children[0] is node:
# Assignment.
return False
if parent.type == syms.parameters or \
(parent.type == syms.typedargslist and (
(prev is not None and prev.type == token.COMMA) or
parent.children[0] is node
)):
# The name of an argument.
return False
return True
def find_indentation(node):
"""Find the indentation of *node*."""
while node is not None:
if node.type == syms.suite and len(node.children) > 2:
indent = node.children[1]
if indent.type == token.INDENT:
return indent.value
node = node.parent
return u""
###########################################################
### The following functions are to find bindings in a suite
###########################################################
def make_suite(node):
if node.type == syms.suite:
return node
node = node.clone()
parent, node.parent = node.parent, None
suite = Node(syms.suite, [node])
suite.parent = parent
return suite
def find_root(node):
"""Find the top level namespace."""
# Scamper up to the top level namespace
while node.type != syms.file_input:
node = node.parent
if not node:
raise ValueError("root found before file_input node was found.")
return node
def does_tree_import(package, name, node):
""" Returns true if name is imported from package at the
top level of the tree which node belongs to.
To cover the case of an import like 'import foo', use
None for the package and 'foo' for the name. """
binding = find_binding(name, find_root(node), package)
return bool(binding)
def is_import(node):
"""Returns true if the node is an import statement."""
return node.type in (syms.import_name, syms.import_from)
def touch_import(package, name, node):
""" Works like `does_tree_import` but adds an import statement
if it was not imported. """
def is_import_stmt(node):
return (node.type == syms.simple_stmt and node.children and
is_import(node.children[0]))
root = find_root(node)
if does_tree_import(package, name, root):
return
# figure out where to insert the new import. First try to find
# the first import and then skip to the last one.
insert_pos = offset = 0
for idx, node in enumerate(root.children):
if not is_import_stmt(node):
continue
for offset, node2 in enumerate(root.children[idx:]):
if not is_import_stmt(node2):
break
insert_pos = idx + offset
break
# if there are no imports where we can insert, find the docstring.
# if that also fails, we stick to the beginning of the file
if insert_pos == 0:
for idx, node in enumerate(root.children):
if (node.type == syms.simple_stmt and node.children and
node.children[0].type == token.STRING):
insert_pos = idx + 1
break
if package is None:
import_ = Node(syms.import_name, [
Leaf(token.NAME, u"import"),
Leaf(token.NAME, name, prefix=u" ")
])
else:
import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")])
children = [import_, Newline()]
root.insert_child(insert_pos, Node(syms.simple_stmt, children))
_def_syms = set([syms.classdef, syms.funcdef])
def find_binding(name, node, package=None):
""" Returns the node which binds variable name, otherwise None.
If optional argument package is supplied, only imports will
be returned.
See test cases for examples."""
for child in node.children:
ret = None
if child.type == syms.for_stmt:
if _find(name, child.children[1]):
return child
n = find_binding(name, make_suite(child.children[-1]), package)
if n: ret = n
elif child.type in (syms.if_stmt, syms.while_stmt):
n = find_binding(name, make_suite(child.children[-1]), package)
if n: ret = n
elif child.type == syms.try_stmt:
n = find_binding(name, make_suite(child.children[2]), package)
if n:
ret = n
else:
for i, kid in enumerate(child.children[3:]):
if kid.type == token.COLON and kid.value == ":":
# i+3 is the colon, i+4 is the suite
n = find_binding(name, make_suite(child.children[i+4]), package)
if n: ret = n
elif child.type in _def_syms and child.children[1].value == name:
ret = child
elif _is_import_binding(child, name, package):
ret = child
elif child.type == syms.simple_stmt:
ret = find_binding(name, child, package)
elif child.type == syms.expr_stmt:
if _find(name, child.children[0]):
ret = child
if ret:
if not package:
return ret
if is_import(ret):
return ret
return None
_block_syms = set([syms.funcdef, syms.classdef, syms.trailer])
def _find(name, node):
nodes = [node]
while nodes:
node = nodes.pop()
if node.type > 256 and node.type not in _block_syms:
nodes.extend(node.children)
elif node.type == token.NAME and node.value == name:
return node
return None
def _is_import_binding(node, name, package=None):
""" Will reuturn node if node will import name, or node
will import * from package. None is returned otherwise.
See test cases for examples. """
if node.type == syms.import_name and not package:
imp = node.children[1]
if imp.type == syms.dotted_as_names:
for child in imp.children:
if child.type == syms.dotted_as_name:
if child.children[2].value == name:
return node
elif child.type == token.NAME and child.value == name:
return node
elif imp.type == syms.dotted_as_name:
last = imp.children[-1]
if last.type == token.NAME and last.value == name:
return node
elif imp.type == token.NAME and imp.value == name:
return node
elif node.type == syms.import_from:
# unicode(...) is used to make life easier here, because
# from a.b import parses to ['import', ['a', '.', 'b'], ...]
if package and unicode(node.children[1]).strip() != package:
return None
n = node.children[3]
if package and _find(u"as", n):
# See test_from_import_as for explanation
return None
elif n.type == syms.import_as_names and _find(name, n):
return node
elif n.type == syms.import_as_name:
child = n.children[2]
if child.type == token.NAME and child.value == name:
return node
elif n.type == token.NAME and n.value == name:
return node
elif package and n.type == token.STAR:
return node
return None | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility ops shared across tf.contrib.signal."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fractions
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
def gcd(a, b, name=None):
"""Returns the greatest common divisor via Euclid's algorithm.
Args:
a: The dividend. A scalar integer `Tensor`.
b: The divisor. A scalar integer `Tensor`.
name: An optional name for the operation.
Returns:
A scalar `Tensor` representing the greatest common divisor between `a` and
`b`.
Raises:
ValueError: If `a` or `b` are not scalar integers.
"""
with ops.name_scope(name, 'gcd', [a, b]):
a = ops.convert_to_tensor(a)
b = ops.convert_to_tensor(b)
a.shape.assert_has_rank(0)
b.shape.assert_has_rank(0)
if not a.dtype.is_integer:
raise ValueError('a must be an integer type. Got: %s' % a.dtype)
if not b.dtype.is_integer:
raise ValueError('b must be an integer type. Got: %s' % b.dtype)
# TPU requires static shape inference. GCD is used for subframe size
# computation, so we should prefer static computation where possible.
const_a = tensor_util.constant_value(a)
const_b = tensor_util.constant_value(b)
if const_a is not None and const_b is not None:
return ops.convert_to_tensor(fractions.gcd(const_a, const_b))
cond = lambda _, b: math_ops.greater(b, array_ops.zeros_like(b))
body = lambda a, b: [b, math_ops.mod(a, b)]
a, b = control_flow_ops.while_loop(cond, body, [a, b], back_prop=False)
return a | unknown | codeparrot/codeparrot-clean | ||
# ===--- SwiftIntTypes.py ----------------------------*- coding: utf-8 -*-===//
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
# Bit counts for all int types
_all_integer_type_bitwidths = [8, 16, 32, 64]
# Number of bits in the biggest int type
int_max_bits = max(_all_integer_type_bitwidths)
def int_max(bits, signed):
bits = bits - 1 if signed else bits
bits = max(bits, 0)
return (1 << bits) - 1
def int_min(bits, signed):
return (-1 * int_max(bits, signed) - 1) if signed else 0
class SwiftIntegerType(object):
def __init__(self, is_word, bits, is_signed):
self.is_word = is_word
self.bits = bits
self.is_signed = is_signed
if is_word:
self.possible_bitwidths = [32, 64]
else:
self.possible_bitwidths = [bits]
self.min = int_min(bits, is_signed)
self.max = int_max(bits, is_signed)
# Derived properties
self.stdlib_name = \
('' if is_signed else 'U') + \
'Int' + \
('' if is_word else str(bits))
self.builtin_name = 'Int' + str(bits)
def get_opposite_signedness(self):
return SwiftIntegerType(self.is_word, self.bits, not self.is_signed)
def __eq__(self, other):
return self.is_word == other.is_word and \
self.bits == other.bits and \
self.is_signed == other.is_signed
def __ne__(self, other):
return not self.__eq__(other)
def all_integer_types(word_bits):
for bitwidth in _all_integer_type_bitwidths:
for is_signed in [False, True]:
yield SwiftIntegerType(
is_word=False, bits=bitwidth,
is_signed=is_signed)
for is_signed in [False, True]:
yield SwiftIntegerType(
is_word=True, bits=word_bits,
is_signed=is_signed)
# 'truncatingBitPattern' initializer is defined if the conversion is truncating
# on any platform that Swift supports.
def should_define_truncating_bit_pattern_init(src_ty, dst_ty):
# Don't define a truncating conversion between a type and itself.
if src_ty == dst_ty:
return False
# Conversion to opposite signedness is never truncating.
if src_ty == dst_ty.get_opposite_signedness():
return False
for src_ty_bits in src_ty.possible_bitwidths:
for dst_ty_bits in dst_ty.possible_bitwidths:
if src_ty_bits > dst_ty_bits:
return True
return False
def all_integer_type_names():
return [self_ty.stdlib_name for self_ty in all_integer_types(0)]
def all_real_number_type_names():
# FIXME , 'Float80' Revert until I figure out a test failure # Float80
# for i386 & x86_64
return ['Float', 'Double']
def all_numeric_type_names():
return all_integer_type_names() + all_real_number_type_names()
def numeric_type_names_macintosh_only():
return ['Float80']
# Swift_Programming_Language/Expressions.html
def all_integer_binary_operator_names():
return ['%', '<<', '>>', '&*', '&', '&+', '&-', '|', '^']
def all_integer_or_real_binary_operator_names():
return ['*', '/', '+', '-', '..<', '...']
def all_arithmetic_comparison_operator_names():
return ['<', '<=', '>', '>=', '==', '!=']
def all_integer_assignment_operator_names():
return ['%=', '<<=', '>>=', '&=', '^=', '|=']
def all_integer_or_real_assignment_operator_names():
return ['=', '*=', '/=', '+=', '-='] | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime_test
import (
"fmt"
"internal/testenv"
"os"
"regexp"
"strings"
"testing"
)
func TestGoroutineLeakProfile(t *testing.T) {
// Some tests have false negatives under mayMoreStackPreempt and mayMoreStackMove.
// This may be a test-only issue in that they're just sensitive to scheduling, but it
// needs more investigation.
for _, cfg := range []string{"mayMoreStackPreempt", "mayMoreStackMove"} {
if strings.Contains(os.Getenv("GOFLAGS"), cfg) {
testenv.SkipFlaky(t, 75729)
}
}
// Goroutine leak test case.
//
// Test cases can be configured with test name, the name of the entry point function,
// a set of expected leaks identified by regular expressions, and the number of times
// the test should be repeated.
//
// Repeated runs reduce flakiness in some tests.
type testCase struct {
name string
simple bool
repetitions int
expectedLeaks map[*regexp.Regexp]bool
// flakyLeaks are goroutine leaks that are too flaky to be reliably detected.
// Still, they might pop up every once in a while. The test will pass regardless
// if they occur or nor, as they are not unexpected.
//
// Note that all flaky leaks are true positives, i.e. real goroutine leaks,
// and it is only their detection that is unreliable due to scheduling
// non-determinism.
flakyLeaks map[*regexp.Regexp]struct{}
}
// makeAnyTest is a short-hand for creating test cases.
// Each of the leaks in the list is identified by a regular expression.
// If a leak is flaky, it is added to the flakyLeaks map.
makeAnyTest := func(name string, flaky bool, repetitions int, leaks ...string) testCase {
tc := testCase{
name: name,
expectedLeaks: make(map[*regexp.Regexp]bool, len(leaks)),
flakyLeaks: make(map[*regexp.Regexp]struct{}, len(leaks)),
// Make sure the test is repeated at least once.
repetitions: repetitions | 1,
}
for _, leak := range leaks {
if !flaky {
tc.expectedLeaks[regexp.MustCompile(leak)] = false
} else {
tc.flakyLeaks[regexp.MustCompile(leak)] = struct{}{}
}
}
return tc
}
// makeTest is a short-hand for creating non-flaky test cases.
makeTest := func(name string, leaks ...string) testCase {
tcase := makeAnyTest(name, false, 2, leaks...)
tcase.simple = true
return tcase
}
// makeFlakyTest is a short-hand for creating flaky test cases.
makeFlakyTest := func(name string, leaks ...string) testCase {
if testing.Short() {
return makeAnyTest(name, true, 2, leaks...)
}
return makeAnyTest(name, true, 10, leaks...)
}
goroutineHeader := regexp.MustCompile(`goroutine \d+ \[`)
// extractLeaks takes the output of a test and splits it into a
// list of strings denoting goroutine leaks.
//
// If the input is:
//
// goroutine 1 [wait reason (leaked)]:
// main.leaked()
// ./testdata/testgoroutineleakprofile/foo.go:37 +0x100
// created by main.main()
// ./testdata/testgoroutineleakprofile/main.go:10 +0x20
//
// goroutine 2 [wait reason (leaked)]:
// main.leaked2()
// ./testdata/testgoroutineleakprofile/foo.go:37 +0x100
// created by main.main()
// ./testdata/testgoroutineleakprofile/main.go:10 +0x20
//
// The output is (as a list of strings):
//
// leaked() [wait reason]
// leaked2() [wait reason]
extractLeaks := func(output string) []string {
stacks := strings.Split(output, "\n\ngoroutine")
var leaks []string
for _, stack := range stacks {
lines := strings.Split(stack, "\n")
if len(lines) < 5 {
// Expecting at least the following lines (where n=len(lines)-1):
//
// [0] goroutine n [wait reason (leaked)]
// ...
// [n-3] bottom.leak.frame(...)
// [n-2] ./bottom/leak/frame/source.go:line
// [n-1] created by go.instruction()
// [n] ./go/instruction/source.go:line
continue
}
if !strings.Contains(lines[0], "(leaked)") {
// Ignore non-leaked goroutines.
continue
}
// Get the wait reason from the goroutine header.
header := lines[0]
waitReason := goroutineHeader.ReplaceAllString(header, "[")
waitReason = strings.ReplaceAll(waitReason, " (leaked)", "")
// Get the function name from the stack trace (should be two lines above `created by`).
var funcName string
for i := len(lines) - 1; i >= 0; i-- {
if strings.Contains(lines[i], "created by") {
funcName = strings.TrimPrefix(lines[i-2], "main.")
break
}
}
if funcName == "" {
t.Fatalf("failed to extract function name from stack trace: %s", lines)
}
leaks = append(leaks, funcName+" "+waitReason)
}
return leaks
}
// Micro tests involve very simple leaks for each type of concurrency primitive operation.
microTests := []testCase{
makeTest("NilRecv",
`NilRecv\.func1\(.* \[chan receive \(nil chan\)\]`,
),
makeTest("NilSend",
`NilSend\.func1\(.* \[chan send \(nil chan\)\]`,
),
makeTest("SelectNoCases",
`SelectNoCases\.func1\(.* \[select \(no cases\)\]`,
),
makeTest("ChanRecv",
`ChanRecv\.func1\(.* \[chan receive\]`,
),
makeTest("ChanSend",
`ChanSend\.func1\(.* \[chan send\]`,
),
makeTest("Select",
`Select\.func1\(.* \[select\]`,
),
makeTest("WaitGroup",
`WaitGroup\.func1\(.* \[sync\.WaitGroup\.Wait\]`,
),
makeTest("MutexStack",
`MutexStack\.func1\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("MutexHeap",
`MutexHeap\.func1.1\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Cond",
`Cond\.func1\(.* \[sync\.Cond\.Wait\]`,
),
makeTest("RWMutexRLock",
`RWMutexRLock\.func1\(.* \[sync\.RWMutex\.RLock\]`,
),
makeTest("RWMutexLock",
`RWMutexLock\.func1\(.* \[sync\.(RW)?Mutex\.Lock\]`,
),
makeTest("Mixed",
`Mixed\.func1\(.* \[sync\.WaitGroup\.Wait\]`,
`Mixed\.func1.1\(.* \[chan send\]`,
),
makeTest("NoLeakGlobal"),
}
// Stress tests are flaky and we do not strictly care about their output.
// They are only intended to stress the goroutine leak detector and profiling
// infrastructure in interesting ways.
stressTestCases := []testCase{
makeFlakyTest("SpawnGC",
`spawnGC.func1\(.* \[chan receive\]`,
),
makeTest("DaisyChain"),
}
// Common goroutine leak patterns.
// Extracted from "Unveiling and Vanquishing Goroutine Leaks in Enterprise Microservices: A Dynamic Analysis Approach"
// doi:10.1109/CGO57630.2024.10444835
patternTestCases := []testCase{
makeTest("NoCloseRange",
`noCloseRange\(.* \[chan send\]`,
`noCloseRange\.func1\(.* \[chan receive\]`,
),
makeTest("MethodContractViolation",
`worker\.Start\.func1\(.* \[select\]`,
),
makeTest("DoubleSend",
`DoubleSend\.func3\(.* \[chan send\]`,
),
makeTest("EarlyReturn",
`earlyReturn\.func1\(.* \[chan send\]`,
),
makeTest("NCastLeak",
`nCastLeak\.func1\(.* \[chan send\]`,
`NCastLeak\.func2\(.* \[chan receive\]`,
),
makeTest("Timeout",
// (vsaioc): Timeout is *theoretically* flaky, but the
// pseudo-random choice for select case branches makes it
// practically impossible for it to fail.
`timeout\.func1\(.* \[chan send\]`,
),
}
// GoKer tests from "GoBench: A Benchmark Suite of Real-World Go Concurrency Bugs".
// Refer to testdata/testgoroutineleakprofile/goker/README.md.
//
// This list is curated for tests that are not excessively flaky.
// Some tests are also excluded because they are redundant.
//
// TODO(vsaioc): Some of these might be removable (their patterns may overlap).
gokerTestCases := []testCase{
makeFlakyTest("Cockroach584",
`Cockroach584\.func2\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Cockroach1055",
`Cockroach1055\.func2\(.* \[chan receive\]`,
`Cockroach1055\.func2\.2\(.* \[sync\.WaitGroup\.Wait\]`,
`Cockroach1055\.func2\.1\(.* \[chan receive\]`,
`Cockroach1055\.func2\.1\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Cockroach1462",
`\(\*Stopper_cockroach1462\)\.RunWorker\.func1\(.* \[chan send\]`,
`Cockroach1462\.func2\(.* \[sync\.WaitGroup\.Wait\]`,
),
makeFlakyTest("Cockroach2448",
`\(\*Store_cockroach2448\)\.processRaft\(.* \[select\]`,
`\(\*state_cockroach2448\)\.start\(.* \[select\]`,
),
makeFlakyTest("Cockroach3710",
`\(\*Store_cockroach3710\)\.ForceRaftLogScanAndProcess\(.* \[sync\.RWMutex\.RLock\]`,
`\(\*Store_cockroach3710\)\.processRaft\.func1\(.* \[sync\.RWMutex\.Lock\]`,
),
makeFlakyTest("Cockroach6181",
`testRangeCacheCoalescedRequests_cockroach6181\(.* \[sync\.WaitGroup\.Wait\]`,
`testRangeCacheCoalescedRequests_cockroach6181\.func1\.1\(.* \[sync\.(RW)?Mutex\.Lock\]`,
`testRangeCacheCoalescedRequests_cockroach6181\.func1\.1\(.* \[sync\.RWMutex\.RLock\]`,
),
makeTest("Cockroach7504",
`Cockroach7504\.func2\.1.* \[sync\.Mutex\.Lock\]`,
`Cockroach7504\.func2\.2.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Cockroach9935",
`\(\*loggingT_cockroach9935\)\.outputLogEntry\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Cockroach10214",
`\(*Store_cockroach10214\)\.sendQueuedHeartbeats\(.* \[sync\.Mutex\.Lock\]`,
`\(*Replica_cockroach10214\)\.tick\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Cockroach10790",
`\(\*Replica_cockroach10790\)\.beginCmds\.func1\(.* \[chan receive\]`,
),
makeTest("Cockroach13197",
`\(\*Tx_cockroach13197\)\.awaitDone\(.* \[chan receive\]`,
),
makeTest("Cockroach13755",
`\(\*Rows_cockroach13755\)\.awaitDone\(.* \[chan receive\]`,
),
makeFlakyTest("Cockroach16167",
`Cockroach16167\.func2\(.* \[sync\.RWMutex\.RLock\]`,
`\(\*Executor_cockroach16167\)\.Start\(.* \[sync\.RWMutex\.Lock\]`,
),
makeFlakyTest("Cockroach18101",
`restore_cockroach18101\.func1\(.* \[chan send\]`,
),
makeTest("Cockroach24808",
`Cockroach24808\.func2\(.* \[chan send\]`,
),
makeTest("Cockroach25456",
`Cockroach25456\.func2\(.* \[chan receive\]`,
),
makeTest("Cockroach35073",
`Cockroach35073\.func2.1\(.* \[chan send\]`,
`Cockroach35073\.func2\(.* \[chan send\]`,
),
makeTest("Cockroach35931",
`Cockroach35931\.func2\(.* \[chan send\]`,
),
makeTest("Etcd5509",
`Etcd5509\.func2\(.* \[sync\.RWMutex\.Lock\]`,
),
makeTest("Etcd6708",
`Etcd6708\.func2\(.* \[sync\.RWMutex\.RLock\]`,
),
makeFlakyTest("Etcd6857",
`\(\*node_etcd6857\)\.Status\(.* \[chan send\]`,
),
makeFlakyTest("Etcd6873",
`\(\*watchBroadcasts_etcd6873\)\.stop\(.* \[chan receive\]`,
`newWatchBroadcasts_etcd6873\.func1\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Etcd7492",
`Etcd7492\.func2\(.* \[sync\.WaitGroup\.Wait\]`,
`Etcd7492\.func2\.1\(.* \[chan send\]`,
`\(\*simpleTokenTTLKeeper_etcd7492\)\.run\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Etcd7902",
`doRounds_etcd7902\.func1\(.* \[chan receive\]`,
`doRounds_etcd7902\.func1\(.* \[sync\.Mutex\.Lock\]`,
`runElectionFunc_etcd7902\(.* \[sync\.WaitGroup\.Wait\]`,
),
makeTest("Etcd10492",
`Etcd10492\.func2\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Grpc660",
`\(\*benchmarkClient_grpc660\)\.doCloseLoopUnary\.func1\(.* \[chan send\]`,
),
makeFlakyTest("Grpc795",
`\(\*Server_grpc795\)\.Serve\(.* \[sync\.Mutex\.Lock\]`,
`testServerGracefulStopIdempotent_grpc795\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Grpc862",
`DialContext_grpc862\.func2\(.* \[chan receive\]`),
makeTest("Grpc1275",
`testInflightStreamClosing_grpc1275\.func1\(.* \[chan receive\]`),
makeTest("Grpc1424",
`DialContext_grpc1424\.func1\(.* \[chan receive\]`),
makeFlakyTest("Grpc1460",
`\(\*http2Client_grpc1460\)\.keepalive\(.* \[chan receive\]`,
`\(\*http2Client_grpc1460\)\.NewStream\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Grpc3017",
// grpc/3017 involves a goroutine leak that also simultaneously engages many GC assists.
`Grpc3017\.func2\(.* \[chan receive\]`,
`Grpc3017\.func2\.1\(.* \[sync\.Mutex\.Lock\]`,
`\(\*lbCacheClientConn_grpc3017\)\.RemoveSubConn\.func1\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Hugo3251",
`Hugo3251\.func2\(.* \[sync\.WaitGroup\.Wait\]`,
`Hugo3251\.func2\.1\(.* \[sync\.Mutex\.Lock\]`,
`Hugo3251\.func2\.1\(.* \[sync\.RWMutex\.RLock\]`,
),
makeFlakyTest("Hugo5379",
`\(\*Page_hugo5379\)\.initContent\.func1\.1\(.* \[sync\.Mutex\.Lock\]`,
`pageRenderer_hugo5379\(.* \[sync\.Mutex\.Lock\]`,
`Hugo5379\.func2\(.* \[sync\.WaitGroup\.Wait\]`,
),
makeFlakyTest("Istio16224",
`Istio16224\.func2\(.* \[sync\.Mutex\.Lock\]`,
`\(\*controller_istio16224\)\.Run\(.* \[chan send\]`,
`\(\*controller_istio16224\)\.Run\(.* \[chan receive\]`,
),
makeFlakyTest("Istio17860",
`\(\*agent_istio17860\)\.runWait\(.* \[chan send\]`,
),
makeFlakyTest("Istio18454",
`\(\*Worker_istio18454\)\.Start\.func1\(.* \[chan receive\]`,
`\(\*Worker_istio18454\)\.Start\.func1\(.* \[chan send\]`,
),
// NOTE(vsaioc):
// Kubernetes/1321 is excluded due to a race condition in the original program
// that may, in extremely rare cases, lead to nil pointer dereference crashes.
// (Reproducible even with regular GC). Only kept here for posterity.
//
// makeTest(testCase{name: "Kubernetes1321"},
// `NewMux_kubernetes1321\.gowrap1\(.* \[chan send\]`,
// `testMuxWatcherClose_kubernetes1321\(.* \[sync\.Mutex\.Lock\]`),
makeTest("Kubernetes5316",
`finishRequest_kubernetes5316\.func1\(.* \[chan send\]`,
),
makeFlakyTest("Kubernetes6632",
`\(\*idleAwareFramer_kubernetes6632\)\.monitor\(.* \[sync\.Mutex\.Lock\]`,
`\(\*idleAwareFramer_kubernetes6632\)\.WriteFrame\(.* \[chan send\]`,
),
makeFlakyTest("Kubernetes10182",
`\(\*statusManager_kubernetes10182\)\.Start\.func1\(.* \[sync\.Mutex\.Lock\]`,
`\(\*statusManager_kubernetes10182\)\.SetPodStatus\(.* \[chan send\]`,
),
makeFlakyTest("Kubernetes11298",
`After_kubernetes11298\.func1\(.* \[chan receive\]`,
`After_kubernetes11298\.func1\(.* \[sync\.Cond\.Wait\]`,
`Kubernetes11298\.func2\(.* \[chan receive\]`,
),
makeFlakyTest("Kubernetes13135",
`Util_kubernetes13135\(.* \[sync\.Mutex\.Lock\]`,
`\(\*WatchCache_kubernetes13135\)\.Add\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Kubernetes25331",
`\(\*watchChan_kubernetes25331\)\.run\(.* \[chan send\]`,
),
makeFlakyTest("Kubernetes26980",
`Kubernetes26980\.func2\(.* \[chan receive\]`,
`Kubernetes26980\.func2\.1\(.* \[sync\.Mutex\.Lock\]`,
`\(\*processorListener_kubernetes26980\)\.pop\(.* \[chan receive\]`,
),
makeFlakyTest("Kubernetes30872",
`\(\*DelayingDeliverer_kubernetes30872\)\.StartWithHandler\.func1\(.* \[sync\.Mutex\.Lock\]`,
`\(\*Controller_kubernetes30872\)\.Run\(.* \[sync\.Mutex\.Lock\]`,
`\(\*NamespaceController_kubernetes30872\)\.Run\.func1\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Kubernetes38669",
`\(\*cacheWatcher_kubernetes38669\)\.process\(.* \[chan send\]`,
),
makeFlakyTest("Kubernetes58107",
`\(\*ResourceQuotaController_kubernetes58107\)\.worker\(.* \[sync\.Cond\.Wait\]`,
`\(\*ResourceQuotaController_kubernetes58107\)\.worker\(.* \[sync\.RWMutex\.RLock\]`,
`\(\*ResourceQuotaController_kubernetes58107\)\.Sync\(.* \[sync\.RWMutex\.Lock\]`,
),
makeFlakyTest("Kubernetes62464",
`\(\*manager_kubernetes62464\)\.reconcileState\(.* \[sync\.RWMutex\.RLock\]`,
`\(\*staticPolicy_kubernetes62464\)\.RemoveContainer\(.* \[sync\.(RW)?Mutex\.Lock\]`,
),
makeFlakyTest("Kubernetes70277",
`Kubernetes70277\.func2\(.* \[chan receive\]`,
),
makeFlakyTest("Moby4951",
`\(\*DeviceSet_moby4951\)\.DeleteDevice\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Moby7559",
`\(\*UDPProxy_moby7559\)\.Run\(.* \[sync\.Mutex\.Lock\]`,
),
makeTest("Moby17176",
`testDevmapperLockReleasedDeviceDeletion_moby17176\.func1\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Moby21233",
`\(\*Transfer_moby21233\)\.Watch\.func1\(.* \[chan send\]`,
`\(\*Transfer_moby21233\)\.Watch\.func1\(.* \[select\]`,
`testTransfer_moby21233\(.* \[chan receive\]`,
),
makeTest("Moby25348",
`\(\*Manager_moby25348\)\.init\(.* \[sync\.WaitGroup\.Wait\]`,
),
makeFlakyTest("Moby27782",
`\(\*JSONFileLogger_moby27782\)\.readLogs\(.* \[sync\.Cond\.Wait\]`,
`\(\*Watcher_moby27782\)\.readEvents\(.* \[select\]`,
),
makeFlakyTest("Moby28462",
`monitor_moby28462\(.* \[sync\.Mutex\.Lock\]`,
`\(\*Daemon_moby28462\)\.StateChanged\(.* \[chan send\]`,
),
makeTest("Moby30408",
`Moby30408\.func2\(.* \[chan receive\]`,
`testActive_moby30408\.func1\(.* \[sync\.Cond\.Wait\]`,
),
makeFlakyTest("Moby33781",
`monitor_moby33781\.func1\(.* \[chan send\]`,
),
makeFlakyTest("Moby36114",
`\(\*serviceVM_moby36114\)\.hotAddVHDsAtStart\(.* \[sync\.Mutex\.Lock\]`,
),
makeFlakyTest("Serving2137",
`\(\*Breaker_serving2137\)\.concurrentRequest\.func1\(.* \[chan send\]`,
`\(\*Breaker_serving2137\)\.concurrentRequest\.func1\(.* \[sync\.Mutex\.Lock\]`,
`Serving2137\.func2\(.* \[chan receive\]`,
),
makeTest("Syncthing4829",
`Syncthing4829\.func2\(.* \[sync\.RWMutex\.RLock\]`,
),
makeTest("Syncthing5795",
`\(\*rawConnection_syncthing5795\)\.dispatcherLoop\(.* \[chan receive\]`,
`Syncthing5795\.func2.* \[chan receive\]`,
),
}
// Combine all test cases into a single list.
testCases := append(microTests, stressTestCases...)
testCases = append(testCases, patternTestCases...)
runTests := func(exepath string, testCases []testCase) {
// Build the test program once.
exe, err := buildTestProg(t, exepath)
if err != nil {
t.Fatal(fmt.Sprintf("building testgoroutineleakprofile failed: %v", err))
}
for _, tcase := range testCases {
t.Run(tcase.name, func(t *testing.T) {
t.Parallel()
cmdEnv := []string{
"GODEBUG=asyncpreemptoff=1",
"GOEXPERIMENT=goroutineleakprofile",
}
if tcase.simple {
// If the test is simple, set GOMAXPROCS=1 in order to better
// control the behavior of the scheduler.
cmdEnv = append(cmdEnv, "GOMAXPROCS=1")
}
var output string
for i := 0; i < tcase.repetitions; i++ {
// Run program for one repetition and get runOutput trace.
runOutput, err := runBuiltTestProgErr(t, exe, tcase.name, cmdEnv...)
if len(runOutput) == 0 {
t.Errorf("Test %s produced no output. Is the goroutine leak profile collected?", tcase.name)
}
// Test cases must not end in a non-zero exit code, or otherwise experience a failure to
// actually execute.
if err != nil {
t.Errorf("unexpected failure\noutput:\n%s\n\n", runOutput)
}
output += runOutput + "\n\n"
}
// Extract all the goroutine leaks
foundLeaks := extractLeaks(output)
// If the test case was not expected to produce leaks, but some were reported,
// stop the test immediately. Zero tolerance policy for false positives.
if len(tcase.expectedLeaks)+len(tcase.flakyLeaks) == 0 && len(foundLeaks) > 0 {
t.Errorf("output:\n%s\n\ngoroutines leaks detected in case with no leaks", output)
}
unexpectedLeaks := make([]string, 0, len(foundLeaks))
// Parse every leak and check if it is expected (maybe as a flaky leak).
leaks:
for _, leak := range foundLeaks {
// Check if the leak is expected.
// If it is, check whether it has been encountered before.
var foundNew bool
var leakPattern *regexp.Regexp
for expectedLeak, ok := range tcase.expectedLeaks {
if expectedLeak.MatchString(leak) {
if !ok {
foundNew = true
}
leakPattern = expectedLeak
break
}
}
if foundNew {
// Only bother writing if we found a new leak.
tcase.expectedLeaks[leakPattern] = true
}
if leakPattern == nil {
// We are dealing with a leak not marked as expected.
// Check if it is a flaky leak.
for flakyLeak := range tcase.flakyLeaks {
if flakyLeak.MatchString(leak) {
// The leak is flaky. Carry on to the next line.
continue leaks
}
}
unexpectedLeaks = append(unexpectedLeaks, leak)
}
}
missingLeakStrs := make([]string, 0, len(tcase.expectedLeaks))
for expectedLeak, found := range tcase.expectedLeaks {
if !found {
missingLeakStrs = append(missingLeakStrs, expectedLeak.String())
}
}
var errors []error
if len(unexpectedLeaks) > 0 {
errors = append(errors, fmt.Errorf("unexpected goroutine leaks:\n%s\n", strings.Join(unexpectedLeaks, "\n")))
}
if len(missingLeakStrs) > 0 {
errors = append(errors, fmt.Errorf("missing expected leaks:\n%s\n", strings.Join(missingLeakStrs, ", ")))
}
if len(errors) > 0 {
t.Fatalf("Failed with the following errors:\n%s\n\noutput:\n%s", errors, output)
}
})
}
}
runTests("testgoroutineleakprofile", testCases)
runTests("testgoroutineleakprofile/goker", gokerTestCases)
} | go | github | https://github.com/golang/go | src/runtime/goroutineleakprofile_test.go |
from flask import Flask
application = Flask(__name__) | python | github | https://github.com/pallets/flask | tests/test_apps/cliapp/inner1/__init__.py |
# SPDX-License-Identifier: GPL-2.0-only OR BSD-2-Clause
%YAML 1.2
---
$id: http://devicetree.org/schemas/mfd/nxp,pf1550.yaml#
$schema: http://devicetree.org/meta-schemas/core.yaml#
title: NXP PF1550 Power Management IC
maintainers:
- Samuel Kayode <samuel.kayode@savoirfairelinux.com>
description:
PF1550 PMIC provides battery charging and power supply for low power IoT and
wearable applications. This device consists of an i2c controlled MFD that
includes regulators, battery charging and an onkey/power button.
$ref: /schemas/power/supply/power-supply.yaml
properties:
compatible:
const: nxp,pf1550
reg:
maxItems: 1
interrupts:
maxItems: 1
wakeup-source: true
regulators:
type: object
additionalProperties: false
patternProperties:
"^(ldo[1-3]|sw[1-3]|vrefddr)$":
type: object
$ref: /schemas/regulator/regulator.yaml
description:
regulator configuration for ldo1-3, buck converters(sw1-3)
and DDR termination reference voltage (vrefddr)
unevaluatedProperties: false
monitored-battery:
description: |
A phandle to a monitored battery node that contains a valid value
for:
constant-charge-voltage-max-microvolt.
nxp,thermal-regulation-celsius:
description:
Temperature threshold for thermal regulation of charger in celsius.
enum: [ 80, 95, 110, 125 ]
nxp,min-system-microvolt:
description:
System specific lower limit voltage.
enum: [ 3500000, 3700000, 4300000 ]
nxp,disable-key-power:
type: boolean
description:
Disable power-down using a long key-press. The onkey driver will remove
support for the KEY_POWER key press when triggered using a long press of
the onkey.
required:
- compatible
- reg
- interrupts
unevaluatedProperties: false
examples:
- |
#include <dt-bindings/interrupt-controller/irq.h>
#include <dt-bindings/input/linux-event-codes.h>
battery: battery-cell {
compatible = "simple-battery";
constant-charge-voltage-max-microvolt = <4400000>;
};
i2c {
#address-cells = <1>;
#size-cells = <0>;
pmic@8 {
compatible = "nxp,pf1550";
reg = <0x8>;
interrupt-parent = <&gpio1>;
interrupts = <2 IRQ_TYPE_LEVEL_LOW>;
wakeup-source;
monitored-battery = <&battery>;
nxp,min-system-microvolt = <4300000>;
nxp,thermal-regulation-celsius = <80>;
regulators {
sw1_reg: sw1 {
regulator-name = "sw1";
regulator-min-microvolt = <600000>;
regulator-max-microvolt = <1387500>;
regulator-always-on;
regulator-ramp-delay = <6250>;
regulator-state-mem {
regulator-on-in-suspend;
regulator-suspend-min-microvolt = <1270000>;
};
};
sw2_reg: sw2 {
regulator-name = "sw2";
regulator-min-microvolt = <600000>;
regulator-max-microvolt = <1387500>;
regulator-always-on;
regulator-state-mem {
regulator-on-in-suspend;
};
};
sw3_reg: sw3 {
regulator-name = "sw3";
regulator-min-microvolt = <1800000>;
regulator-max-microvolt = <3300000>;
regulator-always-on;
regulator-state-mem {
regulator-on-in-suspend;
};
};
vldo1_reg: ldo1 {
regulator-name = "ldo1";
regulator-min-microvolt = <750000>;
regulator-max-microvolt = <3300000>;
regulator-always-on;
regulator-state-mem {
regulator-off-in-suspend;
};
};
vldo2_reg: ldo2 {
regulator-name = "ldo2";
regulator-min-microvolt = <1800000>;
regulator-max-microvolt = <3300000>;
regulator-always-on;
};
vldo3_reg: ldo3 {
regulator-name = "ldo3";
regulator-min-microvolt = <750000>;
regulator-max-microvolt = <3300000>;
regulator-always-on;
};
};
};
}; | unknown | github | https://github.com/torvalds/linux | Documentation/devicetree/bindings/mfd/nxp,pf1550.yaml |
# -*- coding: utf-8 -*-
import sys
import glob
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import csv
import re
files_path = sys.argv[1]
print 'files_path', files_path
files = glob.glob('%s/*.txt' % files_path)
import_options = {'separator': ';'}
csv.field_size_limit(1310720)
def get_data(file_name, find_problem_line=False):
print file_name, find_problem_line
with open(file_name, 'rb') as csvfile:
fixed_file = csvfile.read().replace('\r\r\n', ' ').replace('\r\n', '<br/>').replace(';<br/>', ';\n')
fixed_file = re.sub(r';"([0-9a-zA-Z, ]*;)', r';\1', fixed_file)
fixed_file = StringIO(fixed_file)
reader = csv.reader(fixed_file,
delimiter=import_options.get('separator'),
#quotechar = '"',
)
if find_problem_line:
print 'find_problem_line'
lines = ['1', '2', '3', '4', '5']
r = True
while r:
try:
r = reader.next()
lines.pop(0)
lines.append(str(r))
except:
# print 'last lines', '\n'.join(lines)
raise
print 'OK', '\n'.join(lines)
try:
res = list(reader)
except:
if not find_problem_line:
get_data(file_name, find_problem_line=True)
raise
return res
for file_name in files:
data = get_data(file_name)
print data[0] | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Stubouts, mocks and fixtures for the test suite."""
import copy
import datetime
from nova import db
from nova import exception
class FakeModel(object):
"""Stubs out for model."""
def __init__(self, values):
self.values = values
def __getattr__(self, name):
return self.values[name]
def __getitem__(self, key):
if key in self.values:
return self.values[key]
else:
raise NotImplementedError()
def __repr__(self):
return '<FakeModel: %s>' % self.values
def get(self, name):
return self.values[name]
def stub_out(stubs, funcs):
"""Set the stubs in mapping in the db api."""
for func in funcs:
func_name = '_'.join(func.__name__.split('_')[1:])
stubs.Set(db, func_name, func)
stubs.Set(db.api, func_name, func)
fixed_ip_fields = {'id': 0,
'network_id': 0,
'address': '192.168.0.100',
'instance': False,
'instance_uuid': 'eb57d790-fc60-4119-a51a-f2b0913bdc93',
'allocated': False,
'virtual_interface_id': 0,
'virtual_interface': None,
'floating_ips': []}
network_fields = {'id': 0,
'cidr': '192.168.0.0/24',
'netmask': '255.255.255.0',
'cidr_v6': 'dead:beef::/64',
'netmask_v6': '64',
'project_id': 'fake',
'label': 'fake',
'gateway': '192.168.0.1',
'bridge': 'fa0',
'bridge_interface': 'fake_fa0',
'broadcast': '192.168.0.255',
'gateway_v6': 'dead:beef::1',
'dns': '192.168.0.1',
'vlan': None,
'host': None,
'injected': False,
'vpn_public_address': '192.168.0.2'}
flavor_fields = {'id': 0,
'rxtx_cap': 3}
floating_ip_fields = {'id': 0,
'address': '192.168.1.100',
'fixed_ip_id': None,
'fixed_ip': None,
'project_id': None,
'pool': 'nova',
'auto_assigned': False}
virtual_interface_fields = {'id': 0,
'address': 'DE:AD:BE:EF:00:00',
'network_id': 0,
'instance_id': 0,
'network': FakeModel(network_fields)}
fixed_ips = [fixed_ip_fields]
floating_ips = [floating_ip_fields]
virtual_interfacees = [virtual_interface_fields]
networks = [network_fields]
def fake_floating_ip_allocate_address(context, project_id, pool,
auto_assigned=False):
ips = filter(lambda i: i['fixed_ip_id'] is None and
i['project_id'] is None and
i['pool'] == pool,
floating_ips)
if not ips:
raise exception.NoMoreFloatingIps()
ips[0]['project_id'] = project_id
ips[0]['auto_assigned'] = auto_assigned
return FakeModel(ips[0])
def fake_floating_ip_deallocate(context, address):
ips = filter(lambda i: i['address'] == address,
floating_ips)
if ips:
ips[0]['project_id'] = None
ips[0]['auto_assigned'] = False
def fake_floating_ip_disassociate(context, address):
ips = filter(lambda i: i['address'] == address,
floating_ips)
if ips:
fixed_ip_address = None
if ips[0]['fixed_ip']:
fixed_ip_address = ips[0]['fixed_ip']['address']
ips[0]['fixed_ip'] = None
ips[0]['host'] = None
return fixed_ip_address
def fake_floating_ip_fixed_ip_associate(context, floating_address,
fixed_address, host):
float = filter(lambda i: i['address'] == floating_address,
floating_ips)
fixed = filter(lambda i: i['address'] == fixed_address,
fixed_ips)
if float and fixed:
float[0]['fixed_ip'] = fixed[0]
float[0]['fixed_ip_id'] = fixed[0]['id']
float[0]['host'] = host
def fake_floating_ip_get_all_by_host(context, host):
# TODO(jkoelker): Once we get the patches that remove host from
# the floating_ip table, we'll need to stub
# this out
pass
def fake_floating_ip_get_by_address(context, address):
if isinstance(address, FakeModel):
# NOTE(tr3buchet): yo dawg, i heard you like addresses
address = address['address']
ips = filter(lambda i: i['address'] == address,
floating_ips)
if not ips:
raise exception.FloatingIpNotFoundForAddress(address=address)
return FakeModel(ips[0])
def fake_fixed_ip_associate(context, address, instance_id):
ips = filter(lambda i: i['address'] == address,
fixed_ips)
if not ips:
raise exception.NoMoreFixedIps(net='fake_net')
ips[0]['instance'] = True
ips[0]['instance_id'] = instance_id
def fake_fixed_ip_associate_pool(context, network_id, instance_id):
ips = filter(lambda i: (i['network_id'] == network_id or
i['network_id'] is None) and not i['instance'],
fixed_ips)
if not ips:
raise exception.NoMoreFixedIps(net=network_id)
ips[0]['instance'] = True
ips[0]['instance_id'] = instance_id
return ips[0]['address']
def fake_fixed_ip_create(context, values):
ip = dict(fixed_ip_fields)
ip['id'] = max([i['id'] for i in fixed_ips] or [-1]) + 1
for key in values:
ip[key] = values[key]
return ip
def fake_fixed_ip_disassociate(context, address):
ips = filter(lambda i: i['address'] == address,
fixed_ips)
if ips:
ips[0]['instance_id'] = None
ips[0]['instance'] = None
ips[0]['virtual_interface'] = None
ips[0]['virtual_interface_id'] = None
def fake_fixed_ip_disassociate_all_by_timeout(context, host, time):
return 0
def fake_fixed_ip_get_all(context):
return [FakeModel(i) for i in fixed_ips]
def fake_fixed_ip_get_by_instance(context, instance_uuid):
ips = filter(lambda i: i['instance_uuid'] == instance_uuid,
fixed_ips)
return [FakeModel(i) for i in ips]
def fake_fixed_ip_get_by_address(context, address):
ips = filter(lambda i: i['address'] == address,
fixed_ips)
if ips:
return FakeModel(ips[0])
def fake_fixed_ip_update(context, address, values):
ips = filter(lambda i: i['address'] == address,
fixed_ips)
fif = copy.deepcopy(fixed_ip_fields)
if ips:
for key in values:
ips[0][key] = values[key]
if key == 'virtual_interface_id':
vif = filter(lambda x: x['id'] == values[key],
virtual_interfacees)
if not vif:
continue
fif['virtual_interface'] = FakeModel(vif[0])
def fake_flavor_get(context, id):
if flavor_fields['id'] == id:
return FakeModel(flavor_fields)
def fake_virtual_interface_create(context, values):
vif = dict(virtual_interface_fields)
vif['id'] = max([m['id'] for m in virtual_interfacees] or [-1]) + 1
for key in values:
vif[key] = values[key]
return FakeModel(vif)
def fake_virtual_interface_delete_by_instance(context, instance_id):
vif = copy.copy(virtual_interfacees)
addresses = [m for m in vif
if m['instance_id'] == instance_id]
try:
for address in addresses:
vif.remove(address)
except ValueError:
pass
def fake_virtual_interface_get_by_instance(context, instance_id):
return [FakeModel(m) for m in virtual_interfacees
if m['instance_id'] == instance_id]
def fake_virtual_interface_get_by_instance_and_network(context,
instance_id,
network_id):
vif = filter(lambda m: m['instance_id'] == instance_id and
m['network_id'] == network_id,
virtual_interfacees)
if not vif:
return None
return FakeModel(vif[0])
def fake_network_create_safe(context, values):
net = dict(network_fields)
net['id'] = max([n['id'] for n in networks] or [-1]) + 1
for key in values:
net[key] = values[key]
return FakeModel(net)
def fake_network_get(context, network_id):
net = filter(lambda n: n['id'] == network_id, networks)
if not net:
return None
return FakeModel(net[0])
def fake_network_get_all(context):
return [FakeModel(n) for n in networks]
def fake_network_get_all_by_host(context, host):
nets = filter(lambda n: n['host'] == host, networks)
return [FakeModel(n) for n in nets]
def fake_network_set_host(context, network_id, host_id):
nets = filter(lambda n: n['id'] == network_id, networks)
for net in nets:
net['host'] = host_id
return host_id
def fake_network_update(context, network_id, values):
nets = filter(lambda n: n['id'] == network_id, networks)
for net in nets:
for key in values:
net[key] = values[key]
def fake_project_get_networks(context, project_id):
return [FakeModel(n) for n in networks
if n['project_id'] == project_id]
def stub_out_db_network_api(stubs):
funcs = [fake_floating_ip_allocate_address,
fake_floating_ip_deallocate,
fake_floating_ip_disassociate,
fake_floating_ip_fixed_ip_associate,
fake_floating_ip_get_all_by_host,
fake_floating_ip_get_by_address,
fake_fixed_ip_associate,
fake_fixed_ip_associate_pool,
fake_fixed_ip_create,
fake_fixed_ip_disassociate,
fake_fixed_ip_disassociate_all_by_timeout,
fake_fixed_ip_get_all,
fake_fixed_ip_get_by_instance,
fake_fixed_ip_get_by_address,
fake_fixed_ip_update,
fake_flavor_get,
fake_virtual_interface_create,
fake_virtual_interface_delete_by_instance,
fake_virtual_interface_get_by_instance,
fake_virtual_interface_get_by_instance_and_network,
fake_network_create_safe,
fake_network_get,
fake_network_get_all,
fake_network_get_all_by_host,
fake_network_set_host,
fake_network_update,
fake_project_get_networks]
stub_out(stubs, funcs)
def stub_out_db_instance_api(stubs, injected=True):
"""Stubs out the db API for creating Instances."""
def _create_instance_type(**updates):
instance_type = {'id': 2,
'name': 'm1.tiny',
'memory_mb': 512,
'vcpus': 1,
'vcpu_weight': None,
'root_gb': 0,
'ephemeral_gb': 10,
'flavorid': 1,
'rxtx_factor': 1.0,
'swap': 0,
'deleted_at': None,
'created_at': datetime.datetime(2014, 8, 8, 0, 0, 0),
'updated_at': None,
'deleted': False,
'disabled': False,
'is_public': True,
'extra_specs': {},
}
if updates:
instance_type.update(updates)
return instance_type
INSTANCE_TYPES = {
'm1.tiny': _create_instance_type(
id=2,
name='m1.tiny',
memory_mb=512,
vcpus=1,
vcpu_weight=None,
root_gb=0,
ephemeral_gb=10,
flavorid=1,
rxtx_factor=1.0,
swap=0),
'm1.small': _create_instance_type(
id=5,
name='m1.small',
memory_mb=2048,
vcpus=1,
vcpu_weight=None,
root_gb=20,
ephemeral_gb=0,
flavorid=2,
rxtx_factor=1.0,
swap=1024),
'm1.medium': _create_instance_type(
id=1,
name='m1.medium',
memory_mb=4096,
vcpus=2,
vcpu_weight=None,
root_gb=40,
ephemeral_gb=40,
flavorid=3,
rxtx_factor=1.0,
swap=0),
'm1.large': _create_instance_type(
id=3,
name='m1.large',
memory_mb=8192,
vcpus=4,
vcpu_weight=10,
root_gb=80,
ephemeral_gb=80,
flavorid=4,
rxtx_factor=1.0,
swap=0),
'm1.xlarge': _create_instance_type(
id=4,
name='m1.xlarge',
memory_mb=16384,
vcpus=8,
vcpu_weight=None,
root_gb=160,
ephemeral_gb=160,
flavorid=5,
rxtx_factor=1.0,
swap=0)}
fixed_ip_fields = {'address': '10.0.0.3',
'address_v6': 'fe80::a00:3',
'network_id': 'fake_flat'}
def fake_flavor_get_all(context, inactive=0, filters=None):
return INSTANCE_TYPES.values()
def fake_flavor_get_by_name(context, name):
return INSTANCE_TYPES[name]
def fake_flavor_get(context, id):
for name, inst_type in INSTANCE_TYPES.iteritems():
if str(inst_type['id']) == str(id):
return inst_type
return None
def fake_fixed_ip_get_by_instance(context, instance_id):
return [FakeModel(fixed_ip_fields)]
funcs = [fake_flavor_get_all,
fake_flavor_get_by_name,
fake_flavor_get,
fake_fixed_ip_get_by_instance]
stub_out(stubs, funcs) | unknown | codeparrot/codeparrot-clean | ||
import json
import re
from typing import Any, MutableMapping, Optional, Tuple
from zerver.models import SubMessage
def get_widget_data(content: str) -> Tuple[Optional[str], Optional[str]]:
valid_widget_types = ['tictactoe', 'poll', 'todo']
tokens = content.split(' ')
# tokens[0] will always exist
if tokens[0].startswith('/'):
widget_type = tokens[0][1:]
if widget_type in valid_widget_types:
remaining_content = content.replace(tokens[0], '', 1).strip()
extra_data = get_extra_data_from_widget_type(remaining_content, widget_type)
return widget_type, extra_data
return None, None
def get_extra_data_from_widget_type(content: str,
widget_type: Optional[str]) -> Any:
if widget_type == 'poll':
# This is used to extract the question from the poll command.
# The command '/poll question' will pre-set the question in the poll
lines = content.splitlines()
question = ''
options = []
if lines and lines[0]:
question = lines.pop(0).strip()
for line in lines:
# If someone is using the list syntax, we remove it
# before adding an option.
option = re.sub(r'(\s*[-*]?\s*)', '', line.strip(), 1)
if len(option) > 0:
options.append(option)
extra_data = {
'question': question,
'options': options,
}
return extra_data
return None
def do_widget_post_save_actions(message: MutableMapping[str, Any]) -> None:
'''
This code works with the webapp; mobile and other
clients should also start supporting this soon.
'''
content = message['message'].content
sender_id = message['message'].sender_id
message_id = message['message'].id
widget_type = None
extra_data = None
widget_type, extra_data = get_widget_data(content)
widget_content = message.get('widget_content')
if widget_content is not None:
# Note that we validate this data in check_message,
# so we can trust it here.
widget_type = widget_content['widget_type']
extra_data = widget_content['extra_data']
if widget_type:
content = dict(
widget_type=widget_type,
extra_data=extra_data,
)
submessage = SubMessage(
sender_id=sender_id,
message_id=message_id,
msg_type='widget',
content=json.dumps(content),
)
submessage.save()
message['submessages'] = SubMessage.get_raw_db_rows([message_id]) | unknown | codeparrot/codeparrot-clean | ||
import numpy as np
import pytest
from pandas.errors import Pandas4Warning
from pandas import (
Categorical,
CategoricalDtype,
CategoricalIndex,
Index,
)
import pandas._testing as tm
class TestCategoricalIndexConstructors:
def test_construction_disallows_scalar(self):
msg = "must be called with a collection of some kind"
with pytest.raises(TypeError, match=msg):
CategoricalIndex(data=1, categories=list("abcd"), ordered=False)
with pytest.raises(TypeError, match=msg):
CategoricalIndex(categories=list("abcd"), ordered=False)
def test_construction(self):
ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False)
categories = ci.categories
result = Index(ci)
tm.assert_index_equal(result, ci, exact=True)
assert not result.ordered
result = Index(ci.values)
tm.assert_index_equal(result, ci, exact=True)
assert not result.ordered
# empty
result = CategoricalIndex([], categories=categories)
tm.assert_index_equal(result.categories, Index(categories))
tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8"))
assert not result.ordered
# passing categories
result = CategoricalIndex(list("aabbca"), categories=categories)
tm.assert_index_equal(result.categories, Index(categories))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
)
c = Categorical(list("aabbca"))
result = CategoricalIndex(c)
tm.assert_index_equal(result.categories, Index(list("abc")))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
)
assert not result.ordered
result = CategoricalIndex(c, categories=categories)
tm.assert_index_equal(result.categories, Index(categories))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
)
assert not result.ordered
ci = CategoricalIndex(c, categories=list("abcd"))
result = CategoricalIndex(ci)
tm.assert_index_equal(result.categories, Index(categories))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
)
assert not result.ordered
msg = "Constructing a Categorical with a dtype and values containing"
with tm.assert_produces_warning(Pandas4Warning, match=msg):
result = CategoricalIndex(ci, categories=list("ab"))
tm.assert_index_equal(result.categories, Index(list("ab")))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8")
)
assert not result.ordered
with tm.assert_produces_warning(Pandas4Warning, match=msg):
result = CategoricalIndex(ci, categories=list("ab"), ordered=True)
tm.assert_index_equal(result.categories, Index(list("ab")))
tm.assert_numpy_array_equal(
result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8")
)
assert result.ordered
with tm.assert_produces_warning(Pandas4Warning, match=msg):
result = CategoricalIndex(ci, categories=list("ab"), ordered=True)
with tm.assert_produces_warning(Pandas4Warning, match=msg):
expected = CategoricalIndex(
ci, categories=list("ab"), ordered=True, dtype="category"
)
tm.assert_index_equal(result, expected, exact=True)
# turn me to an Index
result = Index(np.array(ci))
assert isinstance(result, Index)
assert not isinstance(result, CategoricalIndex)
def test_construction_with_dtype(self):
# specify dtype
ci = CategoricalIndex(list("aabbca"), categories=list("abc"), ordered=False)
result = Index(np.array(ci), dtype="category")
tm.assert_index_equal(result, ci, exact=True)
result = Index(np.array(ci).tolist(), dtype="category")
tm.assert_index_equal(result, ci, exact=True)
# these are generally only equal when the categories are reordered
ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
result = Index(np.array(ci), dtype="category").reorder_categories(ci.categories)
tm.assert_index_equal(result, ci, exact=True)
# make sure indexes are handled
idx = Index(range(3))
expected = CategoricalIndex([0, 1, 2], categories=idx, ordered=True)
result = CategoricalIndex(idx, categories=idx, ordered=True)
tm.assert_index_equal(result, expected, exact=True)
def test_construction_empty_with_bool_categories(self):
# see GH#22702
cat = CategoricalIndex([], categories=[True, False])
categories = sorted(cat.categories.tolist())
assert categories == [False, True]
def test_construction_with_categorical_dtype(self):
# construction with CategoricalDtype
# GH#18109
data, cats, ordered = "a a b b".split(), "c b a".split(), True
dtype = CategoricalDtype(categories=cats, ordered=ordered)
result = CategoricalIndex(data, dtype=dtype)
expected = CategoricalIndex(data, categories=cats, ordered=ordered)
tm.assert_index_equal(result, expected, exact=True)
# GH#19032
result = Index(data, dtype=dtype)
tm.assert_index_equal(result, expected, exact=True)
# error when combining categories/ordered and dtype kwargs
msg = "Cannot specify `categories` or `ordered` together with `dtype`."
with pytest.raises(ValueError, match=msg):
CategoricalIndex(data, categories=cats, dtype=dtype)
with pytest.raises(ValueError, match=msg):
CategoricalIndex(data, ordered=ordered, dtype=dtype) | python | github | https://github.com/pandas-dev/pandas | pandas/tests/indexes/categorical/test_constructors.py |
"""
This module gathers tree-based methods, including decision, regression and
randomized trees. Single and multi-output problems are both handled.
"""
# Authors: Gilles Louppe <g.louppe@gmail.com>
# Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Brian Holt <bdholt1@gmail.com>
# Noel Dawe <noel@dawe.me>
# Satrajit Gosh <satrajit.ghosh@gmail.com>
# Joly Arnaud <arnaud.v.joly@gmail.com>
# Fares Hedayati <fares.hedayati@gmail.com>
# Nelson Liu <nelson@nelsonliu.me>
#
# License: BSD 3 clause
from __future__ import division
import numbers
from abc import ABCMeta
from abc import abstractmethod
from math import ceil
import numpy as np
from scipy.sparse import issparse
from ..base import BaseEstimator
from ..base import ClassifierMixin
from ..base import RegressorMixin
from ..externals import six
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils import check_array
from ..utils import check_random_state
from ..utils import compute_sample_weight
from ..utils.multiclass import check_classification_targets
from ..exceptions import NotFittedError
from ._criterion import Criterion
from ._splitter import Splitter
from ._tree import DepthFirstTreeBuilder
from ._tree import BestFirstTreeBuilder
from ._tree import Tree
from . import _tree, _splitter, _criterion
__all__ = ["DecisionTreeClassifier",
"DecisionTreeRegressor",
"ExtraTreeClassifier",
"ExtraTreeRegressor"]
# =============================================================================
# Types and constants
# =============================================================================
DTYPE = _tree.DTYPE
DOUBLE = _tree.DOUBLE
CRITERIA_CLF = {"gini": _criterion.Gini, "entropy": _criterion.Entropy}
CRITERIA_REG = {"mse": _criterion.MSE, "friedman_mse": _criterion.FriedmanMSE,
"mae": _criterion.MAE}
DENSE_SPLITTERS = {"best": _splitter.BestSplitter,
"random": _splitter.RandomSplitter}
SPARSE_SPLITTERS = {"best": _splitter.BestSparseSplitter,
"random": _splitter.RandomSparseSplitter}
# =============================================================================
# Base decision tree
# =============================================================================
class BaseDecisionTree(six.with_metaclass(ABCMeta, BaseEstimator,
_LearntSelectorMixin)):
"""Base class for decision trees.
Warning: This class should not be used directly.
Use derived classes instead.
"""
@abstractmethod
def __init__(self,
criterion,
splitter,
max_depth,
min_samples_split,
min_samples_leaf,
min_weight_fraction_leaf,
max_features,
max_leaf_nodes,
random_state,
min_impurity_split,
class_weight=None,
presort=False,
increasing=None,
decreasing=None):
self.criterion = criterion
self.splitter = splitter
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.random_state = random_state
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_split = min_impurity_split
self.class_weight = class_weight
self.presort = presort
self.increasing = increasing
self.decreasing = decreasing
self.n_features_ = None
self.n_outputs_ = None
self.classes_ = None
self.n_classes_ = None
self.tree_ = None
self.max_features_ = None
def fit(self, X, y, sample_weight=None, check_input=True,
X_idx_sorted=None):
"""Build a decision tree from the training set (X, y).
Parameters
----------
X : array-like or sparse matrix, shape = [n_samples, n_features]
The training input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csc_matrix``.
y : array-like, shape = [n_samples] or [n_samples, n_outputs]
The target values (class labels in classification, real numbers in
regression). In the regression case, use ``dtype=np.float64`` and
``order='C'`` for maximum efficiency.
sample_weight : array-like, shape = [n_samples] or None
Sample weights. If None, then samples are equally weighted. Splits
that would create child nodes with net zero or negative weight are
ignored while searching for a split in each node. In the case of
classification, splits are also ignored if they would result in any
single class carrying a negative weight in either child node.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
X_idx_sorted : array-like, shape = [n_samples, n_features], optional
The indexes of the sorted training input samples. If many tree
are grown on the same dataset, this allows the ordering to be
cached between trees. If None, the data will be sorted here.
Don't use this parameter unless you know what to do.
Returns
-------
self : object
Returns self.
"""
random_state = check_random_state(self.random_state)
if check_input:
X = check_array(X, dtype=DTYPE, accept_sparse="csc")
y = check_array(y, ensure_2d=False, dtype=None)
if issparse(X):
X.sort_indices()
if X.indices.dtype != np.intc or X.indptr.dtype != np.intc:
raise ValueError("No support for np.int64 index based "
"sparse matrices")
# Determine output settings
n_samples, self.n_features_ = X.shape
is_classification = isinstance(self, ClassifierMixin)
y = np.atleast_1d(y)
expanded_class_weight = None
if y.ndim == 1:
# reshape is necessary to preserve the data contiguity against vs
# [:, np.newaxis] that does not.
y = np.reshape(y, (-1, 1))
self.n_outputs_ = y.shape[1]
if is_classification:
check_classification_targets(y)
y = np.copy(y)
self.classes_ = []
self.n_classes_ = []
if self.class_weight is not None:
y_original = np.copy(y)
y_encoded = np.zeros(y.shape, dtype=np.int)
for k in range(self.n_outputs_):
classes_k, y_encoded[:, k] = np.unique(y[:, k],
return_inverse=True)
self.classes_.append(classes_k)
self.n_classes_.append(classes_k.shape[0])
y = y_encoded
if self.class_weight is not None:
expanded_class_weight = compute_sample_weight(
self.class_weight, y_original)
else:
self.classes_ = [None] * self.n_outputs_
self.n_classes_ = [1] * self.n_outputs_
self.n_classes_ = np.array(self.n_classes_, dtype=np.intp)
if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
y = np.ascontiguousarray(y, dtype=DOUBLE)
# Check parameters
max_depth = ((2 ** 31) - 1 if self.max_depth is None
else self.max_depth)
max_leaf_nodes = (-1 if self.max_leaf_nodes is None
else self.max_leaf_nodes)
if isinstance(self.min_samples_leaf, (numbers.Integral, np.integer)):
min_samples_leaf = self.min_samples_leaf
else: # float
min_samples_leaf = int(ceil(self.min_samples_leaf * n_samples))
if isinstance(self.min_samples_split, (numbers.Integral, np.integer)):
min_samples_split = self.min_samples_split
else: # float
min_samples_split = int(ceil(self.min_samples_split * n_samples))
min_samples_split = max(2, min_samples_split)
min_samples_split = max(min_samples_split, 2 * min_samples_leaf)
if isinstance(self.max_features, six.string_types):
if self.max_features == "auto":
if is_classification:
max_features = max(1, int(np.sqrt(self.n_features_)))
else:
max_features = self.n_features_
elif self.max_features == "sqrt":
max_features = max(1, int(np.sqrt(self.n_features_)))
elif self.max_features == "log2":
max_features = max(1, int(np.log2(self.n_features_)))
else:
raise ValueError(
'Invalid value for max_features. Allowed string '
'values are "auto", "sqrt" or "log2".')
elif self.max_features is None:
max_features = self.n_features_
elif isinstance(self.max_features, (numbers.Integral, np.integer)):
max_features = self.max_features
else: # float
if self.max_features > 0.0:
max_features = max(1,
int(self.max_features * self.n_features_))
else:
max_features = 0
self.max_features_ = max_features
if len(y) != n_samples:
raise ValueError("Number of labels=%d does not match "
"number of samples=%d" % (len(y), n_samples))
if not (0. < self.min_samples_split <= 1. or
2 <= self.min_samples_split):
raise ValueError("min_samples_split must be in at least 2"
" or in (0, 1], got %s" % min_samples_split)
if not (0. < self.min_samples_leaf <= 0.5 or
1 <= self.min_samples_leaf):
raise ValueError("min_samples_leaf must be at least than 1 "
"or in (0, 0.5], got %s" % min_samples_leaf)
if not 0 <= self.min_weight_fraction_leaf <= 0.5:
raise ValueError("min_weight_fraction_leaf must in [0, 0.5]")
if max_depth <= 0:
raise ValueError("max_depth must be greater than zero. ")
if not (0 < max_features <= self.n_features_):
raise ValueError("max_features must be in (0, n_features]")
if not isinstance(max_leaf_nodes, (numbers.Integral, np.integer)):
raise ValueError("max_leaf_nodes must be integral number but was "
"%r" % max_leaf_nodes)
if -1 < max_leaf_nodes < 2:
raise ValueError(("max_leaf_nodes {0} must be either smaller than "
"0 or larger than 1").format(max_leaf_nodes))
if sample_weight is not None:
if (getattr(sample_weight, "dtype", None) != DOUBLE or
not sample_weight.flags.contiguous):
sample_weight = np.ascontiguousarray(
sample_weight, dtype=DOUBLE)
if len(sample_weight.shape) > 1:
raise ValueError("Sample weights array has more "
"than one dimension: %d" %
len(sample_weight.shape))
if len(sample_weight) != n_samples:
raise ValueError("Number of weights=%d does not match "
"number of samples=%d" %
(len(sample_weight), n_samples))
if expanded_class_weight is not None:
if sample_weight is not None:
sample_weight = sample_weight * expanded_class_weight
else:
sample_weight = expanded_class_weight
# Set min_weight_leaf from min_weight_fraction_leaf
if self.min_weight_fraction_leaf != 0. and sample_weight is not None:
min_weight_leaf = (self.min_weight_fraction_leaf *
np.sum(sample_weight))
else:
min_weight_leaf = 0.
if self.min_impurity_split < 0.:
raise ValueError("min_impurity_split must be greater than or equal "
"to 0")
presort = self.presort
# Allow presort to be 'auto', which means True if the dataset is dense,
# otherwise it will be False.
if self.presort == 'auto' and issparse(X):
presort = False
elif self.presort == 'auto':
presort = True
if presort is True and issparse(X):
raise ValueError("Presorting is not supported for sparse "
"matrices.")
# If multiple trees are built on the same dataset, we only want to
# presort once. Splitters now can accept presorted indices if desired,
# but do not handle any presorting themselves. Ensemble algorithms
# which desire presorting must do presorting themselves and pass that
# matrix into each tree.
if X_idx_sorted is None and presort:
X_idx_sorted = np.asfortranarray(np.argsort(X, axis=0),
dtype=np.int32)
if presort and X_idx_sorted.shape != X.shape:
raise ValueError("The shape of X (X.shape = {}) doesn't match "
"the shape of X_idx_sorted (X_idx_sorted"
".shape = {})".format(X.shape,
X_idx_sorted.shape))
# Build tree
criterion = self.criterion
if not isinstance(criterion, Criterion):
if is_classification:
criterion = CRITERIA_CLF[self.criterion](self.n_outputs_,
self.n_classes_)
else:
criterion = CRITERIA_REG[self.criterion](self.n_outputs_,
n_samples)
SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS
def _encode_monotonic(increasing, decreasing):
if increasing is None: increasing = []
if decreasing is None: decreasing = []
def is_int_in_range(feature):
return isinstance(feature, int) and 0 <= feature < self.n_features_
def is_valid(features):
return (isinstance(features, list) and
all(is_int_in_range(feature) for feature in features))
if not is_valid(increasing):
raise ValueError("increasing should be a list of ints in the range [0,n_features].")
if not is_valid(decreasing):
raise ValueError("decreasing should be a list of ints in the range [0,n_features].")
if increasing and decreasing:
intersection = set(increasing) & set(decreasing)
if intersection:
raise ValueError("The following features cannot be both increasing and decreasing: " + str(list(intersection)))
monotonic = np.zeros(self.n_features_, dtype=np.int32)
if increasing:
for feature in increasing:
monotonic[feature] = 1
if decreasing:
for feature in decreasing:
monotonic[feature] = -1
return monotonic
monotonic = _encode_monotonic(self.increasing, self.decreasing)
splitter = self.splitter
if not isinstance(self.splitter, Splitter):
splitter = SPLITTERS[self.splitter](criterion,
self.max_features_,
min_samples_leaf,
min_weight_leaf,
random_state,
self.presort,
monotonic)
self.tree_ = Tree(self.n_features_, self.n_classes_, self.n_outputs_)
# Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise
if max_leaf_nodes < 0:
builder = DepthFirstTreeBuilder(splitter, min_samples_split,
min_samples_leaf,
min_weight_leaf,
max_depth, self.min_impurity_split)
else:
builder = BestFirstTreeBuilder(splitter, min_samples_split,
min_samples_leaf,
min_weight_leaf,
max_depth,
max_leaf_nodes, self.min_impurity_split)
builder.build(self.tree_, X, y, sample_weight, X_idx_sorted)
if self.n_outputs_ == 1:
self.n_classes_ = self.n_classes_[0]
self.classes_ = self.classes_[0]
return self
def _validate_X_predict(self, X, check_input):
"""Validate X whenever one tries to predict, apply, predict_proba"""
if self.tree_ is None:
raise NotFittedError("Estimator not fitted, "
"call `fit` before exploiting the model.")
if check_input:
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
if issparse(X) and (X.indices.dtype != np.intc or
X.indptr.dtype != np.intc):
raise ValueError("No support for np.int64 index based "
"sparse matrices")
n_features = X.shape[1]
if self.n_features_ != n_features:
raise ValueError("Number of features of the model must "
"match the input. Model n_features is %s and "
"input n_features is %s "
% (self.n_features_, n_features))
return X
def predict(self, X, check_input=True):
"""Predict class or regression value for X.
For a classification model, the predicted class for each sample in X is
returned. For a regression model, the predicted value based on X is
returned.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
Returns
-------
y : array of shape = [n_samples] or [n_samples, n_outputs]
The predicted classes, or the predict values.
"""
X = self._validate_X_predict(X, check_input)
proba = self.tree_.predict(X)
n_samples = X.shape[0]
# Classification
if isinstance(self, ClassifierMixin):
if self.n_outputs_ == 1:
return self.classes_.take(np.argmax(proba, axis=1), axis=0)
else:
predictions = np.zeros((n_samples, self.n_outputs_))
for k in range(self.n_outputs_):
predictions[:, k] = self.classes_[k].take(
np.argmax(proba[:, k], axis=1),
axis=0)
return predictions
# Regression
else:
if self.n_outputs_ == 1:
return proba[:, 0]
else:
return proba[:, :, 0]
def apply(self, X, check_input=True):
"""
Returns the index of the leaf that each sample is predicted as.
.. versionadded:: 0.17
Parameters
----------
X : array_like or sparse matrix, shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
Returns
-------
X_leaves : array_like, shape = [n_samples,]
For each datapoint x in X, return the index of the leaf x
ends up in. Leaves are numbered within
``[0; self.tree_.node_count)``, possibly with gaps in the
numbering.
"""
X = self._validate_X_predict(X, check_input)
return self.tree_.apply(X)
def decision_path(self, X, check_input=True):
"""Return the decision path in the tree
Parameters
----------
X : array_like or sparse matrix, shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
Returns
-------
indicator : sparse csr array, shape = [n_samples, n_nodes]
Return a node indicator matrix where non zero elements
indicates that the samples goes through the nodes.
"""
X = self._validate_X_predict(X, check_input)
return self.tree_.decision_path(X)
@property
def feature_importances_(self):
"""Return the feature importances.
The importance of a feature is computed as the (normalized) total
reduction of the criterion brought by that feature.
It is also known as the Gini importance.
Returns
-------
feature_importances_ : array, shape = [n_features]
"""
if self.tree_ is None:
raise NotFittedError("Estimator not fitted, call `fit` before"
" `feature_importances_`.")
return self.tree_.compute_feature_importances()
# =============================================================================
# Public estimators
# =============================================================================
class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin):
"""A decision tree classifier.
Read more in the :ref:`User Guide <tree>`.
Parameters
----------
criterion : string, optional (default="gini")
The function to measure the quality of a split. Supported criteria are
"gini" for the Gini impurity and "entropy" for the information gain.
splitter : string, optional (default="best")
The strategy used to choose the split at each node. Supported
strategies are "best" to choose the best split and "random" to choose
the best random split.
max_features : int, float, string or None, optional (default=None)
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=sqrt(n_features)`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : int or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the input samples required to be at a
leaf node.
max_leaf_nodes : int or None, optional (default=None)
Grow a tree with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
class_weight : dict, list of dicts, "balanced" or None, optional (default=None)
Weights associated with classes in the form ``{class_label: weight}``.
If not given, all classes are supposed to have weight one. For
multi-output problems, a list of dicts can be provided in the same
order as the columns of y.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
For multi-output, the weights of each column of y will be multiplied.
Note that these weights will be multiplied with sample_weight (passed
through the fit method) if sample_weight is specified.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. A node will split
if its impurity is above the threshold, otherwise it is a leaf.
.. versionadded:: 0.18
presort : bool, optional (default=False)
Whether to presort the data to speed up the finding of best splits in
fitting. For the default settings of a decision tree on large
datasets, setting this to true may slow down the training process.
When using either a smaller dataset or a restricted depth, this may
speed up the training.
increasing : list of ints, optional (default=None)
Indices of features to have a monotonically increasing effect.
decreasing : list of ints, optional (default=None)
Indices of features to have a monotonically decreasing effect.
Attributes
----------
classes_ : array of shape = [n_classes] or a list of such arrays
The classes labels (single output problem),
or a list of arrays of class labels (multi-output problem).
feature_importances_ : array of shape = [n_features]
The feature importances. The higher, the more important the
feature. The importance of a feature is computed as the (normalized)
total reduction of the criterion brought by that feature. It is also
known as the Gini importance [4]_.
max_features_ : int,
The inferred value of max_features.
n_classes_ : int or list
The number of classes (for single output problems),
or a list containing the number of classes for each
output (for multi-output problems).
n_features_ : int
The number of features when ``fit`` is performed.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
tree_ : Tree object
The underlying Tree object.
See also
--------
DecisionTreeRegressor
References
----------
.. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
.. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
and Regression Trees", Wadsworth, Belmont, CA, 1984.
.. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
Learning", Springer, 2009.
.. [4] L. Breiman, and A. Cutler, "Random Forests",
http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
Examples
--------
>>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
... # doctest: +SKIP
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
"""
def __init__(self,
criterion="gini",
splitter="best",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features=None,
random_state=None,
max_leaf_nodes=None,
min_impurity_split=1e-7,
class_weight=None,
presort=False,
increasing=None,
decreasing=None):
super(DecisionTreeClassifier, self).__init__(
criterion=criterion,
splitter=splitter,
max_depth=max_depth,
min_samples_split=min_samples_split,
min_samples_leaf=min_samples_leaf,
min_weight_fraction_leaf=min_weight_fraction_leaf,
max_features=max_features,
max_leaf_nodes=max_leaf_nodes,
class_weight=class_weight,
random_state=random_state,
min_impurity_split=min_impurity_split,
presort=presort,
increasing=increasing,
decreasing=decreasing)
def predict_proba(self, X, check_input=True):
"""Predict class probabilities of the input samples X.
The predicted class probability is the fraction of samples of the same
class in a leaf.
check_input : boolean, (default=True)
Allow to bypass several input checking.
Don't use this parameter unless you know what you do.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
Returns
-------
p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1.
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
X = self._validate_X_predict(X, check_input)
proba = self.tree_.predict(X)
if self.n_outputs_ == 1:
proba = proba[:, :self.n_classes_]
normalizer = proba.sum(axis=1)[:, np.newaxis]
normalizer[normalizer == 0.0] = 1.0
proba /= normalizer
return proba
else:
all_proba = []
for k in range(self.n_outputs_):
proba_k = proba[:, k, :self.n_classes_[k]]
normalizer = proba_k.sum(axis=1)[:, np.newaxis]
normalizer[normalizer == 0.0] = 1.0
proba_k /= normalizer
all_proba.append(proba_k)
return all_proba
def predict_log_proba(self, X):
"""Predict class log-probabilities of the input samples X.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, it will be converted to
``dtype=np.float32`` and if a sparse matrix is provided
to a sparse ``csr_matrix``.
Returns
-------
p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1.
The class log-probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
proba = self.predict_proba(X)
if self.n_outputs_ == 1:
return np.log(proba)
else:
for k in range(self.n_outputs_):
proba[k] = np.log(proba[k])
return proba
class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin):
"""A decision tree regressor.
Read more in the :ref:`User Guide <tree>`.
Parameters
----------
criterion : string, optional (default="mse")
The function to measure the quality of a split. Supported criteria
are "mse" for the mean squared error, which is equal to variance
reduction as feature selection criterion, and "mae" for the mean
absolute error.
.. versionadded:: 0.18
Mean Absolute Error (MAE) criterion.
splitter : string, optional (default="best")
The strategy used to choose the split at each node. Supported
strategies are "best" to choose the best split and "random" to choose
the best random split.
max_features : int, float, string or None, optional (default=None)
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a percentage and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=n_features`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_depth : int or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a percentage and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node:
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a percentage and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the input samples required to be at a
leaf node.
max_leaf_nodes : int or None, optional (default=None)
Grow a tree with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
min_impurity_split : float, optional (default=1e-7)
Threshold for early stopping in tree growth. If the impurity
of a node is below the threshold, the node is a leaf.
.. versionadded:: 0.18
presort : bool, optional (default=False)
Whether to presort the data to speed up the finding of best splits in
fitting. For the default settings of a decision tree on large
datasets, setting this to true may slow down the training process.
When using either a smaller dataset or a restricted depth, this may
speed up the training.
increasing : list of ints, optional (default=None)
Indices of features to have a monotonically increasing effect.
decreasing : list of ints, optional (default=None)
Indices of features to have a monotonically decreasing effect.
Attributes
----------
feature_importances_ : array of shape = [n_features]
The feature importances.
The higher, the more important the feature.
The importance of a feature is computed as the
(normalized) total reduction of the criterion brought
by that feature. It is also known as the Gini importance [4]_.
max_features_ : int,
The inferred value of max_features.
n_features_ : int
The number of features when ``fit`` is performed.
n_outputs_ : int
The number of outputs when ``fit`` is performed.
tree_ : Tree object
The underlying Tree object.
See also
--------
DecisionTreeClassifier
References
----------
.. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
.. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
and Regression Trees", Wadsworth, Belmont, CA, 1984.
.. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
Learning", Springer, 2009.
.. [4] L. Breiman, and A. Cutler, "Random Forests",
http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
Examples
--------
>>> from sklearn.datasets import load_boston
>>> from sklearn.model_selection import cross_val_score
>>> from sklearn.tree import DecisionTreeRegressor
>>> boston = load_boston()
>>> regressor = DecisionTreeRegressor(random_state=0)
>>> cross_val_score(regressor, boston.data, boston.target, cv=10)
... # doctest: +SKIP
...
array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75...,
0.07..., 0.29..., 0.33..., -1.42..., -1.77...])
"""
def __init__(self,
criterion="mse",
splitter="best",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features=None,
random_state=None,
max_leaf_nodes=None,
min_impurity_split=1e-7,
presort=False,
increasing=None,
decreasing=None):
super(DecisionTreeRegressor, self).__init__(
criterion=criterion,
splitter=splitter,
max_depth=max_depth,
min_samples_split=min_samples_split,
min_samples_leaf=min_samples_leaf,
min_weight_fraction_leaf=min_weight_fraction_leaf,
max_features=max_features,
max_leaf_nodes=max_leaf_nodes,
random_state=random_state,
min_impurity_split=min_impurity_split,
presort=presort,
increasing=increasing,
decreasing=decreasing)
class ExtraTreeClassifier(DecisionTreeClassifier):
"""An extremely randomized tree classifier.
Extra-trees differ from classic decision trees in the way they are built.
When looking for the best split to separate the samples of a node into two
groups, random splits are drawn for each of the `max_features` randomly
selected features and the best split among those is chosen. When
`max_features` is set 1, this amounts to building a totally random
decision tree.
Warning: Extra-trees should only be used within ensemble methods.
Read more in the :ref:`User Guide <tree>`.
See also
--------
ExtraTreeRegressor, ExtraTreesClassifier, ExtraTreesRegressor
References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
Machine Learning, 63(1), 3-42, 2006.
"""
def __init__(self,
criterion="gini",
splitter="random",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
random_state=None,
max_leaf_nodes=None,
min_impurity_split=1e-7,
class_weight=None,
increasing=None,
decreasing=None):
super(ExtraTreeClassifier, self).__init__(
criterion=criterion,
splitter=splitter,
max_depth=max_depth,
min_samples_split=min_samples_split,
min_samples_leaf=min_samples_leaf,
min_weight_fraction_leaf=min_weight_fraction_leaf,
max_features=max_features,
max_leaf_nodes=max_leaf_nodes,
class_weight=class_weight,
min_impurity_split=min_impurity_split,
random_state=random_state,
increasing=increasing,
decreasing=decreasing)
class ExtraTreeRegressor(DecisionTreeRegressor):
"""An extremely randomized tree regressor.
Extra-trees differ from classic decision trees in the way they are built.
When looking for the best split to separate the samples of a node into two
groups, random splits are drawn for each of the `max_features` randomly
selected features and the best split among those is chosen. When
`max_features` is set 1, this amounts to building a totally random
decision tree.
Warning: Extra-trees should only be used within ensemble methods.
Read more in the :ref:`User Guide <tree>`.
See also
--------
ExtraTreeClassifier, ExtraTreesClassifier, ExtraTreesRegressor
References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
Machine Learning, 63(1), 3-42, 2006.
"""
def __init__(self,
criterion="mse",
splitter="random",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.,
max_features="auto",
random_state=None,
min_impurity_split=1e-7,
max_leaf_nodes=None,
increasing=None,
decreasing=None):
super(ExtraTreeRegressor, self).__init__(
criterion=criterion,
splitter=splitter,
max_depth=max_depth,
min_samples_split=min_samples_split,
min_samples_leaf=min_samples_leaf,
min_weight_fraction_leaf=min_weight_fraction_leaf,
max_features=max_features,
max_leaf_nodes=max_leaf_nodes,
min_impurity_split=min_impurity_split,
random_state=random_state,
increasing=increasing,
decreasing=decreasing) | unknown | codeparrot/codeparrot-clean | ||
#=========================================================================
# pisa_jr_test.py
#=========================================================================
import pytest
import random
import pisa_encoding
from pymtl import Bits
from PisaSim import PisaSim
from pisa_inst_test_utils import *
#-------------------------------------------------------------------------
# gen_basic_test
#-------------------------------------------------------------------------
def gen_basic_test():
return """
# Use r3 to track the control flow pattern
addiu r3, r0, 0
nop
nop
nop
nop
nop
nop
nop
nop
lui r1, %hi[label_a]
ori r1, r0, %lo[label_a]
jr r1
ori r3, r3, 0b01
nop
nop
nop
nop
nop
nop
nop
nop
label_a:
ori r3, r3, 0b10
# Only the second bit should be set if jump was taken
mtc0 r3, proc2mngr > 0b10
"""
#-------------------------------------------------------------------------
# gen_src_byp_test
#-------------------------------------------------------------------------
def gen_src_byp_test():
return [
gen_jr_src_byp_test( 5 ),
gen_jr_src_byp_test( 4 ),
gen_jr_src_byp_test( 3 ),
gen_jr_src_byp_test( 2 ),
gen_jr_src_byp_test( 1 ),
gen_jr_src_byp_test( 0 ),
]
#-------------------------------------------------------------------------
# gen_jump_test
#-------------------------------------------------------------------------
def gen_jump_test():
return """
# Use r3 to track the control flow pattern
addiu r3, r0, 0
lui r1, %hi[label_a]
ori r1, r0, %lo[label_a]
jr r1 # j -.
# |
ori r3, r3, 0b000001 # |
# |
label_b: # <--+-.
ori r3, r3, 0b000010 # | |
# | |
lui r1, %hi[label_c] # | |
ori r1, r0, %lo[label_c] # | |
jr r1 # j -+-+-.
# | | |
ori r3, r3, 0b000100 # | | |
# | | |
label_a: # <--' | |
ori r3, r3, 0b001000 # | |
# | |
lui r1, %hi[label_b] # | |
ori r1, r0, %lo[label_b] # | |
jr r1 # j ---' |
# |
ori r3, r3, 0b010000 # |
# |
label_c: # <------'
ori r3, r3, 0b100000 #
# Only the second bit should be set if jump was taken
mtc0 r3, proc2mngr > 0b101010
"""
#-------------------------------------------------------------------------
# test_basic
#-------------------------------------------------------------------------
@pytest.mark.parametrize( "name,test", [
asm_test( gen_basic_test ),
asm_test( gen_src_byp_test ),
asm_test( gen_jump_test ),
])
def test( name, test ):
sim = PisaSim( trace_en=True )
sim.load( pisa_encoding.assemble( test() ) )
sim.run() | unknown | codeparrot/codeparrot-clean | ||
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructor’s instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: unique symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: unique symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: unique symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: unique symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: unique symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: unique symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: unique symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: unique symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: unique symbol;
/**
* An Object whose truthy properties are properties that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: unique symbol;
}
interface Symbol {
/**
* Converts a Symbol object to a symbol.
*/
[Symbol.toPrimitive](hint: string): symbol;
readonly [Symbol.toStringTag]: string;
}
interface Array<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof any[]]?: boolean;
};
}
interface ReadonlyArray<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof readonly any[]]?: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
readonly [Symbol.toStringTag]: string;
}
interface WeakMap<K extends WeakKey, V> {
readonly [Symbol.toStringTag]: string;
}
interface Set<T> {
readonly [Symbol.toStringTag]: string;
}
interface WeakSet<T extends WeakKey> {
readonly [Symbol.toStringTag]: string;
}
interface JSON {
readonly [Symbol.toStringTag]: string;
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction {
readonly [Symbol.toStringTag]: string;
}
interface Math {
readonly [Symbol.toStringTag]: string;
}
interface Promise<T> {
readonly [Symbol.toStringTag]: string;
}
interface PromiseConstructor {
readonly [Symbol.species]: PromiseConstructor;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
readonly [Symbol.species]: RegExpConstructor;
}
interface String {
/**
* Matches a string or an object that supports being matched against, and returns an array
* containing the results of that search, or null if no matches are found.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm.
* @param searchValue An object that supports searching for and replacing matches within a string.
* @param replaceValue The replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: string;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int8Array";
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8Array";
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int16Array";
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint16Array";
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int32Array";
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint32Array";
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float32Array";
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float64Array";
}
interface ArrayConstructor {
readonly [Symbol.species]: ArrayConstructor;
}
interface MapConstructor {
readonly [Symbol.species]: MapConstructor;
}
interface SetConstructor {
readonly [Symbol.species]: SetConstructor;
}
interface ArrayBufferConstructor {
readonly [Symbol.species]: ArrayBufferConstructor;
} | typescript | github | https://github.com/microsoft/TypeScript | src/lib/es2015.symbol.wellknown.d.ts |
# encoding: utf-8
import string
EOF = -1
class BaseLexer(object):
EOF = -1
# No Comments, no brackets, braces, parens, but space
SPACE = ' '
UNDERSCORE = '_'
punctuation_marks = '#!"$%&\'*+,-./:;<=>?@\\^`|~'
whitespace_no_break = '\x0b\x0c\t '
german_letters = 'äöüÄÖÜß'
letters = string.ascii_letters + german_letters # a-zA-Z
def __init__(self, input_file):
self._input = input_file
self._input_length = len(self._input)
self._current_position = 0
# prime lookahead
self._current_character = self._input[self._current_position]
def consume(self):
self._current_position += 1
if self._current_position >= self._input_length:
self._current_character = EOF
else:
self._current_character = self._input[self._current_position]
def match(self, expected_character):
if self._current_character == expected_character:
self.consume()
return
raise Exception('Expecting %s but found %s' %
(expected_character, self._current_character))
def is_letter(self, c):
c = str(c)
return c in self.letters
def is_text(self, c):
c = str(c)
return c in (self.letters + self.punctuation_marks + self.SPACE)
def is_digit(self, c):
c = str(c)
return c in string.digits
def is_linebreak(self, c):
c = str(c)
return c in '\r\n'
def is_space(self, c):
c = str(c)
return c in self.whitespace_no_break | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# opensnoop Trace open() syscalls.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: opensnoop [-h] [-t] [-x] [-p PID]
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 17-Sep-2015 Brendan Gregg Created this.
from __future__ import print_function
from bcc import BPF
import argparse
# arguments
examples = """examples:
./opensnoop # trace all open() syscalls
./opensnoop -t # include timestamps
./opensnoop -x # only show failed opens
./opensnoop -p 181 # only trace PID 181
"""
parser = argparse.ArgumentParser(
description="Trace open() syscalls",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("-t", "--timestamp", action="store_true",
help="include timestamp on output")
parser.add_argument("-x", "--failed", action="store_true",
help="only show failed opens")
parser.add_argument("-p", "--pid",
help="trace this PID only")
args = parser.parse_args()
debug = 0
# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
BPF_HASH(args_filename, u32, const char *);
int kprobe__sys_open(struct pt_regs *ctx, const char __user *filename)
{
u32 pid = bpf_get_current_pid_tgid();
FILTER
args_filename.update(&pid, &filename);
return 0;
};
int kretprobe__sys_open(struct pt_regs *ctx)
{
const char **filenamep;
int ret = ctx->ax;
u32 pid = bpf_get_current_pid_tgid();
filenamep = args_filename.lookup(&pid);
if (filenamep == 0) {
// missed entry
return 0;
}
bpf_trace_printk("%d %s\\n", ret, *filenamep);
args_filename.delete(&pid);
return 0;
}
"""
if args.pid:
bpf_text = bpf_text.replace('FILTER',
'if (pid != %s) { return 0; }' % args.pid)
else:
bpf_text = bpf_text.replace('FILTER', '')
if debug:
print(bpf_text)
# initialize BPF
b = BPF(text=bpf_text)
# header
if args.timestamp:
print("%-14s" % ("TIME(s)"), end="")
print("%-6s %-16s %4s %3s %s" % ("PID", "COMM", "FD", "ERR", "PATH"))
start_ts = 0
# format output
while 1:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
(ret_s, filename) = msg.split(" ", 1)
ret = int(ret_s)
if (args.failed and (ret >= 0)):
continue
# split return value into FD and errno columns
if ret >= 0:
fd_s = ret
err = 0
else:
fd_s = "-1"
err = - ret
# print columns
if args.timestamp:
if start_ts == 0:
start_ts = ts
print("%-14.9f" % (ts - start_ts), end="")
print("%-6d %-16s %4s %3s %s" % (pid, task, fd_s, err, filename)) | unknown | codeparrot/codeparrot-clean | ||
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .copy_sink import CopySink
class SqlDWSink(CopySink):
"""A copy activity SQL Data Warehouse sink.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param write_batch_size: Write batch size. Type: integer (or Expression
with resultType integer), minimum: 0.
:type write_batch_size: object
:param write_batch_timeout: Write batch timeout. Type: string (or
Expression with resultType string), pattern:
((\\d+)\\.)?(\\d\\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
:type write_batch_timeout: object
:param sink_retry_count: Sink retry count. Type: integer (or Expression
with resultType integer).
:type sink_retry_count: object
:param sink_retry_wait: Sink retry wait. Type: string (or Expression with
resultType string), pattern:
((\\d+)\\.)?(\\d\\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
:type sink_retry_wait: object
:param type: Constant filled by server.
:type type: str
:param pre_copy_script: SQL pre-copy script. Type: string (or Expression
with resultType string).
:type pre_copy_script: object
:param allow_poly_base: Indicates to use PolyBase to copy data into SQL
Data Warehouse when applicable. Type: boolean (or Expression with
resultType boolean).
:type allow_poly_base: object
:param poly_base_settings: Specifies PolyBase-related settings when
allowPolyBase is true.
:type poly_base_settings: ~azure.mgmt.datafactory.models.PolybaseSettings
"""
_validation = {
'type': {'required': True},
}
_attribute_map = {
'additional_properties': {'key': '', 'type': '{object}'},
'write_batch_size': {'key': 'writeBatchSize', 'type': 'object'},
'write_batch_timeout': {'key': 'writeBatchTimeout', 'type': 'object'},
'sink_retry_count': {'key': 'sinkRetryCount', 'type': 'object'},
'sink_retry_wait': {'key': 'sinkRetryWait', 'type': 'object'},
'type': {'key': 'type', 'type': 'str'},
'pre_copy_script': {'key': 'preCopyScript', 'type': 'object'},
'allow_poly_base': {'key': 'allowPolyBase', 'type': 'object'},
'poly_base_settings': {'key': 'polyBaseSettings', 'type': 'PolybaseSettings'},
}
def __init__(self, additional_properties=None, write_batch_size=None, write_batch_timeout=None, sink_retry_count=None, sink_retry_wait=None, pre_copy_script=None, allow_poly_base=None, poly_base_settings=None):
super(SqlDWSink, self).__init__(additional_properties=additional_properties, write_batch_size=write_batch_size, write_batch_timeout=write_batch_timeout, sink_retry_count=sink_retry_count, sink_retry_wait=sink_retry_wait)
self.pre_copy_script = pre_copy_script
self.allow_poly_base = allow_poly_base
self.poly_base_settings = poly_base_settings
self.type = 'SqlDWSink' | unknown | codeparrot/codeparrot-clean | ||
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.adapter;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
/**
* Interface allowing extension to the Spring AOP framework to allow
* handling of new Advisors and Advice types.
*
* <p>Implementing objects can create AOP Alliance Interceptors from
* custom advice types, enabling these advice types to be used
* in the Spring AOP framework, which uses interception under the covers.
*
* <p>There is no need for most Spring users to implement this interface;
* do so only if you need to introduce more Advisor or Advice types to Spring.
*
* @author Rod Johnson
*/
public interface AdvisorAdapter {
/**
* Does this adapter understand this advice object? Is it valid to
* invoke the {@code getInterceptors} method with an Advisor that
* contains this advice as an argument?
* @param advice an Advice such as a BeforeAdvice
* @return whether this adapter understands the given advice object
* @see #getInterceptor(org.springframework.aop.Advisor)
* @see org.springframework.aop.BeforeAdvice
*/
boolean supportsAdvice(Advice advice);
/**
* Return an AOP Alliance MethodInterceptor exposing the behavior of
* the given advice to an interception-based AOP framework.
* <p>Don't worry about any Pointcut contained in the Advisor;
* the AOP framework will take care of checking the pointcut.
* @param advisor the Advisor. The supportsAdvice() method must have
* returned true on this object
* @return an AOP Alliance interceptor for this Advisor. There's
* no need to cache instances for efficiency, as the AOP framework
* caches advice chains.
*/
MethodInterceptor getInterceptor(Advisor advisor);
} | java | github | https://github.com/spring-projects/spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/adapter/AdvisorAdapter.java |
<?php
namespace Illuminate\Foundation;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
class Mix
{
/**
* Get the path to a versioned Mix file.
*
* @param string $path
* @param string $manifestDirectory
* @return \Illuminate\Support\HtmlString|string
*
* @throws \Illuminate\Foundation\MixManifestNotFoundException|\Illuminate\Foundation\MixFileNotFoundException
*/
public function __invoke($path, $manifestDirectory = '')
{
static $manifests = [];
if (! str_starts_with($path, '/')) {
$path = "/{$path}";
}
if ($manifestDirectory && ! str_starts_with($manifestDirectory, '/')) {
$manifestDirectory = "/{$manifestDirectory}";
}
if (is_file(public_path($manifestDirectory.'/hot'))) {
$url = rtrim(file_get_contents(public_path($manifestDirectory.'/hot')));
$customUrl = app('config')->get('app.mix_hot_proxy_url');
if (! empty($customUrl)) {
return new HtmlString("{$customUrl}{$path}");
}
if (Str::startsWith($url, ['http://', 'https://'])) {
return new HtmlString(Str::after($url, ':').$path);
}
return new HtmlString("//localhost:8080{$path}");
}
$manifestPath = public_path($manifestDirectory.'/mix-manifest.json');
if (! isset($manifests[$manifestPath])) {
if (! is_file($manifestPath)) {
throw new MixManifestNotFoundException("Mix manifest not found at: {$manifestPath}");
}
$manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
}
$manifest = $manifests[$manifestPath];
if (! isset($manifest[$path])) {
$exception = new MixFileNotFoundException("Unable to locate Mix file: {$path}.");
if (! app('config')->get('app.debug')) {
report($exception);
return $path;
} else {
throw $exception;
}
}
return new HtmlString(app('config')->get('app.mix_url').$manifestDirectory.$manifest[$path]);
}
} | php | github | https://github.com/laravel/framework | src/Illuminate/Foundation/Mix.php |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import delivery
import partner
import sale
import stock
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from zope.interface import implements, Interface, Attribute
from twisted.internet.protocol import Protocol, ServerFactory, ClientFactory, \
connectionDone
from twisted.internet import defer
from twisted.protocols import basic
from twisted.python import log
from twisted.web import server, resource, http
from thrift.transport import TTransport
from cStringIO import StringIO
class TMessageSenderTransport(TTransport.TTransportBase):
def __init__(self):
self.__wbuf = StringIO()
def write(self, buf):
self.__wbuf.write(buf)
def flush(self):
msg = self.__wbuf.getvalue()
self.__wbuf = StringIO()
self.sendMessage(msg)
def sendMessage(self, message):
raise NotImplementedError
class TCallbackTransport(TMessageSenderTransport):
def __init__(self, func):
TMessageSenderTransport.__init__(self)
self.func = func
def sendMessage(self, message):
self.func(message)
class ThriftClientProtocol(basic.Int32StringReceiver):
MAX_LENGTH = 2 ** 31 - 1
def __init__(self, client_class, iprot_factory, oprot_factory=None):
self._client_class = client_class
self._iprot_factory = iprot_factory
if oprot_factory is None:
self._oprot_factory = iprot_factory
else:
self._oprot_factory = oprot_factory
self.recv_map = {}
self.started = defer.Deferred()
def dispatch(self, msg):
self.sendString(msg)
def connectionMade(self):
tmo = TCallbackTransport(self.dispatch)
self.client = self._client_class(tmo, self._oprot_factory)
self.started.callback(self.client)
def connectionLost(self, reason=connectionDone):
for k,v in self.client._reqs.iteritems():
tex = TTransport.TTransportException(
type=TTransport.TTransportException.END_OF_FILE,
message='Connection closed')
v.errback(tex)
def stringReceived(self, frame):
tr = TTransport.TMemoryBuffer(frame)
iprot = self._iprot_factory.getProtocol(tr)
(fname, mtype, rseqid) = iprot.readMessageBegin()
try:
method = self.recv_map[fname]
except KeyError:
method = getattr(self.client, 'recv_' + fname)
self.recv_map[fname] = method
method(iprot, mtype, rseqid)
class ThriftServerProtocol(basic.Int32StringReceiver):
MAX_LENGTH = 2 ** 31 - 1
def dispatch(self, msg):
self.sendString(msg)
def processError(self, error):
self.transport.loseConnection()
def processOk(self, _, tmo):
msg = tmo.getvalue()
if len(msg) > 0:
self.dispatch(msg)
def stringReceived(self, frame):
tmi = TTransport.TMemoryBuffer(frame)
tmo = TTransport.TMemoryBuffer()
iprot = self.factory.iprot_factory.getProtocol(tmi)
oprot = self.factory.oprot_factory.getProtocol(tmo)
d = self.factory.processor.process(iprot, oprot)
d.addCallbacks(self.processOk, self.processError,
callbackArgs=(tmo,))
class IThriftServerFactory(Interface):
processor = Attribute("Thrift processor")
iprot_factory = Attribute("Input protocol factory")
oprot_factory = Attribute("Output protocol factory")
class IThriftClientFactory(Interface):
client_class = Attribute("Thrift client class")
iprot_factory = Attribute("Input protocol factory")
oprot_factory = Attribute("Output protocol factory")
class ThriftServerFactory(ServerFactory):
implements(IThriftServerFactory)
protocol = ThriftServerProtocol
def __init__(self, processor, iprot_factory, oprot_factory=None):
self.processor = processor
self.iprot_factory = iprot_factory
if oprot_factory is None:
self.oprot_factory = iprot_factory
else:
self.oprot_factory = oprot_factory
class ThriftClientFactory(ClientFactory):
implements(IThriftClientFactory)
protocol = ThriftClientProtocol
def __init__(self, client_class, iprot_factory, oprot_factory=None):
self.client_class = client_class
self.iprot_factory = iprot_factory
if oprot_factory is None:
self.oprot_factory = iprot_factory
else:
self.oprot_factory = oprot_factory
def buildProtocol(self, addr):
p = self.protocol(self.client_class, self.iprot_factory,
self.oprot_factory)
p.factory = self
return p
class ThriftResource(resource.Resource):
allowedMethods = ('POST',)
def __init__(self, processor, inputProtocolFactory,
outputProtocolFactory=None):
resource.Resource.__init__(self)
self.inputProtocolFactory = inputProtocolFactory
if outputProtocolFactory is None:
self.outputProtocolFactory = inputProtocolFactory
else:
self.outputProtocolFactory = outputProtocolFactory
self.processor = processor
def getChild(self, path, request):
return self
def _cbProcess(self, _, request, tmo):
msg = tmo.getvalue()
request.setResponseCode(http.OK)
request.setHeader("content-type", "application/x-thrift")
request.write(msg)
request.finish()
def render_POST(self, request):
request.content.seek(0, 0)
data = request.content.read()
tmi = TTransport.TMemoryBuffer(data)
tmo = TTransport.TMemoryBuffer()
iprot = self.inputProtocolFactory.getProtocol(tmi)
oprot = self.outputProtocolFactory.getProtocol(tmo)
d = self.processor.process(iprot, oprot)
d.addCallback(self._cbProcess, request, tmo)
return server.NOT_DONE_YET | unknown | codeparrot/codeparrot-clean | ||
{
"REMOVE": {
"summary": "Stops monitoring.",
"complexity": "O(1)",
"group": "sentinel",
"since": "2.8.4",
"arity": 3,
"container": "SENTINEL",
"function": "sentinelCommand",
"command_flags": [
"ADMIN",
"SENTINEL",
"ONLY_SENTINEL"
],
"reply_schema": {
"const": "OK"
},
"arguments": [
{
"name": "master-name",
"type": "string"
}
]
}
} | json | github | https://github.com/redis/redis | src/commands/sentinel-remove.json |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import pytest
import airflow
from airflow.exceptions import AirflowException
def test_deprecated_exception():
from airflow.utils.deprecation_tools import DeprecatedImportWarning
warning_pattern = "Import 'AirflowException' directly from the airflow module is deprecated"
with pytest.warns(DeprecatedImportWarning, match=warning_pattern):
# If there is no warning, then most possible it imported somewhere else.
assert getattr(airflow, "AirflowException") is AirflowException | python | github | https://github.com/apache/airflow | airflow-core/tests/unit/core/test_airflow_module.py |
# Fluorescence Analysis
import os
import cv2
import numpy as np
import pandas as pd
from plotnine import ggplot, geom_label, aes, geom_line
from plantcv.plantcv import print_image
from plantcv.plantcv import plot_image
from plantcv.plantcv import fatal_error
from plantcv.plantcv import params
from plantcv.plantcv import outputs
def analyze_fvfm(fdark, fmin, fmax, mask, bins=256, label="default"):
"""Analyze PSII camera images.
Inputs:
fdark = grayscale fdark image
fmin = grayscale fmin image
fmax = grayscale fmax image
mask = mask of plant (binary, single channel)
bins = number of bins (1 to 256 for 8-bit; 1 to 65,536 for 16-bit; default is 256)
label = optional label parameter, modifies the variable name of observations recorded
Returns:
analysis_images = list of images (fv image and fvfm histogram image)
:param fdark: numpy.ndarray
:param fmin: numpy.ndarray
:param fmax: numpy.ndarray
:param mask: numpy.ndarray
:param bins: int
:param label: str
:return analysis_images: numpy.ndarray
"""
# Auto-increment the device counter
params.device += 1
# Check that fdark, fmin, and fmax are grayscale (single channel)
if not all(len(np.shape(i)) == 2 for i in [fdark, fmin, fmax]):
fatal_error("The fdark, fmin, and fmax images must be grayscale images.")
# QC Fdark Image
fdark_mask = cv2.bitwise_and(fdark, fdark, mask=mask)
if np.amax(fdark_mask) > 2000:
qc_fdark = False
else:
qc_fdark = True
# Mask Fmin and Fmax Image
fmin_mask = cv2.bitwise_and(fmin, fmin, mask=mask)
fmax_mask = cv2.bitwise_and(fmax, fmax, mask=mask)
# Calculate Fvariable, where Fv = Fmax - Fmin (masked)
fv = np.subtract(fmax_mask, fmin_mask)
# When Fmin is greater than Fmax, a negative value is returned.
# Because the data type is unsigned integers, negative values roll over, resulting in nonsensical values
# Wherever Fmin is greater than Fmax, set Fv to zero
fv[np.where(fmax_mask < fmin_mask)] = 0
analysis_images = []
# Calculate Fv/Fm (Fvariable / Fmax) where Fmax is greater than zero
# By definition above, wherever Fmax is zero, Fvariable will also be zero
# To calculate the divisions properly we need to change from unit16 to float64 data types
fvfm = fv.astype(np.float64)
analysis_images.append(fvfm)
fmax_flt = fmax_mask.astype(np.float64)
fvfm[np.where(fmax_mask > 0)] /= fmax_flt[np.where(fmax_mask > 0)]
# Calculate the median Fv/Fm value for non-zero pixels
fvfm_median = np.median(fvfm[np.where(fvfm > 0)])
# Calculate the histogram of Fv/Fm non-zero values
fvfm_hist, fvfm_bins = np.histogram(fvfm[np.where(fvfm > 0)], bins, range=(0, 1))
# fvfm_bins is a bins + 1 length list of bin endpoints, so we need to calculate bin midpoints so that
# the we have a one-to-one list of x (FvFm) and y (frequency) values.
# To do this we add half the bin width to each lower bin edge x-value
midpoints = fvfm_bins[:-1] + 0.5 * np.diff(fvfm_bins)
# Calculate which non-zero bin has the maximum Fv/Fm value
max_bin = midpoints[np.argmax(fvfm_hist)]
# Create a dataframe
dataset = pd.DataFrame({'Plant Pixels': fvfm_hist, 'Fv/Fm': midpoints})
# Make the histogram figure using plotnine
fvfm_hist_fig = (ggplot(data=dataset, mapping=aes(x='Fv/Fm', y='Plant Pixels'))
+ geom_line(color='green', show_legend=True)
+ geom_label(label='Peak Bin Value: ' + str(max_bin),
x=.15, y=205, size=8, color='green'))
analysis_images.append(fvfm_hist_fig)
if params.debug == 'print':
print_image(fmin_mask, os.path.join(params.debug_outdir, str(params.device) + '_fmin_mask.png'))
print_image(fmax_mask, os.path.join(params.debug_outdir, str(params.device) + '_fmax_mask.png'))
print_image(fv, os.path.join(params.debug_outdir, str(params.device) + '_fv_convert.png'))
fvfm_hist_fig.save(os.path.join(params.debug_outdir, str(params.device) + '_fv_hist.png'), verbose=False)
elif params.debug == 'plot':
plot_image(fmin_mask, cmap='gray')
plot_image(fmax_mask, cmap='gray')
plot_image(fv, cmap='gray')
print(fvfm_hist_fig)
outputs.add_observation(sample=label, variable='fvfm_hist', trait='Fv/Fm frequencies',
method='plantcv.plantcv.fluor_fvfm', scale='none', datatype=list,
value=fvfm_hist.tolist(), label=np.around(midpoints, decimals=len(str(bins))).tolist())
outputs.add_observation(sample=label, variable='fvfm_hist_peak', trait='peak Fv/Fm value',
method='plantcv.plantcv.fluor_fvfm', scale='none', datatype=float,
value=float(max_bin), label='none')
outputs.add_observation(sample=label, variable='fvfm_median', trait='Fv/Fm median',
method='plantcv.plantcv.fluor_fvfm', scale='none', datatype=float,
value=float(np.around(fvfm_median, decimals=4)), label='none')
outputs.add_observation(sample=label, variable='fdark_passed_qc', trait='Fdark passed QC',
method='plantcv.plantcv.fluor_fvfm', scale='none', datatype=bool,
value=qc_fdark, label='none')
# Store images
outputs.images.append(analysis_images)
return analysis_images | unknown | codeparrot/codeparrot-clean | ||
"""
.. _tut-sensors-time-freq:
============================================
Frequency and time-frequency sensor analysis
============================================
The objective is to show you how to explore the spectral content
of your data (frequency and time-frequency). Here we'll work on Epochs.
We will use this dataset: :ref:`somato-dataset`. It contains so-called event
related synchronizations (ERS) / desynchronizations (ERD) in the beta band.
""" # noqa: E501
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Richard Höchenberger <richard.hoechenberger@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet, psd_multitaper, psd_welch
from mne.datasets import somato
###############################################################################
# Set parameters
data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
'sub-{}_task-{}_meg.fif'.format(subject, task))
# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
# picks MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False)
# Construct Epochs
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6),
preload=True)
epochs.resample(200., npad='auto') # resample to reduce computation time
###############################################################################
# Frequency analysis
# ------------------
#
# We start by exploring the frequence content of our epochs.
###############################################################################
# Let's first check out all channel types by averaging across epochs.
epochs.plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False)
###############################################################################
# Now let's take a look at the spatial distributions of the PSD.
epochs.plot_psd_topomap(ch_type='grad', normalize=True)
###############################################################################
# Alternatively, you can also create PSDs from Epochs objects with functions
# that start with ``psd_`` such as
# :func:`mne.time_frequency.psd_multitaper` and
# :func:`mne.time_frequency.psd_welch`.
f, ax = plt.subplots()
psds, freqs = psd_multitaper(epochs, fmin=2, fmax=40, n_jobs=1)
psds = 10. * np.log10(psds)
psds_mean = psds.mean(0).mean(0)
psds_std = psds.mean(0).std(0)
ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
color='k', alpha=.5)
ax.set(title='Multitaper PSD (gradiometers)', xlabel='Frequency (Hz)',
ylabel='Power Spectral Density (dB)')
plt.show()
###############################################################################
# Notably, :func:`mne.time_frequency.psd_welch` supports the keyword argument
# ``average``, which specifies how to estimate the PSD based on the individual
# windowed segments. The default is ``average='mean'``, which simply calculates
# the arithmetic mean across segments. Specifying ``average='median'``, in
# contrast, returns the PSD based on the median of the segments (corrected for
# bias relative to the mean), which is a more robust measure.
# Estimate PSDs based on "mean" and "median" averaging for comparison.
kwargs = dict(fmin=2, fmax=40, n_jobs=1)
psds_welch_mean, freqs_mean = psd_welch(epochs, average='mean', **kwargs)
psds_welch_median, freqs_median = psd_welch(epochs, average='median', **kwargs)
# Convert power to dB scale.
psds_welch_mean = 10 * np.log10(psds_welch_mean)
psds_welch_median = 10 * np.log10(psds_welch_median)
# We will only plot the PSD for a single sensor in the first epoch.
ch_name = 'MEG 0122'
ch_idx = epochs.info['ch_names'].index(ch_name)
epo_idx = 0
_, ax = plt.subplots()
ax.plot(freqs_mean, psds_welch_mean[epo_idx, ch_idx, :], color='k',
ls='-', label='mean of segments')
ax.plot(freqs_median, psds_welch_median[epo_idx, ch_idx, :], color='k',
ls='--', label='median of segments')
ax.set(title='Welch PSD ({}, Epoch {})'.format(ch_name, epo_idx),
xlabel='Frequency (Hz)', ylabel='Power Spectral Density (dB)')
ax.legend(loc='upper right')
plt.show()
###############################################################################
# Lastly, we can also retrieve the unaggregated segments by passing
# ``average=None`` to :func:`mne.time_frequency.psd_welch`. The dimensions of
# the returned array are ``(n_epochs, n_sensors, n_freqs, n_segments)``.
psds_welch_unagg, freqs_unagg = psd_welch(epochs, average=None, **kwargs)
print(psds_welch_unagg.shape)
###############################################################################
# .. _inter-trial-coherence:
#
# Time-frequency analysis: power and inter-trial coherence
# --------------------------------------------------------
#
# We now compute time-frequency representations (TFRs) from our Epochs.
# We'll look at power and inter-trial coherence (ITC).
#
# To this we'll use the function :func:`mne.time_frequency.tfr_morlet`
# but you can also use :func:`mne.time_frequency.tfr_multitaper`
# or :func:`mne.time_frequency.tfr_stockwell`.
#
# .. note::
# The ``decim`` parameter reduces the sampling rate of the time-frequency
# decomposition by the defined factor. This is usually done to reduce
# memory usage. For more information refer to the documentation of
# :func:`mne.time_frequency.tfr_morlet`.
#
# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2. # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
return_itc=True, decim=3, n_jobs=1)
###############################################################################
# Inspect power
# -------------
#
# .. note::
# The generated figures are interactive. In the topo you can click
# on an image to visualize the data for one sensor.
# You can also select a portion in the time-frequency plane to
# obtain a topomap for a certain time-frequency region.
power.plot_topo(baseline=(-0.5, 0), mode='logratio', title='Average power')
power.plot([82], baseline=(-0.5, 0), mode='logratio', title=power.ch_names[82])
fig, axis = plt.subplots(1, 2, figsize=(7, 4))
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=8, fmax=12,
baseline=(-0.5, 0), mode='logratio', axes=axis[0],
title='Alpha', show=False)
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=13, fmax=25,
baseline=(-0.5, 0), mode='logratio', axes=axis[1],
title='Beta', show=False)
mne.viz.tight_layout()
plt.show()
###############################################################################
# Joint Plot
# ----------
# You can also create a joint plot showing both the aggregated TFR
# across channels and topomaps at specific times and frequencies to obtain
# a quick overview regarding oscillatory effects across time and space.
power.plot_joint(baseline=(-0.5, 0), mode='mean', tmin=-.5, tmax=2,
timefreqs=[(.5, 10), (1.3, 8)])
###############################################################################
# Inspect ITC
# -----------
itc.plot_topo(title='Inter-Trial coherence', vmin=0., vmax=1., cmap='Reds')
###############################################################################
# .. note::
# Baseline correction can be applied to power or done in plots.
# To illustrate the baseline correction in plots, the next line is
# commented power.apply_baseline(baseline=(-0.5, 0), mode='logratio')
#
# Exercise
# --------
#
# - Visualize the inter-trial coherence values as topomaps as done with
# power. | unknown | codeparrot/codeparrot-clean | ||
# Copyright (C) 2004-2009 Bastian Kleineidam
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Test miscellaneous html tag parsing and URL types
"""
from tests import need_network
from . import LinkCheckTest
class TestMisc(LinkCheckTest):
"""
Test misc link types.
"""
@need_network
def test_misc(self):
self.file_test("misc.html")
def test_html5(self):
self.file_test("html5.html")
def test_utf8(self):
self.file_test("utf8.html")
@need_network
def test_archive(self):
self.file_test("archive.html")
@need_network
def test_itms_services(self):
url = "itms-services:?action=download-manifest&url=http://www.example.com/"
resultlines = [
"url %s" % url,
"cache key %s" % url,
"real url %s" % url,
"valid",
"url http://www.example.com/",
"cache key http://www.example.com/",
"real url http://www.example.com/",
"valid",
]
self.direct(url, resultlines, recursionlevel=1) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit Tests for `hbase_wraqpper` module.
"""
from mock import Mock
import pytest
from HBaseBoard.hbase_wrapper import HBaseWrapper
@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
monkeypatch.setattr("happybase.Connection", Mock())
@pytest.mark.unittest
class TestHBaseWrapper(object):
def setup(self):
self.hb_wrapper = HBaseWrapper()
self.hb_wrapper.hbase_con = Mock()
def test_default_table_creation(self):
self.hb_wrapper.create_default_table("test_table")
self.hb_wrapper.hbase_con.create_table.assert_called_with(
"test_table", dict(cf=dict()))
def test_create_table_with_schema(self):
cf_dict = dict(cf1=dict(), cf2=dict())
self.hb_wrapper.create_default_table("test_table", cf_dict)
self.hb_wrapper.hbase_con.create_table.assert_called_with(
"test_table", cf_dict)
def test_get_table_returns_table(self):
table_name = "test_table"
self.hb_wrapper.hbase_con.tables.return_value = [table_name]
self.hb_wrapper.get_table(table_name)
self.hb_wrapper.hbase_con.table.assert_called_with(table_name)
def test_get_table_raises_error_if_table_doesnt_exist(self):
self.hb_wrapper.hbase_con.tables.return_value = ["some_table"]
with pytest.raises(ValueError):
self.hb_wrapper.get_table("new_table")
def test_get_table_list(self):
self.hb_wrapper.hbase_con.tables.return_value = ["table_name"]
assert ["table_name"] == self.hb_wrapper.get_tables_list()
def test_clear_all_tables(self):
self.hb_wrapper.hbase_con.tables.return_value = [
"test_table1", "test_table2"
]
self.hb_wrapper.delete_all_tables()
assert 2 == self.hb_wrapper.hbase_con.delete_table.call_count
self.hb_wrapper.hbase_con.delete_table.assert_any_call(
"test_table1", disable=True)
self.hb_wrapper.hbase_con.delete_table.assert_any_call(
"test_table2", disable=True) | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) 2003-2006 Sylvain Thenault (thenault@gmail.com).
# Copyright (c) 2003-2011 LOGILAB S.A. (Paris, FRANCE).
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""HTML reporter"""
import sys
from cgi import escape
from logilab.common.ureports import HTMLWriter, Section, Table
from pylint.interfaces import IReporter
from pylint.reporters import BaseReporter
class HTMLReporter(BaseReporter):
"""report messages and layouts in HTML"""
__implements__ = IReporter
extension = 'html'
def __init__(self, output=sys.stdout):
BaseReporter.__init__(self, output)
self.msgs = []
def add_message(self, msg_id, location, msg):
"""manage message of different type and in the context of path"""
module, obj, line, col_offset = location[1:]
if self.include_ids:
sigle = msg_id
else:
sigle = msg_id[0]
self.msgs += [sigle, module, obj, str(line), str(col_offset), escape(msg)]
def set_output(self, output=None):
"""set output stream
messages buffered for old output is processed first"""
if self.out and self.msgs:
self._display(Section())
BaseReporter.set_output(self, output)
def _display(self, layout):
"""launch layouts display
overridden from BaseReporter to add insert the messages section
(in add_message, message is not displayed, just collected so it
can be displayed in an html table)
"""
if self.msgs:
# add stored messages to the layout
msgs = ['type', 'module', 'object', 'line', 'col_offset', 'message']
msgs += self.msgs
sect = Section('Messages')
layout.append(sect)
sect.append(Table(cols=6, children=msgs, rheaders=1))
self.msgs = []
HTMLWriter().format(layout, self.out) | unknown | codeparrot/codeparrot-clean | ||
package client
import (
"net/http"
"testing"
cerrdefs "github.com/containerd/errdefs"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestConfigUpdateError(t *testing.T) {
client, err := New(
WithMockClient(errorMock(http.StatusInternalServerError, "Server error")),
)
assert.NilError(t, err)
_, err = client.ConfigUpdate(t.Context(), "config_id", ConfigUpdateOptions{})
assert.Check(t, is.ErrorType(err, cerrdefs.IsInternal))
_, err = client.ConfigUpdate(t.Context(), "", ConfigUpdateOptions{})
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument))
assert.Check(t, is.ErrorContains(err, "value is empty"))
_, err = client.ConfigUpdate(t.Context(), " ", ConfigUpdateOptions{})
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument))
assert.Check(t, is.ErrorContains(err, "value is empty"))
}
func TestConfigUpdate(t *testing.T) {
const expectedURL = "/configs/config_id/update"
client, err := New(
WithMockClient(func(req *http.Request) (*http.Response, error) {
if err := assertRequest(req, http.MethodPost, expectedURL); err != nil {
return nil, err
}
return mockJSONResponse(http.StatusOK, nil, "")(req)
}),
)
assert.NilError(t, err)
_, err = client.ConfigUpdate(t.Context(), "config_id", ConfigUpdateOptions{})
assert.NilError(t, err)
} | go | github | https://github.com/moby/moby | client/config_update_test.go |
import re
import os
import base64
try:
# Python 3
from urllib.parse import urlencode
except (ImportError):
# Python 2
from urllib import urlencode
from .json_api_client import JSONApiClient
from ..downloaders.downloader_exception import DownloaderException
# Used to map file extensions to formats
_readme_formats = {
'.md': 'markdown',
'.mkd': 'markdown',
'.mdown': 'markdown',
'.markdown': 'markdown',
'.textile': 'textile',
'.creole': 'creole',
'.rst': 'rst'
}
class ReadmeClient(JSONApiClient):
def readme_info(self, url):
"""
Retrieve the readme and info about it
:param url:
The URL of the readme file
:raises:
DownloaderException: if there is an error downloading the readme
ClientException: if there is an error parsing the response
:return:
A dict with the following keys:
`filename`
`format` - `markdown`, `textile`, `creole`, `rst` or `txt`
`contents` - contents of the readme as str/unicode
"""
contents = None
# Try to grab the contents of a GitHub-based readme by grabbing the cached
# content of the readme API call
github_match = re.match('https://raw.github.com/([^/]+/[^/]+)/([^/]+)/readme(\.(md|mkd|mdown|markdown|textile|creole|rst|txt))?$', url, re.I)
if github_match:
user_repo = github_match.group(1)
branch = github_match.group(2)
query_string = urlencode({'ref': branch})
readme_json_url = 'https://api.github.com/repos/%s/readme?%s' % (user_repo, query_string)
try:
info = self.fetch_json(readme_json_url, prefer_cached=True)
contents = base64.b64decode(info['content'])
except (ValueError) as e:
pass
if not contents:
contents = self.fetch(url)
basename, ext = os.path.splitext(url)
format = 'txt'
ext = ext.lower()
if ext in _readme_formats:
format = _readme_formats[ext]
try:
contents = contents.decode('utf-8')
except (UnicodeDecodeError) as e:
contents = contents.decode('cp1252', errors='replace')
return {
'filename': os.path.basename(url),
'format': format,
'contents': contents
} | unknown | codeparrot/codeparrot-clean | ||
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
"""
How To: Create a Table
----------------------
>>> from azure.storage import *
>>> table_service = TableService(name, key)
>>> table_service.create_table('tasktable')
True
How to Add an Entity to a Table
-------------------------------
>>> task = {'PartitionKey': 'tasksSeattle', 'RowKey': '1', 'description' : 'Take out the trash', 'priority' : 200}
>>> entity = table_service.insert_entity('tasktable', task)
>>> task = Entity()
>>> task.PartitionKey = 'tasksSeattle'
>>> task.RowKey = '2'
>>> task.description = 'Wash the car'
>>> task.priority = 100
>>> entity = table_service.insert_entity('tasktable', task)
How to Update an Entity
-----------------------
>>> task = {'description' : 'Take out the garbage', 'priority' : 250}
>>> entity = table_service.update_entity('tasktable', 'tasksSeattle', '1', task)
>>> task = {'description' : 'Take out the garbage again', 'priority' : 250}
>>> entity = table_service.insert_or_replace_entity('tasktable', 'tasksSeattle', '1', task)
>>> task = {'description' : 'Buy detergent', 'priority' : 300}
>>> entity = table_service.insert_or_replace_entity('tasktable', 'tasksSeattle', '3', task)
How to Change a Group of Entities
---------------------------------
>>> task10 = {'PartitionKey': 'tasksSeattle', 'RowKey': '10', 'description' : 'Go grocery shopping', 'priority' : 400}
>>> task11 = {'PartitionKey': 'tasksSeattle', 'RowKey': '11', 'description' : 'Clean the bathroom', 'priority' : 100}
>>> table_service.begin_batch()
>>> table_service.insert_entity('tasktable', task10)
>>> table_service.insert_entity('tasktable', task11)
>>> table_service.commit_batch()
How to Query for an Entity
--------------------------
>>> task = table_service.get_entity('tasktable', 'tasksSeattle', '1')
>>> print(task.description)
Take out the garbage again
>>> print(task.priority)
250
>>> task = table_service.get_entity('tasktable', 'tasksSeattle', '10')
>>> print(task.description)
Go grocery shopping
>>> print(task.priority)
400
How to Query a Set of Entities
------------------------------
>>> tasks = table_service.query_entities('tasktable', "PartitionKey eq 'tasksSeattle'")
>>> for task in tasks:
... print(task.description)
... print(task.priority)
Take out the garbage again
250
Go grocery shopping
400
Clean the bathroom
100
Wash the car
100
Buy detergent
300
How to Query a Subset of Entity Properties
------------------------------------------
>>> tasks = table_service.query_entities('tasktable', "PartitionKey eq 'tasksSeattle'", 'description')
>>> for task in tasks:
... print(task.description)
Take out the garbage again
Go grocery shopping
Clean the bathroom
Wash the car
Buy detergent
How to Delete an Entity
-----------------------
>>> table_service.delete_entity('tasktable', 'tasksSeattle', '1')
How to Delete a Table
---------------------
>>> table_service.delete_table('tasktable')
True
"""
from util import credentials
name = credentials.getStorageServicesName()
key = credentials.getStorageServicesKey()
if __name__ == "__main__":
import doctest
doctest.testmod() | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import account_analytic_default
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
import argparse
import sys
from yahoo_finance import Share
def init_argparse():
parser = argparse.ArgumentParser(description="hl52")
parser.add_argument("--symfile", dest="symFile",
help="Path to the symbols file to analyze.")
return parser.parse_args()
def load_symbols(filename):
with open(filename, 'rb') as f:
symbol_list = [line.rstrip() for line in f]
return symbol_list
def calc_marker_loc(bid, low, high, markerWidth=10):
markerLoc = 0
# find out how far above the low price the current bid price is
if bid >= low:
bidAboveLow = bid - low
else:
return 0
hlRange = high - low
markerLoc = int(round(bidAboveLow * markerWidth / hlRange, 0))
# ensure we don't return anything invalid...just in case.
if markerLoc > markerWidth - 1:
markerLoc = markerWidth - 1
return markerLoc
def print_52_week_hl_marker(bid, low, high, symbol, length=10):
markerTemplate = list('=' * length)
markerLoc = calc_marker_loc(bid, low, high, length)
markerTemplate[markerLoc] = 'X'
# If bid has crossed below 52-week low, I want the
# percentage printed at the end of the line here
# The way I did this feels very 'brute force'...
if (bid / low) < 1.0:
print('{:5}@{:6.2f} : {:6.2f}[{}]{:6.2f} {:6.2f}%'
.format(symbol,
bid,
low,
''.join(markerTemplate),
high,
(bid / low) * 100.0))
else:
print('{:5}@{:6.2f} : {:6.2f}[{}]{:6.2f}'
.format(symbol,
bid,
low,
''.join(markerTemplate),
high))
def main(argv):
print('Begin run...')
args = init_argparse()
print('Loading symbols from {}'.format(args.symFile))
symbols = load_symbols(args.symFile)
d = {}
for s in symbols:
print('fetching {}...'.format(s))
share = Share(s)
bid = float(share.get_price())
year_low = float(share.get_year_low())
year_high = float(share.get_year_high())
d[s] = [bid, year_low, year_high]
# v is a list of ticker information:
# v[0] - bid
# v[1] - 52-week low
# v[2] - 52-week high
for k, v in sorted(d.iteritems()):
print_52_week_hl_marker(float(v[0]), float(v[1]), float(v[2]), k, 50)
print('End run.')
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv)) | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{app, icon::create_icns_file};
use crate::{
bundle::{settings::Arch, Bundle},
error::{Context, ErrorExt},
utils::CommandExt,
PackageType, Settings,
};
use std::{
env,
fs::{self, write},
path::PathBuf,
process::{Command, Stdio},
};
pub struct Bundled {
pub dmg: Vec<PathBuf>,
pub app: Vec<PathBuf>,
}
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the DMG was created.
pub fn bundle_project(settings: &Settings, bundles: &[Bundle]) -> crate::Result<Bundled> {
// generate the .app bundle if needed
let app_bundle_paths = if !bundles
.iter()
.any(|bundle| bundle.package_type == PackageType::MacOsBundle)
{
app::bundle_project(settings)?
} else {
Vec::new()
};
// get the target path
let output_path = settings.project_out_directory().join("bundle/dmg");
let package_base_name = format!(
"{}_{}_{}",
settings.product_name(),
settings.version_string(),
match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::AArch64 => "aarch64",
Arch::Universal => "universal",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)));
}
}
);
let dmg_name = format!("{}.dmg", &package_base_name);
let dmg_path = output_path.join(&dmg_name);
let product_name = settings.product_name();
let bundle_file_name = format!("{product_name}.app");
let bundle_dir = settings.project_out_directory().join("bundle/macos");
let support_directory_path = output_path
.parent()
.unwrap()
.join("share/create-dmg/support");
for path in &[&support_directory_path, &output_path] {
if path.exists() {
fs::remove_dir_all(path).fs_context("failed to remove old dmg", path.to_path_buf())?;
}
fs::create_dir_all(path).fs_context("failed to create output directory", path.to_path_buf())?;
}
// create paths for script
let bundle_script_path = output_path.join("bundle_dmg.sh");
log::info!(action = "Bundling"; "{} ({})", dmg_name, dmg_path.display());
// write the scripts
write(&bundle_script_path, include_str!("./bundle_dmg"))?;
write(
support_directory_path.join("template.applescript"),
include_str!("./template.applescript"),
)?;
write(
support_directory_path.join("eula-resources-template.xml"),
include_str!("./eula-resources-template.xml"),
)?;
// chmod script for execution
Command::new("chmod")
.arg("777")
.arg(&bundle_script_path)
.current_dir(&output_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("Failed to chmod script");
let dmg_settings = settings.dmg();
let app_position = &dmg_settings.app_position;
let application_folder_position = &dmg_settings.application_folder_position;
let window_size = &dmg_settings.window_size;
let app_position_x = app_position.x.to_string();
let app_position_y = app_position.y.to_string();
let application_folder_position_x = application_folder_position.x.to_string();
let application_folder_position_y = application_folder_position.y.to_string();
let window_size_width = window_size.width.to_string();
let window_size_height = window_size.height.to_string();
let mut bundle_dmg_cmd = Command::new(&bundle_script_path);
bundle_dmg_cmd.args([
"--volname",
product_name,
"--icon",
&bundle_file_name,
&app_position_x,
&app_position_y,
"--app-drop-link",
&application_folder_position_x,
&application_folder_position_y,
"--window-size",
&window_size_width,
&window_size_height,
"--hide-extension",
&bundle_file_name,
]);
let window_position = dmg_settings
.window_position
.as_ref()
.map(|position| (position.x.to_string(), position.y.to_string()));
if let Some(window_position) = &window_position {
bundle_dmg_cmd.arg("--window-pos");
bundle_dmg_cmd.arg(&window_position.0);
bundle_dmg_cmd.arg(&window_position.1);
}
let background_path = if let Some(background_path) = &dmg_settings.background {
Some(env::current_dir()?.join(background_path))
} else {
None
};
if let Some(background_path) = &background_path {
bundle_dmg_cmd.arg("--background");
bundle_dmg_cmd.arg(background_path);
}
let icns_icon_path = create_icns_file(&output_path, settings)?;
if let Some(icon) = &icns_icon_path {
bundle_dmg_cmd.arg("--volicon");
bundle_dmg_cmd.arg(icon);
}
let license_path = if let Some(license_path) = settings.license_file() {
Some(env::current_dir()?.join(license_path))
} else {
None
};
if let Some(license_path) = &license_path {
bundle_dmg_cmd.arg("--eula");
bundle_dmg_cmd.arg(license_path);
}
// Issue #592 - Building MacOS dmg files on CI
// https://github.com/tauri-apps/tauri/issues/592
if env::var_os("TAURI_BUNDLER_DMG_IGNORE_CI").unwrap_or_default() != "true" {
if let Some(value) = env::var_os("CI") {
if value == "true" {
bundle_dmg_cmd.arg("--skip-jenkins");
}
}
}
log::info!(action = "Running"; "bundle_dmg.sh");
// execute the bundle script
bundle_dmg_cmd
.current_dir(bundle_dir.clone())
.args(vec![dmg_name.as_str(), bundle_file_name.as_str()])
.output_ok()
.context("error running bundle_dmg.sh")?;
fs::rename(bundle_dir.join(dmg_name), dmg_path.clone())?;
// Sign DMG if needed
// skipping self-signing DMGs https://github.com/tauri-apps/tauri/issues/12288
let identity = settings.macos().signing_identity.as_deref();
if !settings.no_sign() && identity != Some("-") {
if let Some(keychain) = super::sign::keychain(identity)? {
super::sign::sign(
&keychain,
vec![super::sign::SignTarget {
path: dmg_path.clone(),
is_an_executable: false,
}],
settings,
)?;
}
}
Ok(Bundled {
dmg: vec![dmg_path],
app: app_bundle_paths,
})
} | rust | github | https://github.com/tauri-apps/tauri | crates/tauri-bundler/src/bundle/macos/dmg/mod.rs |
<?php
namespace Illuminate\Tests\Container;
use Illuminate\Container\RewindableGenerator;
use PHPUnit\Framework\TestCase;
class RewindableGeneratorTest extends TestCase
{
public function testCountUsesProvidedValue()
{
$generator = new RewindableGenerator(function () {
yield 'foo';
}, 999);
$this->assertCount(999, $generator);
}
public function testCountUsesProvidedValueAsCallback()
{
$called = 0;
$generator = new RewindableGenerator(function () {
yield 'foo';
}, function () use (&$called) {
$called++;
return 500;
});
// the count callback is called lazily
$this->assertSame(0, $called);
$this->assertCount(500, $generator);
count($generator);
// the count callback is called only once
$this->assertSame(1, $called);
}
} | php | github | https://github.com/laravel/framework | tests/Container/RewindableGeneratorTest.php |
import itertools
import functools
import rlcompleter
from textwrap import dedent
from unittest import TestCase
from unittest.mock import MagicMock
from test.support import force_colorized_test_class, force_not_colorized_test_class
from .support import handle_all_events, handle_events_narrow_console
from .support import ScreenEqualMixin, code_to_events
from .support import prepare_reader, prepare_console
from _pyrepl.console import Event
from _pyrepl.reader import Reader
from _colorize import default_theme
overrides = {"reset": "z", "soft_keyword": "K"}
colors = {overrides.get(k, k[0].lower()): v for k, v in default_theme.syntax.items()}
@force_not_colorized_test_class
class TestReader(ScreenEqualMixin, TestCase):
def test_calc_screen_wrap_simple(self):
events = code_to_events(10 * "a")
reader, _ = handle_events_narrow_console(events)
self.assert_screen_equal(reader, f"{9*"a"}\\\na")
def test_calc_screen_wrap_wide_characters(self):
events = code_to_events(8 * "a" + "樂")
reader, _ = handle_events_narrow_console(events)
self.assert_screen_equal(reader, f"{8*"a"}\\\n樂")
def test_calc_screen_wrap_three_lines(self):
events = code_to_events(20 * "a")
reader, _ = handle_events_narrow_console(events)
self.assert_screen_equal(reader, f"{9*"a"}\\\n{9*"a"}\\\naa")
def test_calc_screen_prompt_handling(self):
def prepare_reader_keep_prompts(*args, **kwargs):
reader = prepare_reader(*args, **kwargs)
del reader.get_prompt
reader.ps1 = ">>> "
reader.ps2 = ">>> "
reader.ps3 = "... "
reader.ps4 = ""
reader.can_colorize = False
reader.paste_mode = False
return reader
events = code_to_events("if some_condition:\nsome_function()")
reader, _ = handle_events_narrow_console(
events,
prepare_reader=prepare_reader_keep_prompts,
)
# fmt: off
self.assert_screen_equal(
reader,
(
">>> if so\\\n"
"me_condit\\\n"
"ion:\n"
"... s\\\n"
"ome_funct\\\n"
"ion()"
)
)
# fmt: on
def test_calc_screen_wrap_three_lines_mixed_character(self):
# fmt: off
code = (
"def f():\n"
f" {8*"a"}\n"
f" {5*"樂"}"
)
# fmt: on
events = code_to_events(code)
reader, _ = handle_events_narrow_console(events)
# fmt: off
self.assert_screen_equal(
reader,
(
"def f():\n"
f" {7*"a"}\\\n"
"a\n"
f" {3*"樂"}\\\n"
"樂樂"
),
clean=True,
)
# fmt: on
def test_calc_screen_backspace(self):
events = itertools.chain(
code_to_events("aaa"),
[
Event(evt="key", data="backspace", raw=bytearray(b"\x7f")),
],
)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, "aa")
def test_calc_screen_wrap_removes_after_backspace(self):
events = itertools.chain(
code_to_events(10 * "a"),
[
Event(evt="key", data="backspace", raw=bytearray(b"\x7f")),
],
)
reader, _ = handle_events_narrow_console(events)
self.assert_screen_equal(reader, 9 * "a")
def test_calc_screen_backspace_in_second_line_after_wrap(self):
events = itertools.chain(
code_to_events(11 * "a"),
[
Event(evt="key", data="backspace", raw=bytearray(b"\x7f")),
],
)
reader, _ = handle_events_narrow_console(events)
self.assert_screen_equal(reader, f"{9*"a"}\\\na")
def test_setpos_for_xy_simple(self):
events = code_to_events("11+11")
reader, _ = handle_all_events(events)
reader.setpos_from_xy(0, 0)
self.assertEqual(reader.pos, 0)
def test_setpos_from_xy_multiple_lines(self):
# fmt: off
code = (
"def foo():\n"
" return 1"
)
# fmt: on
events = code_to_events(code)
reader, _ = handle_all_events(events)
reader.setpos_from_xy(2, 1)
self.assertEqual(reader.pos, 13)
def test_setpos_from_xy_after_wrap(self):
# fmt: off
code = (
"def foo():\n"
" hello"
)
# fmt: on
events = code_to_events(code)
reader, _ = handle_events_narrow_console(events)
reader.setpos_from_xy(2, 2)
self.assertEqual(reader.pos, 13)
def test_setpos_fromxy_in_wrapped_line(self):
# fmt: off
code = (
"def foo():\n"
" hello"
)
# fmt: on
events = code_to_events(code)
reader, _ = handle_events_narrow_console(events)
reader.setpos_from_xy(0, 1)
self.assertEqual(reader.pos, 9)
def test_up_arrow_after_ctrl_r(self):
events = iter(
[
Event(evt="key", data="\x12", raw=bytearray(b"\x12")),
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
]
)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, "")
def test_newline_within_block_trailing_whitespace(self):
# fmt: off
code = (
"def foo():\n"
"a = 1\n"
)
# fmt: on
events = itertools.chain(
code_to_events(code),
[
# go to the end of the first line
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")),
Event(evt="key", data="\x05", raw=bytearray(b"\x1bO5")),
# new lines in-block shouldn't terminate the block
Event(evt="key", data="\n", raw=bytearray(b"\n")),
Event(evt="key", data="\n", raw=bytearray(b"\n")),
# end of line 2
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")),
Event(evt="key", data="\x05", raw=bytearray(b"\x1bO5")),
# a double new line in-block should terminate the block
# even if its followed by whitespace
Event(evt="key", data="\n", raw=bytearray(b"\n")),
Event(evt="key", data="\n", raw=bytearray(b"\n")),
],
)
no_paste_reader = functools.partial(prepare_reader, paste_mode=False)
reader, _ = handle_all_events(events, prepare_reader=no_paste_reader)
expected = (
"def foo():\n"
" \n"
" \n"
" a = 1\n"
" \n"
" " # HistoricalReader will trim trailing whitespace
)
self.assert_screen_equal(reader, expected, clean=True)
self.assertTrue(reader.finished)
def test_input_hook_is_called_if_set(self):
input_hook = MagicMock()
def _prepare_console(events):
console = MagicMock()
console.get_event.side_effect = events
console.height = 100
console.width = 80
console.input_hook = input_hook
return console
events = code_to_events("a")
reader, _ = handle_all_events(events, prepare_console=_prepare_console)
self.assertEqual(len(input_hook.mock_calls), 4)
def test_keyboard_interrupt_clears_screen(self):
namespace = {"itertools": itertools}
code = "import itertools\nitertools."
events = itertools.chain(
code_to_events(code),
[
# Two tabs for completion
Event(evt="key", data="\t", raw=bytearray(b"\t")),
Event(evt="key", data="\t", raw=bytearray(b"\t")),
Event(evt="key", data="\x03", raw=bytearray(b"\x03")), # Ctrl-C
],
)
console = prepare_console(events)
reader = prepare_reader(
console,
readline_completer=rlcompleter.Completer(namespace).complete,
)
try:
# we're not using handle_all_events() here to be able to
# follow the KeyboardInterrupt sequence of events. Normally this
# happens in simple_interact.run_multiline_interactive_console.
while True:
reader.handle1()
except KeyboardInterrupt:
# at this point the completions are still visible
self.assertTrue(len(reader.screen) > 2)
reader.refresh()
# after the refresh, they are gone
self.assertEqual(len(reader.screen), 2)
self.assert_screen_equal(reader, code, clean=True)
else:
self.fail("KeyboardInterrupt not raised.")
def test_prompt_length(self):
# Handles simple ASCII prompt
ps1 = ">>> "
prompt, l = Reader.process_prompt(ps1)
self.assertEqual(prompt, ps1)
self.assertEqual(l, 4)
# Handles ANSI escape sequences
ps1 = "\033[0;32m>>> \033[0m"
prompt, l = Reader.process_prompt(ps1)
self.assertEqual(prompt, "\033[0;32m>>> \033[0m")
self.assertEqual(l, 4)
# Handles ANSI escape sequences bracketed in \001 .. \002
ps1 = "\001\033[0;32m\002>>> \001\033[0m\002"
prompt, l = Reader.process_prompt(ps1)
self.assertEqual(prompt, "\033[0;32m>>> \033[0m")
self.assertEqual(l, 4)
# Handles wide characters in prompt
ps1 = "樂>> "
prompt, l = Reader.process_prompt(ps1)
self.assertEqual(prompt, ps1)
self.assertEqual(l, 5)
# Handles wide characters AND ANSI sequences together
ps1 = "\001\033[0;32m\002樂>\001\033[0m\002> "
prompt, l = Reader.process_prompt(ps1)
self.assertEqual(prompt, "\033[0;32m樂>\033[0m> ")
self.assertEqual(l, 5)
def test_completions_updated_on_key_press(self):
namespace = {"itertools": itertools}
code = "itertools."
events = itertools.chain(
code_to_events(code),
[
# Two tabs for completion
Event(evt="key", data="\t", raw=bytearray(b"\t")),
Event(evt="key", data="\t", raw=bytearray(b"\t")),
],
code_to_events("a"),
)
completing_reader = functools.partial(
prepare_reader,
readline_completer=rlcompleter.Completer(namespace).complete,
)
reader, _ = handle_all_events(events, prepare_reader=completing_reader)
actual = reader.screen
self.assertEqual(len(actual), 2)
self.assertEqual(actual[0], f"{code}a")
self.assertEqual(actual[1].rstrip(), "itertools.accumulate(")
def test_key_press_on_tab_press_once(self):
namespace = {"itertools": itertools}
code = "itertools."
events = itertools.chain(
code_to_events(code),
[
Event(evt="key", data="\t", raw=bytearray(b"\t")),
],
code_to_events("a"),
)
completing_reader = functools.partial(
prepare_reader,
readline_completer=rlcompleter.Completer(namespace).complete,
)
reader, _ = handle_all_events(events, prepare_reader=completing_reader)
self.assert_screen_equal(reader, f"{code}a")
def test_pos2xy_with_no_columns(self):
console = prepare_console([])
reader = prepare_reader(console)
# Simulate a resize to 0 columns
reader.screeninfo = []
self.assertEqual(reader.pos2xy(), (0, 0))
def test_setpos_from_xy_for_non_printing_char(self):
code = "# non \u200c printing character"
events = code_to_events(code)
reader, _ = handle_all_events(events)
reader.setpos_from_xy(8, 0)
self.assertEqual(reader.pos, 7)
@force_colorized_test_class
class TestReaderInColor(ScreenEqualMixin, TestCase):
def test_syntax_highlighting_basic(self):
code = dedent(
"""\
import re, sys
def funct(case: str = sys.platform) -> None:
match = re.search(
"(me)",
'''
Come on
Come on now
You know that it's time to emerge
''',
)
match case:
case "emscripten": print("on the web")
case "ios" | "android":
print("on the phone")
case _: print('arms around', match.group(1))
type type = type[type]
"""
)
expected = dedent(
"""\
{k}import{z} re{o},{z} sys
{a}{k}def{z} {d}funct{z}{o}({z}case{o}:{z} {b}str{z} {o}={z} sys{o}.{z}platform{o}){z} {o}->{z} {k}None{z}{o}:{z}
match {o}={z} re{o}.{z}search{o}({z}
{s}"(me)"{z}{o},{z}
{s}'''{z}
{s} Come on{z}
{s} Come on now{z}
{s} You know that it's time to emerge{z}
{s} '''{z}{o},{z}
{o}){z}
{K}match{z} case{o}:{z}
{K}case{z} {s}"emscripten"{z}{o}:{z} {b}print{z}{o}({z}{s}"on the web"{z}{o}){z}
{K}case{z} {s}"ios"{z} {o}|{z} {s}"android"{z}{o}:{z}
{b}print{z}{o}({z}{s}"on the phone"{z}{o}){z}
{K}case{z} {K}_{z}{o}:{z} {b}print{z}{o}({z}{s}'arms around'{z}{o},{z} match{o}.{z}group{o}({z}{n}1{z}{o}){z}{o}){z}
{K}type{z} {b}type{z} {o}={z} {b}type{z}{o}[{z}{b}type{z}{o}]{z}
"""
)
expected_sync = expected.format(a="", **colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected_sync)
self.assertEqual(reader.pos, 419)
self.assertEqual(reader.cxy, (0, 16))
async_msg = "{k}async{z} ".format(**colors)
expected_async = expected.format(a=async_msg, **colors)
more_events = itertools.chain(
code_to_events(code),
[Event(evt="key", data="up", raw=bytearray(b"\x1bOA"))] * 15,
code_to_events("async "),
)
reader, _ = handle_all_events(more_events)
self.assert_screen_equal(reader, expected_async)
self.assertEqual(reader.pos, 21)
self.assertEqual(reader.cxy, (6, 1))
def test_syntax_highlighting_incomplete_string_first_line(self):
code = dedent(
"""\
def unfinished_function(arg: str = "still typing
"""
)
expected = dedent(
"""\
{k}def{z} {d}unfinished_function{z}{o}({z}arg{o}:{z} {b}str{z} {o}={z} {s}"still typing{z}
"""
).format(**colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_incomplete_string_another_line(self):
code = dedent(
"""\
def unfinished_function(
arg: str = "still typing
"""
)
expected = dedent(
"""\
{k}def{z} {d}unfinished_function{z}{o}({z}
arg{o}:{z} {b}str{z} {o}={z} {s}"still typing{z}
"""
).format(**colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_incomplete_multiline_string(self):
code = dedent(
"""\
def unfinished_function():
'''Still writing
the docstring
"""
)
expected = dedent(
"""\
{k}def{z} {d}unfinished_function{z}{o}({z}{o}){z}{o}:{z}
{s}'''Still writing{z}
{s} the docstring{z}
"""
).format(**colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_incomplete_fstring(self):
code = dedent(
"""\
def unfinished_function():
var = f"Single-quote but {
1
+
1
} multi-line!
"""
)
expected = dedent(
"""\
{k}def{z} {d}unfinished_function{z}{o}({z}{o}){z}{o}:{z}
var {o}={z} {s}f"{z}{s}Single-quote but {z}{o}{OB}{z}
{n}1{z}
{o}+{z}
{n}1{z}
{o}{CB}{z}{s} multi-line!{z}
"""
).format(OB="{", CB="}", **colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_indentation_error(self):
code = dedent(
"""\
def unfinished_function():
var = 1
oops
"""
)
expected = dedent(
"""\
{k}def{z} {d}unfinished_function{z}{o}({z}{o}){z}{o}:{z}
var {o}={z} {n}1{z}
oops
"""
).format(**colors)
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.assert_screen_equal(reader, expected)
def test_syntax_highlighting_literal_brace_in_fstring_or_tstring(self):
code = dedent(
"""\
f"{{"
f"}}"
f"a{{b"
f"a}}b"
f"a{{b}}c"
t"a{{b}}c"
f"{{{0}}}"
f"{ {0} }"
"""
)
expected = dedent(
"""\
{s}f"{z}{s}<<{z}{s}"{z}
{s}f"{z}{s}>>{z}{s}"{z}
{s}f"{z}{s}a<<{z}{s}b{z}{s}"{z}
{s}f"{z}{s}a>>{z}{s}b{z}{s}"{z}
{s}f"{z}{s}a<<{z}{s}b>>{z}{s}c{z}{s}"{z}
{s}t"{z}{s}a<<{z}{s}b>>{z}{s}c{z}{s}"{z}
{s}f"{z}{s}<<{z}{o}<{z}{n}0{z}{o}>{z}{s}>>{z}{s}"{z}
{s}f"{z}{o}<{z} {o}<{z}{n}0{z}{o}>{z} {o}>{z}{s}"{z}
"""
).format(**colors).replace("<", "{").replace(">", "}")
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, code, clean=True)
self.maxDiff=None
self.assert_screen_equal(reader, expected)
def test_control_characters(self):
code = 'flag = "🏳️🌈"'
events = code_to_events(code)
reader, _ = handle_all_events(events)
self.assert_screen_equal(reader, 'flag = "🏳️\\u200d🌈"', clean=True)
self.assert_screen_equal(reader, 'flag {o}={z} {s}"🏳️\\u200d🌈"{z}'.format(**colors)) | python | github | https://github.com/python/cpython | Lib/test/test_pyrepl/test_reader.py |
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
package database
import (
"context"
"errors"
"fmt"
v5 "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/automatedrotationutil"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/pluginutil"
"github.com/hashicorp/vault/sdk/logical"
)
var (
respErrEmptyPluginName = "empty plugin name"
respErrEmptyName = "empty name attribute given"
)
// DatabaseConfig is used by the Factory function to configure a Database
// object.
type DatabaseConfig struct {
EntDatabaseConfig `mapstructure:",squash"`
PluginName string `json:"plugin_name" structs:"plugin_name" mapstructure:"plugin_name"`
PluginVersion string `json:"plugin_version" structs:"plugin_version" mapstructure:"plugin_version"`
RunningPluginVersion string `json:"running_plugin_version,omitempty" structs:"running_plugin_version,omitempty" mapstructure:"running_plugin_version,omitempty"`
// ConnectionDetails stores the database specific connection settings needed
// by each database type.
ConnectionDetails map[string]interface{} `json:"connection_details" structs:"connection_details" mapstructure:"connection_details"`
AllowedRoles []string `json:"allowed_roles" structs:"allowed_roles" mapstructure:"allowed_roles"`
RootCredentialsRotateStatements []string `json:"root_credentials_rotate_statements" structs:"root_credentials_rotate_statements" mapstructure:"root_credentials_rotate_statements"`
PasswordPolicy string `json:"password_policy" structs:"password_policy" mapstructure:"password_policy"`
VerifyConnection bool `json:"verify_connection" structs:"verify_connection" mapstructure:"verify_connection"`
// SkipStaticRoleImportRotation is a flag to toggle wether or not a given
// static account's password should be rotated on creation of the static
// roles associated with this DB config. This can be overridden at the
// role-level by the role's skip_import_rotation field. The default is
// false. Enterprise only.
SkipStaticRoleImportRotation bool `json:"skip_static_role_import_rotation" structs:"skip_static_role_import_rotation" mapstructure:"skip_static_role_import_rotation"`
automatedrotationutil.AutomatedRotationParams
}
// ConnectionDetails represents the DatabaseConfig.ConnectionDetails map as a
// struct
type ConnectionDetails struct {
SelfManaged bool `json:"self_managed" structs:"self_managed" mapstructure:"self_managed"`
}
func (c *DatabaseConfig) SupportsCredentialType(credentialType v5.CredentialType) bool {
credTypes, ok := c.ConnectionDetails[v5.SupportedCredentialTypesKey].([]interface{})
if !ok {
// Default to supporting CredentialTypePassword for database plugins that
// don't specify supported credential types in the initialization response
return credentialType == v5.CredentialTypePassword
}
for _, ct := range credTypes {
if ct == credentialType.String() {
return true
}
}
return false
}
// pathResetConnection configures a path to reset a plugin.
func pathResetConnection(b *databaseBackend) *framework.Path {
return &framework.Path{
Pattern: fmt.Sprintf("reset/%s", framework.GenericNameRegex("name")),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixDatabase,
OperationVerb: "reset",
OperationSuffix: "connection",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of this database connection",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathConnectionReset(),
},
HelpSynopsis: pathResetConnectionHelpSyn,
HelpDescription: pathResetConnectionHelpDesc,
}
}
// pathConnectionReset resets a plugin by closing the existing instance and
// creating a new one.
func (b *databaseBackend) pathConnectionReset() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
if name == "" {
return logical.ErrorResponse(respErrEmptyName), nil
}
if err := b.reloadConnection(ctx, req.Storage, name); err != nil {
return nil, err
}
b.dbEvent(ctx, "reset", req.Path, name, false)
recordDatabaseObservation(ctx, b, req, name, ObservationTypeDatabaseConnectionReset)
return nil, nil
}
}
func (b *databaseBackend) reloadConnection(ctx context.Context, storage logical.Storage, name string) error {
// Close plugin and delete the entry in the connections cache.
if err := b.ClearConnection(name); err != nil {
return err
}
// Execute plugin again, we don't need the object so throw away.
if _, err := b.GetConnection(ctx, storage, name); err != nil {
return err
}
return nil
}
// pathReloadPlugin reloads all connections using a named plugin.
func pathReloadPlugin(b *databaseBackend) *framework.Path {
return &framework.Path{
Pattern: fmt.Sprintf("reload/%s", framework.GenericNameRegex("plugin_name")),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixDatabase,
OperationVerb: "reload",
OperationSuffix: "plugin",
},
Fields: map[string]*framework.FieldSchema{
"plugin_name": {
Type: framework.TypeString,
Description: "Name of the database plugin",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.reloadPlugin(),
},
HelpSynopsis: pathReloadPluginHelpSyn,
HelpDescription: pathReloadPluginHelpDesc,
}
}
// reloadPlugin reloads all instances of a named plugin by closing the existing
// instances and creating new ones.
func (b *databaseBackend) reloadPlugin() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
pluginName := data.Get("plugin_name").(string)
if pluginName == "" {
return logical.ErrorResponse(respErrEmptyPluginName), nil
}
connNames, err := req.Storage.List(ctx, "config/")
if err != nil {
return nil, err
}
reloaded := []string{}
reloadFailed := []string{}
for _, connName := range connNames {
entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", connName))
if err != nil {
return nil, fmt.Errorf("failed to read connection configuration: %w", err)
}
if entry == nil {
continue
}
var config DatabaseConfig
if err := entry.DecodeJSON(&config); err != nil {
return nil, err
}
if config.PluginName == pluginName {
if err := b.reloadConnection(ctx, req.Storage, connName); err != nil {
b.Logger().Error("failed to reload connection", "name", connName, "error", err)
b.dbEvent(ctx, "reload-connection-fail", req.Path, "", false, "name", connName)
recordDatabaseObservation(ctx, b, req, connName, ObservationTypeDatabaseReloadFail,
AdditionalDatabaseMetadata{key: "plugin_name", value: pluginName})
reloadFailed = append(reloadFailed, connName)
} else {
b.Logger().Debug("reloaded connection", "name", connName)
b.dbEvent(ctx, "reload-connection", req.Path, "", true, "name", connName)
recordDatabaseObservation(ctx, b, req, connName, ObservationTypeDatabaseReloadSuccess,
AdditionalDatabaseMetadata{key: "plugin_name", value: pluginName})
reloaded = append(reloaded, connName)
}
}
}
recordDatabaseObservation(ctx, b, req, "", ObservationTypeDatabaseReloadPlugin,
AdditionalDatabaseMetadata{key: "plugin_name", value: pluginName},
AdditionalDatabaseMetadata{key: "reloaded", value: reloaded},
AdditionalDatabaseMetadata{key: "reload_failed", value: reloadFailed})
resp := &logical.Response{
Data: map[string]interface{}{
"connections": reloaded,
"count": len(reloaded),
},
}
if len(reloaded) > 0 {
b.dbEvent(ctx, "reload", req.Path, "", true, "plugin_name", pluginName)
} else if len(reloaded) == 0 && len(reloadFailed) == 0 {
b.Logger().Debug("no connections were found", "plugin_name", pluginName)
}
return resp, nil
}
}
// pathConfigurePluginConnection returns a configured framework.Path setup to
// operate on plugins.
func pathConfigurePluginConnection(b *databaseBackend) *framework.Path {
fields := map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of this database connection",
},
"plugin_name": {
Type: framework.TypeString,
Description: `The name of a builtin or previously registered
plugin known to vault. This endpoint will create an instance of
that plugin type.`,
},
"plugin_version": {
Type: framework.TypeString,
Description: `The version of the plugin to use.`,
},
"verify_connection": {
Type: framework.TypeBool,
Default: true,
Description: `If true, the connection details are verified by
actually connecting to the database. Defaults to true.`,
},
"allowed_roles": {
Type: framework.TypeCommaStringSlice,
Description: `Comma separated string or array of the role names
allowed to get creds from this database connection. If empty no
roles are allowed. If "*" all roles are allowed.`,
},
"root_rotation_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements to be executed
to rotate the root user's credentials. See the plugin's API
page for more information on support and formatting for this
parameter.`,
},
"password_policy": {
Type: framework.TypeString,
Description: `Password policy to use when generating passwords.`,
},
}
AddConnectionFieldsEnt(fields)
automatedrotationutil.AddAutomatedRotationFields(fields)
return &framework.Path{
Pattern: fmt.Sprintf("config/%s", framework.GenericNameRegex("name")),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixDatabase,
},
Fields: fields,
ExistenceCheck: b.connectionExistenceCheck(),
Operations: map[logical.Operation]framework.OperationHandler{
logical.CreateOperation: &framework.PathOperation{
Callback: b.connectionWriteHandler(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "configure",
OperationSuffix: "connection",
},
ForwardPerformanceSecondary: true,
ForwardPerformanceStandby: true,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.connectionWriteHandler(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "configure",
OperationSuffix: "connection",
},
ForwardPerformanceSecondary: true,
ForwardPerformanceStandby: true,
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.connectionReadHandler(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "read",
OperationSuffix: "connection-configuration",
},
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.connectionDeleteHandler(),
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "delete",
OperationSuffix: "connection-configuration",
},
},
},
HelpSynopsis: pathConfigConnectionHelpSyn,
HelpDescription: pathConfigConnectionHelpDesc,
}
}
func (b *databaseBackend) connectionExistenceCheck() framework.ExistenceFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
name := data.Get("name").(string)
if name == "" {
return false, errors.New(`missing "name" parameter`)
}
entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", name))
if err != nil {
return false, fmt.Errorf("failed to read connection configuration: %w", err)
}
return entry != nil, nil
}
}
func pathListPluginConnection(b *databaseBackend) *framework.Path {
return &framework.Path{
Pattern: fmt.Sprintf("config/?$"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixDatabase,
OperationSuffix: "connections",
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.connectionListHandler(),
},
HelpSynopsis: pathConfigConnectionHelpSyn,
HelpDescription: pathConfigConnectionHelpDesc,
}
}
func (b *databaseBackend) connectionListHandler() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
entries, err := req.Storage.List(ctx, "config/")
if err != nil {
return nil, err
}
return logical.ListResponse(entries), nil
}
}
// connectionDeleteHandler deletes the connection configuration
func (b *databaseBackend) connectionDeleteHandler() framework.OperationFunc {
return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
if name == "" {
return logical.ErrorResponse(respErrEmptyName), nil
}
err := req.Storage.Delete(ctx, fmt.Sprintf("config/%s", name))
if err != nil {
return nil, fmt.Errorf("failed to delete connection configuration: %w", err)
}
if err := b.ClearConnection(name); err != nil {
return nil, err
}
b.dbEvent(ctx, "config-delete", req.Path, name, true)
recordDatabaseObservation(ctx, b, req, name, ObservationTypeDatabaseConfigDelete)
return nil, nil
}
}
func storeConfig(ctx context.Context, storage logical.Storage, name string, config *DatabaseConfig) error {
entry, err := logical.StorageEntryJSON(fmt.Sprintf("config/%s", name), config)
if err != nil {
return fmt.Errorf("unable to marshal object to JSON: %w", err)
}
err = storage.Put(ctx, entry)
if err != nil {
return fmt.Errorf("failed to save object: %w", err)
}
return nil
}
func (b *databaseBackend) getPinnedVersion(ctx context.Context, pluginName string) (string, error) {
extendedSys, ok := b.System().(logical.ExtendedSystemView)
if !ok {
return "", fmt.Errorf("database backend does not support running as an external plugin")
}
pin, err := extendedSys.GetPinnedPluginVersion(ctx, consts.PluginTypeDatabase, pluginName)
if errors.Is(err, pluginutil.ErrPinnedVersionNotFound) {
return "", nil
}
if err != nil {
return "", err
}
return pin.Version, nil
}
const pathConfigConnectionHelpSyn = `
Configure connection details to a database plugin.
`
const pathConfigConnectionHelpDesc = `
This path configures the connection details used to connect to a particular
database. This path runs the provided plugin name and passes the configured
connection details to the plugin. See the documentation for the plugin specified
for a full list of accepted connection details.
In addition to the database specific connection details, this endpoint also
accepts:
* "plugin_name" (required) - The name of a builtin or previously registered
plugin known to vault. This endpoint will create an instance of that
plugin type.
* "verify_connection" (default: true) - A boolean value denoting if the plugin should verify
it is able to connect to the database using the provided connection
details.
`
const pathResetConnectionHelpSyn = `
Resets a database plugin.
`
const pathResetConnectionHelpDesc = `
This path resets the database connection by closing the existing database plugin
instance and running a new one.
`
const pathReloadPluginHelpSyn = `
Reloads all connections using a named database plugin.
`
const pathReloadPluginHelpDesc = `
This path resets each database connection using a named plugin by closing each
existing database plugin instance and running a new one.
` | go | github | https://github.com/hashicorp/vault | builtin/logical/database/path_config_connection.go |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.Serializable;
import java.util.NoSuchElementException;
import org.jspecify.annotations.Nullable;
/**
* Implementation detail for the internal structure of {@link Range} instances. Represents a unique
* way of "cutting" a "number line" (actually of instances of type {@code C}, not necessarily
* "numbers") into two sections; this can be done below a certain value, above a certain value,
* below all values or above all values. With this object defined in this way, an interval can
* always be represented by a pair of {@code Cut} instances.
*
* @author Kevin Bourrillion
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtCompatible
abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable {
final C endpoint;
Cut(C endpoint) {
this.endpoint = endpoint;
}
abstract boolean isLessThan(C value);
abstract BoundType typeAsLowerBound();
abstract BoundType typeAsUpperBound();
abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain);
abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain);
abstract void describeAsLowerBound(StringBuilder sb);
abstract void describeAsUpperBound(StringBuilder sb);
abstract @Nullable C leastValueAbove(DiscreteDomain<C> domain);
abstract @Nullable C greatestValueBelow(DiscreteDomain<C> domain);
/*
* The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or
* (only in the case of types that are unbounded below) BELOW_ALL.
*/
Cut<C> canonical(DiscreteDomain<C> domain) {
return this;
}
// note: overridden by {BELOW,ABOVE}_ALL
@Override
public int compareTo(Cut<C> that) {
if (that == belowAll()) {
return 1;
}
if (that == aboveAll()) {
return -1;
}
int result = Range.compareOrThrow(endpoint, that.endpoint);
if (result != 0) {
return result;
}
// same value. below comes before above
return Boolean.compare(this instanceof AboveValue, that instanceof AboveValue);
}
C endpoint() {
return endpoint;
}
@SuppressWarnings("unchecked") // catching CCE
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof Cut) {
// It might not really be a Cut<C>, but we'll catch a CCE if it's not
Cut<C> that = (Cut<C>) obj;
try {
int compareResult = compareTo(that);
return compareResult == 0;
} catch (ClassCastException wastNotComparableToOurType) {
return false;
}
}
return false;
}
// Prevent "missing hashCode" warning by explicitly forcing subclasses implement it
@Override
public abstract int hashCode();
/*
* The implementation neither produces nor consumes any non-null instance of type C, so
* casting the type parameter is safe.
*/
@SuppressWarnings("unchecked")
static <C extends Comparable> Cut<C> belowAll() {
return (Cut<C>) BelowAll.INSTANCE;
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
private static final class BelowAll extends Cut<Comparable<?>> {
private static final BelowAll INSTANCE = new BelowAll();
private BelowAll() {
/*
* No code ever sees this bogus value for `endpoint`: This class overrides both methods that
* use the `endpoint` field, compareTo() and endpoint(). Additionally, the main implementation
* of Cut.compareTo checks for belowAll before reading accessing `endpoint` on another Cut
* instance.
*/
super("");
}
@Override
Comparable<?> endpoint() {
throw new IllegalStateException("range unbounded on this side");
}
@Override
boolean isLessThan(Comparable<?> value) {
return true;
}
@Override
BoundType typeAsLowerBound() {
throw new IllegalStateException();
}
@Override
BoundType typeAsUpperBound() {
throw new AssertionError("this statement should be unreachable");
}
@Override
Cut<Comparable<?>> withLowerBoundType(
BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
throw new IllegalStateException();
}
@Override
Cut<Comparable<?>> withUpperBoundType(
BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError("this statement should be unreachable");
}
@Override
void describeAsLowerBound(StringBuilder sb) {
sb.append("(-\u221e");
}
@Override
void describeAsUpperBound(StringBuilder sb) {
throw new AssertionError();
}
@Override
Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) {
return domain.minValue();
}
@Override
Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError();
}
@Override
Cut<Comparable<?>> canonical(DiscreteDomain<Comparable<?>> domain) {
try {
return Cut.belowValue(domain.minValue());
} catch (NoSuchElementException e) {
return this;
}
}
@Override
public int compareTo(Cut<Comparable<?>> o) {
return (o == this) ? 0 : -1;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public String toString() {
return "-\u221e";
}
private Object readResolve() {
return INSTANCE;
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
/*
* The implementation neither produces nor consumes any non-null instance of
* type C, so casting the type parameter is safe.
*/
@SuppressWarnings("unchecked")
static <C extends Comparable> Cut<C> aboveAll() {
return (Cut<C>) AboveAll.INSTANCE;
}
private static final class AboveAll extends Cut<Comparable<?>> {
private static final AboveAll INSTANCE = new AboveAll();
private AboveAll() {
// For discussion of "", see BelowAll.
super("");
}
@Override
Comparable<?> endpoint() {
throw new IllegalStateException("range unbounded on this side");
}
@Override
boolean isLessThan(Comparable<?> value) {
return false;
}
@Override
BoundType typeAsLowerBound() {
throw new AssertionError("this statement should be unreachable");
}
@Override
BoundType typeAsUpperBound() {
throw new IllegalStateException();
}
@Override
Cut<Comparable<?>> withLowerBoundType(
BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError("this statement should be unreachable");
}
@Override
Cut<Comparable<?>> withUpperBoundType(
BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
throw new IllegalStateException();
}
@Override
void describeAsLowerBound(StringBuilder sb) {
throw new AssertionError();
}
@Override
void describeAsUpperBound(StringBuilder sb) {
sb.append("+\u221e)");
}
@Override
Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) {
throw new AssertionError();
}
@Override
Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) {
return domain.maxValue();
}
@Override
public int compareTo(Cut<Comparable<?>> o) {
return (o == this) ? 0 : 1;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public String toString() {
return "+\u221e";
}
private Object readResolve() {
return INSTANCE;
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
static <C extends Comparable> Cut<C> belowValue(C endpoint) {
return new BelowValue<>(endpoint);
}
private static final class BelowValue<C extends Comparable> extends Cut<C> {
BelowValue(C endpoint) {
super(checkNotNull(endpoint));
}
@Override
boolean isLessThan(C value) {
return Range.compareOrThrow(endpoint, value) <= 0;
}
@Override
BoundType typeAsLowerBound() {
return BoundType.CLOSED;
}
@Override
BoundType typeAsUpperBound() {
return BoundType.OPEN;
}
@Override
Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case CLOSED:
return this;
case OPEN:
C previous = domain.previous(endpoint);
return (previous == null) ? Cut.belowAll() : new AboveValue<>(previous);
}
throw new AssertionError();
}
@Override
Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case CLOSED:
C previous = domain.previous(endpoint);
return (previous == null) ? Cut.aboveAll() : new AboveValue<>(previous);
case OPEN:
return this;
}
throw new AssertionError();
}
@Override
void describeAsLowerBound(StringBuilder sb) {
sb.append('[').append(endpoint);
}
@Override
void describeAsUpperBound(StringBuilder sb) {
sb.append(endpoint).append(')');
}
@Override
C leastValueAbove(DiscreteDomain<C> domain) {
return endpoint;
}
@Override
@Nullable C greatestValueBelow(DiscreteDomain<C> domain) {
return domain.previous(endpoint);
}
@Override
public int hashCode() {
return endpoint.hashCode();
}
@Override
public String toString() {
return "\\" + endpoint + "/";
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
static <C extends Comparable> Cut<C> aboveValue(C endpoint) {
return new AboveValue<>(endpoint);
}
private static final class AboveValue<C extends Comparable> extends Cut<C> {
AboveValue(C endpoint) {
super(checkNotNull(endpoint));
}
@Override
boolean isLessThan(C value) {
return Range.compareOrThrow(endpoint, value) < 0;
}
@Override
BoundType typeAsLowerBound() {
return BoundType.OPEN;
}
@Override
BoundType typeAsUpperBound() {
return BoundType.CLOSED;
}
@Override
Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case OPEN:
return this;
case CLOSED:
C next = domain.next(endpoint);
return (next == null) ? Cut.belowAll() : belowValue(next);
}
throw new AssertionError();
}
@Override
Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
switch (boundType) {
case OPEN:
C next = domain.next(endpoint);
return (next == null) ? Cut.aboveAll() : belowValue(next);
case CLOSED:
return this;
}
throw new AssertionError();
}
@Override
void describeAsLowerBound(StringBuilder sb) {
sb.append('(').append(endpoint);
}
@Override
void describeAsUpperBound(StringBuilder sb) {
sb.append(endpoint).append(']');
}
@Override
@Nullable C leastValueAbove(DiscreteDomain<C> domain) {
return domain.next(endpoint);
}
@Override
C greatestValueBelow(DiscreteDomain<C> domain) {
return endpoint;
}
@Override
Cut<C> canonical(DiscreteDomain<C> domain) {
C next = leastValueAbove(domain);
return (next != null) ? belowValue(next) : Cut.aboveAll();
}
@Override
public int hashCode() {
return ~endpoint.hashCode();
}
@Override
public String toString() {
return "/" + endpoint + "\\";
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
} | java | github | https://github.com/google/guava | android/guava/src/com/google/common/collect/Cut.java |
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
* @author Chris Beams
*/
class AnnotationPointcutTests {
private ClassPathXmlApplicationContext ctx;
private AnnotatedTestBean testBean;
@BeforeEach
void setup() {
this.ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
this.testBean = ctx.getBean("testBean", AnnotatedTestBean.class);
}
@AfterEach
void tearDown() {
this.ctx.close();
}
@Test
void annotationBindingInAroundAdvice() {
assertThat(testBean.doThis()).isEqualTo("this value");
}
@Test
void noMatchingWithoutAnnotationPresent() {
assertThat(testBean.doTheOther()).isEqualTo("doTheOther");
}
}
class TestMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) {
return "this value";
}
} | java | github | https://github.com/spring-projects/spring-framework | spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java |
# -*- coding: utf-8 -*-
"""
pygments.console
~~~~~~~~~~~~~~~~
Format colored console output.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
esc = "\x1b["
codes = {}
codes[""] = ""
codes["reset"] = esc + "39;49;00m"
codes["bold"] = esc + "01m"
codes["faint"] = esc + "02m"
codes["standout"] = esc + "03m"
codes["underline"] = esc + "04m"
codes["blink"] = esc + "05m"
codes["overline"] = esc + "06m"
dark_colors = ["black", "darkred", "darkgreen", "brown", "darkblue",
"purple", "teal", "lightgray"]
light_colors = ["darkgray", "red", "green", "yellow", "blue",
"fuchsia", "turquoise", "white"]
x = 30
for d, l in zip(dark_colors, light_colors):
codes[d] = esc + "%im" % x
codes[l] = esc + "%i;01m" % x
x += 1
del d, l, x
codes["darkteal"] = codes["turquoise"]
codes["darkyellow"] = codes["brown"]
codes["fuscia"] = codes["fuchsia"]
codes["white"] = codes["bold"]
def reset_color():
return codes["reset"]
def colorize(color_key, text):
return codes[color_key] + text + codes["reset"]
def ansiformat(attr, text):
"""
Format ``text`` with a color and/or some attributes::
color normal color
*color* bold color
_color_ underlined color
+color+ blinking color
"""
result = []
if attr[:1] == attr[-1:] == '+':
result.append(codes['blink'])
attr = attr[1:-1]
if attr[:1] == attr[-1:] == '*':
result.append(codes['bold'])
attr = attr[1:-1]
if attr[:1] == attr[-1:] == '_':
result.append(codes['underline'])
attr = attr[1:-1]
result.append(codes[attr])
result.append(text)
result.append(codes['reset'])
return ''.join(result) | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import scipy
from gnuradio import filter
from PyQt4 import QtGui
# Filter design functions using a window
def design_win_lpf(fs, gain, wintype, mainwin):
ret = True
pb,r = mainwin.gui.endofLpfPassBandEdit.text().toDouble()
ret = r and ret
sb,r = mainwin.gui.startofLpfStopBandEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.lpfStopBandAttenEdit.text().toDouble()
ret = r and ret
if(ret):
tb = sb - pb
try:
taps = filter.firdes.low_pass_2(gain, fs, pb, tb,
atten, wintype)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
return ([], [], ret)
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "lpf", "pbend": pb, "sbstart": sb,
"atten": atten, "ntaps": len(taps)}
return (taps, params, ret)
else:
return ([], [], ret)
def design_win_bpf(fs, gain, wintype, mainwin):
ret = True
pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble()
ret = r and ret
pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble()
ret = r and ret
if(ret):
try:
taps = filter.firdes.band_pass_2(gain, fs, pb1, pb2, tb,
atten, wintype)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
return ([], [], ret)
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "bpf", "pbstart": pb1, "pbend": pb2,
"tb": tb, "atten": atten, "ntaps": len(taps)}
return (taps,params,r)
else:
return ([],[],ret)
def design_win_cbpf(fs, gain, wintype, mainwin):
ret = True
pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble()
ret = r and ret
pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble()
ret = r and ret
if(ret):
try:
taps = filter.firdes.complex_band_pass_2(gain, fs, pb1, pb2, tb,
atten, wintype)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
return ([], [], ret)
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "cbpf", "pbstart": pb1, "pbend": pb2,
"tb": tb, "atten": atten, "ntaps": len(taps)}
return (taps,params,r)
else:
return ([],[],ret)
def design_win_bnf(fs, gain, wintype, mainwin):
ret = True
pb1,r = mainwin.gui.startofBnfStopBandEdit.text().toDouble()
ret = r and ret
pb2,r = mainwin.gui.endofBnfStopBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bnfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bnfStopBandAttenEdit.text().toDouble()
ret = r and ret
if(ret):
try:
taps = filter.firdes.band_reject_2(gain, fs, pb1, pb2, tb,
atten, wintype)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
return ([], [], ret)
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "bnf", "sbstart": pb1, "sbend": pb2,
"tb": tb, "atten": atten, "ntaps": len(taps)}
return (taps,params,r)
else:
return ([],[],ret)
def design_win_hpf(fs, gain, wintype, mainwin):
ret = True
sb,r = mainwin.gui.endofHpfStopBandEdit.text().toDouble()
ret = r and ret
pb,r = mainwin.gui.startofHpfPassBandEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.hpfStopBandAttenEdit.text().toDouble()
ret = r and ret
if(ret):
tb = pb - sb
try:
taps = filter.firdes.high_pass_2(gain, fs, pb, tb,
atten, wintype)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "hpf", "sbend": sb, "pbstart": pb,
"atten": atten, "ntaps": len(taps)}
return (taps,params,ret)
else:
return ([],[],ret)
def design_win_hb(fs, gain, wintype, mainwin):
ret = True
filtord,r = mainwin.gui.firhbordEdit.text().toDouble()
ret = r and ret
trwidth,r = mainwin.gui.firhbtrEdit.text().toDouble()
ret = r and ret
filtwin = { filter.firdes.WIN_HAMMING : 'hamming',
filter.firdes.WIN_HANN : 'hanning',
filter.firdes.WIN_BLACKMAN : 'blackman',
filter.firdes.WIN_RECTANGULAR: 'boxcar',
filter.firdes.WIN_KAISER: ('kaiser', 4.0),
filter.firdes.WIN_BLACKMAN_hARRIS: 'blackmanharris'}
if int(filtord) & 1:
reply = QtGui.QMessageBox.information(mainwin, "Filter order should be even",
"Filter order should be even","&Ok")
return ([],[],False)
if(ret):
taps = scipy.signal.firwin(int(filtord)+1, 0.5, window = filtwin[wintype])
taps[abs(taps) <= 1e-6] = 0.
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "hb","ntaps": len(taps)}
return (taps,params,ret)
else:
return ([],[],ret)
def design_win_rrc(fs, gain, wintype, mainwin):
ret = True
sr,r = mainwin.gui.rrcSymbolRateEdit.text().toDouble()
ret = r and ret
alpha,r = mainwin.gui.rrcAlphaEdit.text().toDouble()
ret = r and ret
ntaps,r = mainwin.gui.rrcNumTapsEdit.text().toInt()
ret = r and ret
if(ret):
try:
taps = filter.firdes.root_raised_cosine(gain, fs, sr,
alpha, ntaps)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "rrc", "srate": sr, "alpha": alpha,
"ntaps": ntaps}
return (taps,params,ret)
else:
return ([],[],ret)
def design_win_gaus(fs, gain, wintype, mainwin):
ret = True
sr,r = mainwin.gui.gausSymbolRateEdit.text().toDouble()
ret = r and ret
bt,r = mainwin.gui.gausBTEdit.text().toDouble()
ret = r and ret
ntaps,r = mainwin.gui.gausNumTapsEdit.text().toInt()
ret = r and ret
if(ret):
spb = fs / sr
try:
taps = filter.firdes.gaussian(gain, spb, bt, ntaps)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Runtime Error",
e.args[0], "&Ok")
else:
params = {"fs": fs, "gain": gain, "wintype": wintype,
"filttype": "gaus", "srate": sr, "bt": bt,
"ntaps": ntaps}
return (taps,params,ret)
else:
return ([],[],ret)
# Design Functions for Equiripple Filters
def design_opt_lpf(fs, gain, mainwin):
ret = True
pb,r = mainwin.gui.endofLpfPassBandEdit.text().toDouble()
ret = r and ret
sb,r = mainwin.gui.startofLpfStopBandEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.lpfStopBandAttenEdit.text().toDouble()
ret = r and ret
ripple,r = mainwin.gui.lpfPassBandRippleEdit.text().toDouble()
ret = r and ret
if(ret):
try:
taps = filter.optfir.low_pass(gain, fs, pb, sb,
ripple, atten)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT,
"filttype": "lpf", "pbend": pb, "sbstart": sb,
"atten": atten, "ripple": ripple, "ntaps": len(taps)}
return (taps, params, ret)
else:
return ([], [], ret)
def design_opt_bpf(fs, gain, mainwin):
ret = True
pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble()
ret = r and ret
pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble()
ret = r and ret
ripple,r = mainwin.gui.bpfPassBandRippleEdit.text().toDouble()
ret = r and ret
if(r):
sb1 = pb1 - tb
sb2 = pb2 + tb
try:
taps = filter.optfir.band_pass(gain, fs, sb1, pb1, pb2, sb2,
ripple, atten)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT,
"filttype": "bpf", "pbstart": pb1, "pbend": pb2,
"tb": tb, "atten": atten, "ripple": ripple,
"ntaps": len(taps)}
return (taps,params,r)
else:
return ([],[],r)
def design_opt_cbpf(fs, gain, mainwin):
ret = True
pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble()
ret = r and ret
pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble()
ret = r and ret
ripple,r = mainwin.gui.bpfPassBandRippleEdit.text().toDouble()
ret = r and ret
if(r):
sb1 = pb1 - tb
sb2 = pb2 + tb
try:
taps = filter.optfir.complex_band_pass(gain, fs, sb1, pb1, pb2, sb2,
ripple, atten)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT,
"filttype": "cbpf", "pbstart": pb1, "pbend": pb2,
"tb": tb, "atten": atten, "ripple": ripple,
"ntaps": len(taps)}
return (taps,params,r)
else:
return ([],[],r)
def design_opt_bnf(fs, gain, mainwin):
ret = True
sb1,r = mainwin.gui.startofBnfStopBandEdit.text().toDouble()
ret = r and ret
sb2,r = mainwin.gui.endofBnfStopBandEdit.text().toDouble()
ret = r and ret
tb,r = mainwin.gui.bnfTransitionEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.bnfStopBandAttenEdit.text().toDouble()
ret = r and ret
ripple,r = mainwin.gui.bnfPassBandRippleEdit.text().toDouble()
ret = r and ret
if(ret):
pb1 = sb1 - tb
pb2 = sb2 + tb
try:
taps = filter.optfir.band_reject(gain, fs, pb1, sb1, sb2, pb2,
ripple, atten)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT,
"filttype": "bnf", "sbstart": pb1, "sbend": pb2,
"tb": tb, "atten": atten, "ripple": ripple,
"ntaps": len(taps)}
return (taps,params,ret)
else:
return ([],[],ret)
def design_opt_hb(fs, gain, mainwin):
ret = True
filtord,r = mainwin.gui.firhbordEdit.text().toDouble()
ret = r and ret
trwidth,r = mainwin.gui.firhbtrEdit.text().toDouble()
ret = r and ret
if int(filtord) & 1:
reply = QtGui.QMessageBox.information(mainwin, "Filter order should be even",
"Filter order should be even","&Ok")
return ([],[],False)
if(ret):
try:
bands = [0,.25 - (trwidth/fs), .25 + (trwidth/fs), 0.5]
taps = scipy.signal.remez(int(filtord)+1, bands, [1,0], [1,1])
taps[abs(taps) <= 1e-6] = 0.
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter Design Error",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT,
"filttype": "hb", "ntaps": len(taps)}
return (taps,params,ret)
else:
return ([],[],ret)
def design_opt_hpf(fs, gain, mainwin):
ret = True
sb,r = mainwin.gui.endofHpfStopBandEdit.text().toDouble()
ret = r and ret
pb,r = mainwin.gui.startofHpfPassBandEdit.text().toDouble()
ret = r and ret
atten,r = mainwin.gui.hpfStopBandAttenEdit.text().toDouble()
ret = r and ret
ripple,r = mainwin.gui.hpfPassBandRippleEdit.text().toDouble()
ret = r and ret
if(ret):
try:
taps = filter.optfir.high_pass(gain, fs, sb, pb,
atten, ripple)
except RuntimeError, e:
reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge",
e.args[0], "&Ok")
return ([],[],False)
else:
params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT,
"filttype": "hpf", "sbend": sb, "pbstart": pb,
"atten": atten, "ripple": ripple,
"ntaps": len(taps)}
return (taps,params,ret)
else:
return ([],[],ret) | unknown | codeparrot/codeparrot-clean | ||
/*
* Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty
import io.netty.channel.*
import io.netty.channel.epoll.*
import io.netty.channel.kqueue.*
import io.netty.channel.nio.*
import io.netty.channel.socket.*
import io.netty.util.concurrent.*
import java.lang.reflect.*
import java.util.concurrent.*
import kotlin.reflect.*
/**
* Transparently allows for the creation of [EventLoopGroup]'s utilising the optimal implementation for
* a given operating system, subject to availability, or falling back to [NioEventLoopGroup] if none is available.
*
* [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.server.netty.EventLoopGroupProxy)
*/
public class EventLoopGroupProxy(
public val channel: KClass<out ServerSocketChannel>,
group: EventLoopGroup
) : EventLoopGroup by group {
public companion object {
public fun create(parallelism: Int): EventLoopGroupProxy {
val defaultFactory = DefaultThreadFactory(EventLoopGroupProxy::class.java, true)
val channelClass = getChannelClass()
return when {
KQueue.isAvailable() -> EventLoopGroupProxy(
channelClass,
KQueueEventLoopGroup(parallelism, defaultFactory)
)
Epoll.isAvailable() -> EventLoopGroupProxy(
channelClass,
EpollEventLoopGroup(parallelism, defaultFactory)
)
else -> EventLoopGroupProxy(channelClass, NioEventLoopGroup(parallelism, defaultFactory))
}
}
}
} | kotlin | github | https://github.com/ktorio/ktor | ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/EventLoopGroupProxy.kt |
"""
Views for returning XModule JS (used by requirejs)
"""
import json
from django.conf import settings
from django.http import HttpResponse
from staticfiles.storage import staticfiles_storage
from edxmako.shortcuts import render_to_response
def get_xmodule_urls():
"""
Returns a list of the URLs to hit to grab all the XModule JS
"""
if settings.DEBUG:
paths = [path.replace(".coffee", ".js") for path in
settings.PIPELINE_JS['module-js']['source_filenames']]
else:
paths = [settings.PIPELINE_JS['module-js']['output_filename']]
return [staticfiles_storage.url(path) for path in paths]
def xmodule_js_files(request):
"""
View function that returns XModule URLs as a JSON list; meant to be used
as an API
"""
urls = get_xmodule_urls()
return HttpResponse(json.dumps(urls), content_type="application/json")
def requirejs_xmodule(request):
"""
View function that returns a requirejs-wrapped Javascript file that
loads all the XModule URLs; meant to be loaded via requireJS
"""
return render_to_response(
"xmodule.js",
{"urls": get_xmodule_urls()},
content_type="text/javascript",
) | unknown | codeparrot/codeparrot-clean | ||
/*
* Copyright 2010-2025 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.symbols
import org.jetbrains.kotlin.analysis.api.annotations.KaAnnotationList
import org.jetbrains.kotlin.analysis.api.fir.KaFirSession
import org.jetbrains.kotlin.analysis.api.fir.hasRegularGetter
import org.jetbrains.kotlin.analysis.api.impl.base.symbols.pointers.KaBasePropertyGetterSymbolPointer
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.symbols.KaPropertyGetterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaReceiverParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaSymbolModality
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KaSymbolPointer
import org.jetbrains.kotlin.analysis.api.types.KaType
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.utils.exceptions.withFirSymbolEntry
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.utils.exceptions.requireWithAttachment
import org.jetbrains.kotlin.utils.exceptions.withPsiEntry
/** Represents a custom getter */
internal class KaFirPropertyGetterSymbol(
override val owningKaProperty: KaFirKotlinPropertySymbol<KtProperty>,
) : KaPropertyGetterSymbol(), KaFirBasePropertyGetterSymbol {
init {
requireWithAttachment(
backingPsi?.property?.hasRegularGetter != false,
{ "Property getter without a body" },
) {
withPsiEntry("propertyGetter", backingPsi)
withFirSymbolEntry("firSymbol", firSymbol)
}
}
override val isExpect: Boolean
get() = isExpectImpl
override val isNotDefault: Boolean
get() = withValidityAssertion { true }
@Deprecated("Use `!isNotDefault` instead", replaceWith = ReplaceWith("!isNotDefault"))
override val isDefault: Boolean
get() = isDefaultImpl
override val isInline: Boolean
get() = isInlineImpl
override val isOverride: Boolean
get() = isOverrideImpl
@Deprecated("Use `isCustom` instead", replaceWith = ReplaceWith("isCustom"))
override val hasBody: Boolean
get() = hasBodyImpl
override val modality: KaSymbolModality
get() = modalityImpl
override val compilerVisibility: Visibility
get() = compilerVisibilityImpl
override val returnType: KaType
get() = returnTypeImpl
override val receiverParameter: KaReceiverParameterSymbol?
get() = receiverParameterImpl
override val annotations: KaAnnotationList
get() = annotationsImpl
override val callableId: CallableId?
get() = callableIdImpl
override val isExternal: Boolean
get() = isExternalImpl
override fun createPointer(): KaSymbolPointer<KaPropertyGetterSymbol> = withValidityAssertion {
psiBasedSymbolPointerOfTypeIfSource<KaPropertyGetterSymbol>()
?: KaBasePropertyGetterSymbolPointer(propertySymbolPointer = owningKaProperty.createPointer(), originalSymbol = this)
}
override fun equals(other: Any?): Boolean = psiOrSymbolEquals(other)
override fun hashCode(): Int = psiOrSymbolHashCode()
companion object {
fun create(declaration: KtPropertyAccessor, session: KaFirSession): KaPropertyGetterSymbol {
val property = declaration.property
val owningKaProperty = with(session) {
@Suppress("UNCHECKED_CAST")
property.symbol as KaFirKotlinPropertySymbol<KtProperty>
}
return if (property.hasRegularGetter) {
KaFirPropertyGetterSymbol(owningKaProperty)
} else {
KaFirDefaultPropertyGetterSymbol(owningKaProperty)
}
}
}
} | kotlin | github | https://github.com/JetBrains/kotlin | analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/symbols/KaFirPropertyGetterSymbol.kt |
#
# A Python binding for cracklib.
#
# Parts of this code are based on work Copyright (c) 2003 by Domenico
# Andreoli.
#
# Copyright (c) 2008, 2009 Jan Dittberner <jan@dittberner.info>
#
# This file is part of cracklib.
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""Python extensions for the cracklib binding.
"""
import string
from _cracklib import FascistCheck
ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
DIFF_OK = 5
MIN_LENGTH = 9
DIG_CREDIT = 1
UP_CREDIT = 1
LOW_CREDIT = 1
OTH_CREDIT = 1
def palindrome(sample):
"""Checks whether the given string is a palindrome.
"""
for i in range(len(sample)):
if sample[i] != sample[-i - 1]:
return 0
return 1
def distdifferent(old, new, i, j):
"""Calculate how different two strings are in terms of the number
of character removals, additions, and changes needed to go from one
to the other."""
if i == 0 or len(old) <= i:
cval = 0
else:
cval = old[i - 1]
if j == 0 or len(new) <= i:
dval = 0
else:
dval = new[j - 1]
return cval != dval
def distcalculate(distances, old, new, i, j):
"""Calculates the distance between two strings.
"""
tmp = 0
if distances[i][j] != -1:
return distances[i][j]
tmp = distcalculate(distances, old, new, i - 1, j - 1)
tmp = min(tmp, distcalculate(distances, old, new, i , j - 1))
tmp = min(tmp, distcalculate(distances, old, new, i - 1, j ))
tmp = tmp + distdifferent(old, new, i, j)
distances[i][j] = tmp
return tmp
def distance(old, new):
"""Gets the distance of two given strings.
"""
oldlength = len(old)
newlength = len(new)
distances = [ [] for i in range(oldlength + 1) ]
for i in range(oldlength + 1):
distances[i] = [ -1 for j in range(newlength + 1) ]
for i in range(oldlength + 1):
distances[i][0] = i
for j in range(newlength + 1):
distances[0][j] = j
distances[0][0] = 0
retval = distcalculate(distances, old, new, oldlength, newlength)
for i in range(len(distances)):
for j in range(len(distances[i])):
distances[i][j] = 0
return retval
def similar(old, new):
"""Calculates whether the given strings are similar.
"""
if distance(old, new) >= DIFF_OK:
return 0
if len(new) >= (len(old) * 2):
return 0
# passwords are too similar
return 1
def simple(new):
"""Checks whether the given string is simple or not.
"""
digits = 0
uppers = 0
lowers = 0
others = 0
for character in new:
if character in string.digits:
digits = digits + 1
elif character in ASCII_UPPERCASE:
uppers = uppers + 1
elif character in ASCII_LOWERCASE:
lowers = lowers + 1
else:
others = others + 1
# The scam was this - a password of only one character type
# must be 8 letters long. Two types, 7, and so on.
# This is now changed, the base size and the credits or defaults
# see the docs on the module for info on these parameters, the
# defaults cause the effect to be the same as before the change
if DIG_CREDIT >= 0 and digits > DIG_CREDIT:
digits = DIG_CREDIT
if UP_CREDIT >= 0 and uppers > UP_CREDIT:
uppers = UP_CREDIT
if LOW_CREDIT >= 0 and lowers > LOW_CREDIT:
lowers = LOW_CREDIT
if OTH_CREDIT >= 0 and others > OTH_CREDIT:
others = OTH_CREDIT
size = MIN_LENGTH
if DIG_CREDIT >= 0:
size = size - digits
elif digits < (DIG_CREDIT * -1):
return 1
if UP_CREDIT >= 0:
size = size - uppers
elif uppers < (UP_CREDIT * -1):
return 1
if LOW_CREDIT >= 0:
size = size - lowers
elif lowers < (LOW_CREDIT * -1):
return 1
if OTH_CREDIT >= 0:
size = size - others
elif others < (OTH_CREDIT * -1):
return 1
if len(new) < size:
return 1
return 0
def VeryFascistCheck(new, old = None, dictpath = None):
"""Extends the FascistCheck function with other checks implemented
in this module.
"""
if old != None:
if new == old:
raise ValueError, "is the same as the old one"
oldmono = old.lower()
newmono = new.lower()
wrapped = old + old
if newmono == oldmono:
raise ValueError, "case changes only"
if wrapped.find(new) != -1:
raise ValueError, "is rotated"
if similar(oldmono, newmono):
raise ValueError, "is too similar to the old one"
if dictpath == None:
FascistCheck(new)
else:
FascistCheck(new, dictpath)
if palindrome(new):
raise ValueError, "is a palindrome"
if simple(new):
raise ValueError, "is too simple"
return new | unknown | codeparrot/codeparrot-clean | ||
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
"""
The I{schema} module provides a intelligent representation of
an XSD schema. The I{raw} model is the XML tree and the I{model}
is the denormalized, objectified and intelligent view of the schema.
Most of the I{value-add} provided by the model is centered around
tranparent referenced type resolution and targeted denormalization.
"""
import suds.metrics
from suds import *
from suds.xsd import *
from suds.xsd.sxbuiltin import *
from suds.xsd.sxbasic import Factory as BasicFactory
from suds.xsd.sxbuiltin import Factory as BuiltinFactory
from suds.xsd.sxbase import SchemaObject
from suds.xsd.deplist import DepList
from suds.sax.element import Element
from suds.sax import splitPrefix, Namespace
from logging import getLogger
log = getLogger(__name__)
class SchemaCollection:
"""
A collection of schema objects. This class is needed because WSDLs
may contain more then one <schema/> node.
@ivar wsdl: A wsdl object.
@type wsdl: L{suds.wsdl.Definitions}
@ivar children: A list contained schemas.
@type children: [L{Schema},...]
@ivar namespaces: A dictionary of contained schemas by namespace.
@type namespaces: {str:L{Schema}}
"""
def __init__(self, wsdl):
"""
@param wsdl: A wsdl object.
@type wsdl: L{suds.wsdl.Definitions}
"""
self.wsdl = wsdl
self.children = []
self.namespaces = {}
def add(self, schema):
"""
Add a schema node to the collection. Schema(s) within the same target
namespace are consolidated.
@param schema: A schema object.
@type schema: (L{Schema})
"""
key = schema.tns[1]
existing = self.namespaces.get(key)
if existing is None:
self.children.append(schema)
self.namespaces[key] = schema
else:
existing.root.children += schema.root.children
existing.root.nsprefixes.update(schema.root.nsprefixes)
def load(self, options):
"""
Load the schema objects for the root nodes.
- de-references schemas
- merge schemas
@param options: An options dictionary.
@type options: L{options.Options}
@return: The merged schema.
@rtype: L{Schema}
"""
if options.autoblend:
self.autoblend()
for child in self.children:
child.build()
for child in self.children:
child.open_imports(options)
for child in self.children:
child.dereference()
log.debug('loaded:\n%s', self)
merged = self.merge()
log.debug('MERGED:\n%s', merged)
return merged
def autoblend(self):
"""
Ensure that all schemas within the collection
import each other which has a blending effect.
@return: self
@rtype: L{SchemaCollection}
"""
namespaces = self.namespaces.keys()
for s in self.children:
for ns in namespaces:
tns = s.root.get('targetNamespace')
if tns == ns:
continue
for imp in s.root.getChildren('import'):
if imp.get('namespace') == ns:
continue
imp = Element('import', ns=Namespace.xsdns)
imp.set('namespace', ns)
s.root.append(imp)
return self
def locate(self, ns):
"""
Find a schema by namespace. Only the URI portion of
the namespace is compared to each schema's I{targetNamespace}
@param ns: A namespace.
@type ns: (prefix,URI)
@return: The schema matching the namesapce, else None.
@rtype: L{Schema}
"""
return self.namespaces.get(ns[1])
def merge(self):
"""
Merge the contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
"""
if len(self):
schema = self.children[0]
for s in self.children[1:]:
schema.merge(s)
return schema
else:
return None
def __len__(self):
return len(self.children)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
result = ['\nschema collection']
for s in self.children:
result.append(s.str(1))
return '\n'.join(result)
class Schema:
"""
The schema is an objectification of a <schema/> (xsd) definition.
It provides inspection, lookup and type resolution.
@ivar root: The root node.
@type root: L{sax.element.Element}
@ivar baseurl: The I{base} URL for this schema.
@type baseurl: str
@ivar container: A schema collection containing this schema.
@type container: L{SchemaCollection}
@ivar children: A list of direct top level children.
@type children: [L{SchemaObject},...]
@ivar all: A list of all (includes imported) top level children.
@type all: [L{SchemaObject},...]
@ivar types: A schema types cache.
@type types: {name:L{SchemaObject}}
@ivar imports: A list of import objects.
@type imports: [L{SchemaObject},...]
@ivar elements: A list of <element/> objects.
@type elements: [L{SchemaObject},...]
@ivar attributes: A list of <attribute/> objects.
@type attributes: [L{SchemaObject},...]
@ivar groups: A list of group objects.
@type groups: [L{SchemaObject},...]
@ivar agrps: A list of attribute group objects.
@type agrps: [L{SchemaObject},...]
@ivar form_qualified: The flag indicating:
(@elementFormDefault).
@type form_qualified: bool
"""
Tag = 'schema'
def __init__(self, root, baseurl, options, container=None):
"""
@param root: The xml root.
@type root: L{sax.element.Element}
@param baseurl: The base url used for importing.
@type baseurl: basestring
@param options: An options dictionary.
@type options: L{options.Options}
@param container: An optional container.
@type container: L{SchemaCollection}
"""
self.root = root
self.id = objid(self)
self.tns = self.mktns()
self.baseurl = baseurl
self.container = container
self.children = []
self.all = []
self.types = {}
self.imports = []
self.elements = {}
self.attributes = {}
self.groups = {}
self.agrps = {}
if options.doctor is not None:
options.doctor.examine(root)
form = self.root.get('elementFormDefault')
if form is None:
self.form_qualified = False
else:
self.form_qualified = ( form == 'qualified' )
if container is None:
self.build()
self.open_imports(options)
log.debug('built:\n%s', self)
self.dereference()
log.debug('dereferenced:\n%s', self)
def mktns(self):
"""
Make the schema's target namespace.
@return: The namespace representation of the schema's
targetNamespace value.
@rtype: (prefix, uri)
"""
tns = [None, self.root.get('targetNamespace')]
if tns[1] is not None:
tns[0] = self.root.findPrefix(tns[1])
return tuple(tns)
def build(self):
"""
Build the schema (object graph) using the root node
using the factory.
- Build the graph.
- Collate the children.
"""
self.children = BasicFactory.build(self.root, self)
collated = BasicFactory.collate(self.children)
self.children = collated[0]
self.attributes = collated[2]
self.imports = collated[1]
self.elements = collated[3]
self.types = collated[4]
self.groups = collated[5]
self.agrps = collated[6]
def merge(self, schema):
"""
Merge the contents from the schema. Only objects not already contained
in this schema's collections are merged. This is to provide for bidirectional
import which produce cyclic includes.
@returns: self
@rtype: L{Schema}
"""
for item in schema.attributes.items():
if item[0] in self.attributes:
continue
self.all.append(item[1])
self.attributes[item[0]] = item[1]
for item in schema.elements.items():
if item[0] in self.elements:
continue
self.all.append(item[1])
self.elements[item[0]] = item[1]
for item in schema.types.items():
if item[0] in self.types:
continue
self.all.append(item[1])
self.types[item[0]] = item[1]
for item in schema.groups.items():
if item[0] in self.groups:
continue
self.all.append(item[1])
self.groups[item[0]] = item[1]
for item in schema.agrps.items():
if item[0] in self.agrps:
continue
self.all.append(item[1])
self.agrps[item[0]] = item[1]
schema.merged = True
return self
def open_imports(self, options):
"""
Instruct all contained L{sxbasic.Import} children to import
the schema's which they reference. The contents of the
imported schema are I{merged} in.
@param options: An options dictionary.
@type options: L{options.Options}
"""
for imp in self.imports:
imported = imp.open(options)
if imported is None:
continue
imported.open_imports(options)
log.debug('imported:\n%s', imported)
self.merge(imported)
def dereference(self):
"""
Instruct all children to perform dereferencing.
"""
all = []
indexes = {}
for child in self.children:
child.content(all)
deplist = DepList()
for x in all:
x.qualify()
midx, deps = x.dependencies()
item = (x, tuple(deps))
deplist.add(item)
indexes[x] = midx
for x, deps in deplist.sort():
midx = indexes.get(x)
if midx is None: continue
d = deps[midx]
log.debug('(%s) merging %s <== %s', self.tns[1], Repr(x), Repr(d))
x.merge(d)
def locate(self, ns):
"""
Find a schema by namespace. Only the URI portion of
the namespace is compared to each schema's I{targetNamespace}.
The request is passed to the container.
@param ns: A namespace.
@type ns: (prefix,URI)
@return: The schema matching the namesapce, else None.
@rtype: L{Schema}
"""
if self.container is not None:
return self.container.locate(ns)
else:
return None
def custom(self, ref, context=None):
"""
Get whether the specified reference is B{not} an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if B{not} a builtin, else False.
@rtype: bool
"""
if ref is None:
return True
else:
return ( not self.builtin(ref, context) )
def builtin(self, ref, context=None):
"""
Get whether the specified reference is an (xs) builtin.
@param ref: A str or qref.
@type ref: (str|qref)
@return: True if builtin, else False.
@rtype: bool
"""
w3 = 'http://www.w3.org'
try:
if isqref(ref):
ns = ref[1]
return ( ref[0] in Factory.tags and ns.startswith(w3) )
if context is None:
context = self.root
prefix = splitPrefix(ref)[0]
prefixes = context.findPrefixes(w3, 'startswith')
return ( prefix in prefixes and ref[0] in Factory.tags )
except:
return False
def instance(self, root, baseurl, options):
"""
Create and return an new schema object using the
specified I{root} and I{url}.
@param root: A schema root node.
@type root: L{sax.element.Element}
@param baseurl: A base URL.
@type baseurl: str
@param options: An options dictionary.
@type options: L{options.Options}
@return: The newly created schema object.
@rtype: L{Schema}
@note: This is only used by Import children.
"""
return Schema(root, baseurl, options)
def str(self, indent=0):
tab = '%*s'%(indent*3, '')
result = []
result.append('%s%s' % (tab, self.id))
result.append('%s(raw)' % tab)
result.append(self.root.str(indent+1))
result.append('%s(model)' % tab)
for c in self.children:
result.append(c.str(indent+1))
result.append('')
return '\n'.join(result)
def __repr__(self):
myrep = '<%s tns="%s"/>' % (self.id, self.tns[1])
return myrep.encode('utf-8')
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.str() | unknown | codeparrot/codeparrot-clean | ||
import web
from functools import wraps
from social.utils import setting_name, module_member
from social.backends.utils import user_backends_data
from social.strategies.utils import get_strategy
DEFAULTS = {
'STRATEGY': 'social.strategies.webpy_strategy.WebpyStrategy',
'STORAGE': 'social.apps.webpy_app.models.WebpyStorage'
}
def get_helper(name, do_import=False):
config = web.config.get(setting_name(name),
DEFAULTS.get(name, None))
return do_import and module_member(config) or config
def load_strategy(*args, **kwargs):
backends = get_helper('AUTHENTICATION_BACKENDS')
strategy = get_helper('STRATEGY')
storage = get_helper('STORAGE')
return get_strategy(backends, strategy, storage, *args, **kwargs)
def strategy(redirect_uri=None):
def decorator(func):
@wraps(func)
def wrapper(self, backend=None, *args, **kwargs):
uri = redirect_uri
if uri and backend and '%(backend)s' in uri:
uri = uri % {'backend': backend}
self.strategy = load_strategy(request=web.ctx, backend=backend,
redirect_uri=uri, *args, **kwargs)
if backend:
return func(self, backend=backend, *args, **kwargs)
else:
return func(self, *args, **kwargs)
return wrapper
return decorator
def backends(user):
"""Load Social Auth current user data to context under the key 'backends'.
Will return the output of social.backends.utils.user_backends_data."""
return user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'),
get_helper('STORAGE', do_import=True))
def login_redirect():
"""Load current redirect to context."""
method = web.ctx.method == 'POST' and 'post' or 'get'
data = web.input(_method=method)
value = data.get('next')
return {
'REDIRECT_FIELD_NAME': 'next',
'REDIRECT_FIELD_VALUE': value,
'REDIRECT_QUERYSTRING': value and ('next=' + value) or ''
} | unknown | codeparrot/codeparrot-clean | ||
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkPositive;
import static com.google.common.collect.Lists.newArrayListWithExpectedSize;
import static com.google.common.collect.Maps.safeGet;
import static java.lang.Math.max;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.jspecify.annotations.Nullable;
/**
* A multiset that supports concurrent modifications and that provides atomic versions of most
* {@code Multiset} operations (exceptions where noted). Null elements are not supported.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset">{@code Multiset}</a>.
*
* @author Cliff L. Biffle
* @author mike nonemacher
* @since 2.0
*/
@J2ktIncompatible
@GwtIncompatible
public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {
/*
* The ConcurrentHashMultiset's atomic operations are implemented primarily in terms of
* AtomicInteger's atomic operations, with some help from ConcurrentMap's atomic operations on
* creation and removal (including automatic removal of zeroes). If the modification of an
* AtomicInteger results in zero, we compareAndSet the value to zero; if that succeeds, we remove
* the entry from the Map. If another operation sees a zero in the map, it knows that the entry is
* about to be removed, so this operation may remove it (often by replacing it with a new
* AtomicInteger).
*/
/** The number of occurrences of each element. */
private final transient ConcurrentMap<E, AtomicInteger> countMap;
/**
* An instance created in {@link #readObject} to be returned from {@link #readResolve}. This field
* is used only by those methods, and it is never set in a "normal" instance.
*
* <p>This class needs to write deserialized data into fields that are {@code final transient}.
* Such writes will become impossible to perform in {@link #readObject} after JEP 500. Instead, we
* must create a new instance with the desired field values, stash it in this field, and then
* instruct Java serialization to use it instead of the originally created object.
*
* <p>We have chosen this approach over at least two alternatives:
*
* <ul>
* <li>We could change the serialization of this class incompatibly. We have reserved the right
* to make such changes to our serialized forms, and we have made them before, usually
* without trouble. In this case, my guess is that our chosen approach is even less likely
* to lead to trouble than an incompatible change would be.
* <li>We could make {@link #countMap} no longer be {@code final}. Then we could write to it
* directly during deserialization. However, we would lose Java's guarantees for {@code
* final} fields, including that their values are guaranteed to be visible even when an
* instance is unsafely published.
* </ul>
*/
private transient @Nullable ConcurrentHashMultiset<E> deserializationReplacement;
/**
* Creates a new, empty {@code ConcurrentHashMultiset} using the default initial capacity, load
* factor, and concurrency settings.
*/
public static <E> ConcurrentHashMultiset<E> create() {
return create(new ConcurrentHashMap<>());
}
/**
* Creates a new {@code ConcurrentHashMultiset} containing the specified elements, using the
* default initial capacity, load factor, and concurrency settings.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) {
ConcurrentHashMultiset<E> multiset = create();
Iterables.addAll(multiset, elements);
return multiset;
}
/**
* Creates a new, empty {@code ConcurrentHashMultiset} using {@code countMap} as the internal
* backing map.
*
* <p>This instance will assume ownership of {@code countMap}, and other code should not maintain
* references to the map or modify it in any way.
*
* <p>The returned multiset is serializable if the input map is.
*
* @param countMap backing map for storing the elements in the multiset and their counts. It must
* be empty.
* @throws IllegalArgumentException if {@code countMap} is not empty
* @since 20.0
*/
public static <E> ConcurrentHashMultiset<E> create(ConcurrentMap<E, AtomicInteger> countMap) {
checkArgument(countMap.isEmpty(), "the backing map (%s) must be empty", countMap);
return new ConcurrentHashMultiset<>(countMap);
}
private ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) {
this.countMap = countMap;
}
// Query Operations
/**
* Returns the number of occurrences of {@code element} in this multiset.
*
* @param element the element to look for
* @return the nonnegative number of occurrences of the element
*/
@Override
public int count(@Nullable Object element) {
AtomicInteger existingCounter = safeGet(countMap, element);
return (existingCounter == null) ? 0 : existingCounter.get();
}
/**
* {@inheritDoc}
*
* <p>If the data in the multiset is modified by any other threads during this method, it is
* undefined which (if any) of these modifications will be reflected in the result.
*/
@Override
public int size() {
long sum = 0L;
for (AtomicInteger value : countMap.values()) {
sum += value.get();
}
return Ints.saturatedCast(sum);
}
/*
* We override the toArray methods for two reasons:
*
* 1. Both superclass toArray methods assume that size() gives a correct answer, while our size()
* might not (and the answer might change while we're building the array).
*
* TODO: cpovirk - Is this an issue anywhere anymore? It looks to have been fixed for Java 8
* (https://bugs.openjdk.org/browse/JDK-7121314) and before Lollipop
* (https://r.android.com/47508). We *would* need to worry for J2KT, whose own concurrency support
* is evolving (b/381065164, b/458160722), but this class is @J2ktIncompatible.
*
* 2. The superclass toArray() method declares the more general return type `@Nullable Object[]`,
* but we know that our values will never be `null`.
*/
@Override
public Object[] toArray() {
return snapshotElementsToList().toArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return snapshotElementsToList().toArray(array);
}
/*
* We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but
* either of these would recurse back to us again!
*/
private List<E> snapshotElementsToList() {
List<E> list = newArrayListWithExpectedSize(size());
for (Multiset.Entry<E> entry : entrySet()) {
E element = entry.getElement();
for (int i = entry.getCount(); i > 0; i--) {
list.add(element);
}
}
return list;
}
// Modification Operations
/**
* Adds a number of occurrences of the specified element to this multiset.
*
* @param element the element to add
* @param occurrences the number of occurrences to add
* @return the previous count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if the resulting amount
* would exceed {@link Integer#MAX_VALUE}
*/
@CanIgnoreReturnValue
@Override
public int add(E element, int occurrences) {
checkNotNull(element);
if (occurrences == 0) {
return count(element);
}
checkPositive(occurrences, "occurrences");
while (true) {
AtomicInteger existingCounter = safeGet(countMap, element);
if (existingCounter == null) {
existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences));
if (existingCounter == null) {
return 0;
}
// existingCounter != null: fall through to operate against the existing AtomicInteger
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue != 0) {
try {
int newValue = Math.addExact(oldValue, occurrences);
if (existingCounter.compareAndSet(oldValue, newValue)) {
// newValue can't == 0, so no need to check & remove
return oldValue;
}
} catch (ArithmeticException overflow) {
throw new IllegalArgumentException(
"Overflow adding " + occurrences + " occurrences to a count of " + oldValue);
}
} else {
// In the case of a concurrent remove, we might observe a zero value, which means another
// thread is about to remove (element, existingCounter) from the map. Rather than wait,
// we can just do that work here.
AtomicInteger newCounter = new AtomicInteger(occurrences);
if ((countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter)) {
return 0;
}
break;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes a number of occurrences of the specified element from this multiset. If the multiset
* contains fewer than this number of occurrences to begin with, all occurrences will be removed.
*
* @param element the element whose occurrences should be removed
* @param occurrences the number of occurrences of the element to remove
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
/*
* TODO(cpovirk): remove and removeExactly currently accept null inputs only
* if occurrences == 0. This satisfies both NullPointerTester and
* CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's
* a good policy, especially because, in order for the test to pass, the
* parameter must be misleadingly annotated as @Nullable. I suspect that
* we'll want to remove @Nullable, add an eager checkNotNull, and loosen up
* testRemove_nullAllowed.
*/
@CanIgnoreReturnValue
@Override
public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkPositive(occurrences, "occurrences");
AtomicInteger existingCounter = safeGet(countMap, element);
if (existingCounter == null) {
return 0;
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue != 0) {
int newValue = max(0, oldValue - occurrences);
if (existingCounter.compareAndSet(oldValue, newValue)) {
if (newValue == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return oldValue;
}
} else {
return 0;
}
}
}
/**
* Removes exactly the specified number of occurrences of {@code element}, or makes no change if
* this is not possible.
*
* <p>This method, in contrast to {@link #remove(Object, int)}, has no effect when the element
* count is smaller than {@code occurrences}.
*
* @param element the element to remove
* @param occurrences the number of occurrences of {@code element} to remove
* @return {@code true} if the removal was possible (including if {@code occurrences} is zero)
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
@CanIgnoreReturnValue
public boolean removeExactly(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return true;
}
checkPositive(occurrences, "occurrences");
AtomicInteger existingCounter = safeGet(countMap, element);
if (existingCounter == null) {
return false;
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue < occurrences) {
return false;
}
int newValue = oldValue - occurrences;
if (existingCounter.compareAndSet(oldValue, newValue)) {
if (newValue == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return true;
}
}
}
/**
* Adds or removes occurrences of {@code element} such that the {@link #count} of the element
* becomes {@code count}.
*
* @return the count of {@code element} in the multiset before this call
* @throws IllegalArgumentException if {@code count} is negative
*/
@CanIgnoreReturnValue
@Override
public int setCount(E element, int count) {
checkNotNull(element);
checkNonnegative(count, "count");
while (true) {
AtomicInteger existingCounter = safeGet(countMap, element);
if (existingCounter == null) {
if (count == 0) {
return 0;
} else {
existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count));
if (existingCounter == null) {
return 0;
}
// existingCounter != null: fall through
}
}
while (true) {
int oldValue = existingCounter.get();
if (oldValue == 0) {
if (count == 0) {
return 0;
} else {
AtomicInteger newCounter = new AtomicInteger(count);
if ((countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter)) {
return 0;
}
}
break;
} else {
if (existingCounter.compareAndSet(oldValue, count)) {
if (count == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return oldValue;
}
}
}
}
}
/**
* Sets the number of occurrences of {@code element} to {@code newCount}, but only if the count is
* currently {@code expectedOldCount}. If {@code element} does not appear in the multiset exactly
* {@code expectedOldCount} times, no changes will be made.
*
* @return {@code true} if the change was successful. This usually indicates that the multiset has
* been modified, but not always: in the case that {@code expectedOldCount == newCount}, the
* method will return {@code true} if the condition was met.
* @throws IllegalArgumentException if {@code expectedOldCount} or {@code newCount} is negative
*/
@CanIgnoreReturnValue
@Override
public boolean setCount(E element, int expectedOldCount, int newCount) {
checkNotNull(element);
checkNonnegative(expectedOldCount, "oldCount");
checkNonnegative(newCount, "newCount");
AtomicInteger existingCounter = safeGet(countMap, element);
if (existingCounter == null) {
if (expectedOldCount != 0) {
return false;
} else if (newCount == 0) {
return true;
} else {
// if our write lost the race, it must have lost to a nonzero value, so we can stop
return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null;
}
}
int oldValue = existingCounter.get();
if (oldValue == expectedOldCount) {
if (oldValue == 0) {
if (newCount == 0) {
// Just observed a 0; try to remove the entry to clean up the map
countMap.remove(element, existingCounter);
return true;
} else {
AtomicInteger newCounter = new AtomicInteger(newCount);
return (countMap.putIfAbsent(element, newCounter) == null)
|| countMap.replace(element, existingCounter, newCounter);
}
} else {
if (existingCounter.compareAndSet(oldValue, newCount)) {
if (newCount == 0) {
// Just CASed to 0; remove the entry to clean up the map. If the removal fails,
// another thread has already replaced it with a new counter, which is fine.
countMap.remove(element, existingCounter);
}
return true;
}
}
}
return false;
}
// Views
@Override
Set<E> createElementSet() {
Set<E> delegate = countMap.keySet();
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return delegate;
}
@Override
public boolean contains(@Nullable Object object) {
return object != null && Collections2.safeContains(delegate, object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return standardContainsAll(collection);
}
@Override
public boolean remove(@Nullable Object object) {
return object != null && Collections2.safeRemove(delegate, object);
}
@Override
public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
};
}
@Override
Iterator<E> elementIterator() {
throw new AssertionError("should never be called");
}
/**
* @deprecated Internal method, use {@link #entrySet()}.
*/
@Deprecated
@Override
public Set<Multiset.Entry<E>> createEntrySet() {
return new EntrySet();
}
@Override
int distinctElements() {
return countMap.size();
}
@Override
public boolean isEmpty() {
return countMap.isEmpty();
}
@Override
Iterator<Entry<E>> entryIterator() {
// AbstractIterator makes this fairly clean, but it doesn't support remove(). To support
// remove(), we create an AbstractIterator, and then use ForwardingIterator to delegate to it.
Iterator<Entry<E>> readOnlyIterator =
new AbstractIterator<Entry<E>>() {
private final Iterator<Map.Entry<E, AtomicInteger>> mapEntries =
countMap.entrySet().iterator();
@Override
protected @Nullable Entry<E> computeNext() {
while (true) {
if (!mapEntries.hasNext()) {
return endOfData();
}
Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next();
int count = mapEntry.getValue().get();
if (count != 0) {
return Multisets.immutableEntry(mapEntry.getKey(), count);
}
}
}
};
return new ForwardingIterator<Entry<E>>() {
private @Nullable Entry<E> last;
@Override
protected Iterator<Entry<E>> delegate() {
return readOnlyIterator;
}
@Override
public Entry<E> next() {
last = super.next();
return last;
}
@Override
public void remove() {
checkState(last != null, "no calls to next() since the last call to remove()");
ConcurrentHashMultiset.this.setCount(last.getElement(), 0);
last = null;
}
};
}
@Override
public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override
public void clear() {
countMap.clear();
}
@WeakOuter
private final class EntrySet extends AbstractMultiset<E>.EntrySet {
@Override
ConcurrentHashMultiset<E> multiset() {
return ConcurrentHashMultiset.this;
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override
public Object[] toArray() {
return snapshot().toArray();
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
private List<Multiset.Entry<E>> snapshot() {
List<Multiset.Entry<E>> list = newArrayListWithExpectedSize(size());
// Not Iterables.addAll(list, this), because that'll forward right back here.
Iterators.addAll(list, iterator());
return list;
}
}
/**
* @serialData the ConcurrentMap of elements and their counts.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(countMap);
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
@SuppressWarnings("unchecked") // reading data stored by writeObject
ConcurrentMap<E, AtomicInteger> deserializedCountMap =
(ConcurrentMap<E, AtomicInteger>) requireNonNull(stream.readObject());
deserializationReplacement = new ConcurrentHashMultiset<>(deserializedCountMap);
}
private Object readResolve() {
return requireNonNull(deserializationReplacement); // set by readObject
}
private static final long serialVersionUID = 1;
} | java | github | https://github.com/google/guava | android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java |
/*
This is a WebAssembly userland setjmp/longjmp implementation based on Binaryen's Asyncify.
Inspired by Alon Zakai's snippet released under the MIT License:
* https://github.com/kripken/talks/blob/991fb1e4b6d7e4b0ea6b3e462d5643f11d422771/jmp.c
WebAssembly doesn't have context-switching mechanism for now, so emulate it by Asyncify,
which transforms WebAssembly binary to unwind/rewind the execution point and store/restore
locals.
The basic concept of this implementation is:
1. setjmp captures the current execution context by unwinding to the root frame, then immediately
rewind to the setjmp call using the captured context. The context is saved in jmp_buf.
2. longjmp unwinds to the root frame and rewinds to a setjmp call re-using a passed jmp_buf.
This implementation also supports switching context across different call stack (non-standard)
This approach is good at behavior reproducibility and self-containedness compared to Emscripten's
JS exception approach. However this is super expensive because Asyncify inserts many glue code to
control execution point in userland.
This implementation will be replaced with future stack-switching feature.
*/
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include "wasm/asyncify.h"
#include "wasm/machine.h"
#include "wasm/setjmp.h"
#ifdef RB_WASM_ENABLE_DEBUG_LOG
# include <wasi/api.h>
# include <unistd.h>
// NOTE: We can't use printf() and most of library function that are
// Asyncified due to the use of them in the application itself.
// Use of printf() causes "unreachable" error because Asyncified
// function misunderstands Asyncify's internal state during
// start_unwind()...stop_unwind() and start_rewind()...stop_rewind().
# define RB_WASM_DEBUG_LOG_INTERNAL(msg) do { \
const uint8_t *msg_start = (uint8_t *)msg; \
const uint8_t *msg_end = msg_start; \
for (; *msg_end != '\0'; msg_end++) {} \
__wasi_ciovec_t iov = {.buf = msg_start, .buf_len = msg_end - msg_start}; \
size_t nwritten; \
__wasi_fd_write(STDERR_FILENO, &iov, 1, &nwritten); \
} while (0)
# define RB_WASM_DEBUG_LOG(msg) \
RB_WASM_DEBUG_LOG_INTERNAL(__FILE__ ":" STRINGIZE(__LINE__) ": " msg "\n")
#else
# define RB_WASM_DEBUG_LOG(msg)
#endif
enum rb_wasm_jmp_buf_state {
// Initial state
JMP_BUF_STATE_INITIALIZED = 0,
// Unwinding to the root or rewinding to the setjmp call
// to capture the current execution context
JMP_BUF_STATE_CAPTURING = 1,
// Ready for longjmp
JMP_BUF_STATE_CAPTURED = 2,
// Unwinding to the root or rewinding to the setjmp call
// to restore the execution context
JMP_BUF_STATE_RETURNING = 3,
};
void
async_buf_init(struct __rb_wasm_asyncify_jmp_buf* buf)
{
buf->top = &buf->buffer[0];
buf->end = &buf->buffer[WASM_SETJMP_STACK_BUFFER_SIZE];
}
// Global unwinding/rewinding jmpbuf state
static rb_wasm_jmp_buf *_rb_wasm_active_jmpbuf;
void *rb_asyncify_unwind_buf;
__attribute__((noinline))
int
_rb_wasm_setjmp_internal(rb_wasm_jmp_buf *env)
{
RB_WASM_DEBUG_LOG("enter _rb_wasm_setjmp_internal");
switch (env->state) {
case JMP_BUF_STATE_INITIALIZED: {
RB_WASM_DEBUG_LOG(" JMP_BUF_STATE_INITIALIZED");
env->state = JMP_BUF_STATE_CAPTURING;
env->payload = 0;
env->longjmp_buf_ptr = NULL;
_rb_wasm_active_jmpbuf = env;
async_buf_init(&env->setjmp_buf);
asyncify_start_unwind(&env->setjmp_buf);
return -1; // return a dummy value
}
case JMP_BUF_STATE_CAPTURING: {
asyncify_stop_rewind();
RB_WASM_DEBUG_LOG(" JMP_BUF_STATE_CAPTURING");
env->state = JMP_BUF_STATE_CAPTURED;
_rb_wasm_active_jmpbuf = NULL;
return 0;
}
case JMP_BUF_STATE_RETURNING: {
asyncify_stop_rewind();
RB_WASM_DEBUG_LOG(" JMP_BUF_STATE_RETURNING");
env->state = JMP_BUF_STATE_CAPTURED;
_rb_wasm_active_jmpbuf = NULL;
return env->payload;
}
default:
assert(0 && "unexpected state");
}
return 0;
}
void
_rb_wasm_longjmp(rb_wasm_jmp_buf* env, int value)
{
RB_WASM_DEBUG_LOG("enter _rb_wasm_longjmp");
assert(env->state == JMP_BUF_STATE_CAPTURED);
assert(value != 0);
env->state = JMP_BUF_STATE_RETURNING;
env->payload = value;
// Asyncify buffer built during unwinding for longjmp will not
// be used to rewind, so re-use static-variable.
static struct __rb_wasm_asyncify_jmp_buf tmp_longjmp_buf;
env->longjmp_buf_ptr = &tmp_longjmp_buf;
_rb_wasm_active_jmpbuf = env;
async_buf_init(env->longjmp_buf_ptr);
asyncify_start_unwind(env->longjmp_buf_ptr);
}
enum try_catch_phase {
TRY_CATCH_PHASE_MAIN = 0,
TRY_CATCH_PHASE_RESCUE = 1,
};
void
rb_wasm_try_catch_init(struct rb_wasm_try_catch *try_catch,
rb_wasm_try_catch_func_t try_f,
rb_wasm_try_catch_func_t catch_f,
void *context)
{
try_catch->state = TRY_CATCH_PHASE_MAIN;
try_catch->try_f = try_f;
try_catch->catch_f = catch_f;
try_catch->context = context;
try_catch->stack_pointer = NULL;
}
// NOTE: This function is not processed by Asyncify due to a call of asyncify_stop_rewind
__attribute__((noinline))
void
rb_wasm_try_catch_loop_run(struct rb_wasm_try_catch *try_catch, rb_wasm_jmp_buf *target)
{
extern void *rb_asyncify_unwind_buf;
extern rb_wasm_jmp_buf *_rb_wasm_active_jmpbuf;
target->state = JMP_BUF_STATE_CAPTURED;
if (try_catch->stack_pointer == NULL) {
try_catch->stack_pointer = rb_wasm_get_stack_pointer();
}
switch ((enum try_catch_phase)try_catch->state) {
case TRY_CATCH_PHASE_MAIN:
// may unwind
try_catch->try_f(try_catch->context);
break;
case TRY_CATCH_PHASE_RESCUE:
if (try_catch->catch_f) {
// may unwind
try_catch->catch_f(try_catch->context);
}
break;
}
{
// catch longjmp with target jmp_buf
while (rb_asyncify_unwind_buf && _rb_wasm_active_jmpbuf == target) {
// do similar steps setjmp does when JMP_BUF_STATE_RETURNING
// stop unwinding
// (but call stop_rewind to update the asyncify state to "normal" from "unwind")
asyncify_stop_rewind();
// reset the stack pointer to what it was before the most recent call to try_f or catch_f
rb_wasm_set_stack_pointer(try_catch->stack_pointer);
// clear the active jmpbuf because it's already stopped
_rb_wasm_active_jmpbuf = NULL;
// reset jmpbuf state to be able to unwind again
target->state = JMP_BUF_STATE_CAPTURED;
// move to catch loop phase
try_catch->state = TRY_CATCH_PHASE_RESCUE;
if (try_catch->catch_f) {
try_catch->catch_f(try_catch->context);
}
}
// no unwind or unrelated unwind, then exit
}
}
void *
rb_wasm_handle_jmp_unwind(void)
{
RB_WASM_DEBUG_LOG("enter rb_wasm_handle_jmp_unwind");
if (!_rb_wasm_active_jmpbuf) {
return NULL;
}
switch (_rb_wasm_active_jmpbuf->state) {
case JMP_BUF_STATE_CAPTURING:
RB_WASM_DEBUG_LOG(" JMP_BUF_STATE_CAPTURING");
// save the captured Asyncify stack top
_rb_wasm_active_jmpbuf->dst_buf_top = _rb_wasm_active_jmpbuf->setjmp_buf.top;
break;
case JMP_BUF_STATE_RETURNING:
RB_WASM_DEBUG_LOG(" JMP_BUF_STATE_RETURNING");
// restore the saved Asyncify stack top
_rb_wasm_active_jmpbuf->setjmp_buf.top = _rb_wasm_active_jmpbuf->dst_buf_top;
break;
default:
assert(0 && "unexpected state");
}
return &_rb_wasm_active_jmpbuf->setjmp_buf;
} | c | github | https://github.com/ruby/ruby | wasm/setjmp.c |
from fabric.api import env, sudo, run, cd, local, put, prefix, roles, execute, task
from fabric.api import settings as fab_settings
from geonodes import GEONODE_INSTANCES as GN
def _build_env(target):
if target in GN:
GNT = GN[target]
e = {
'user': GNT['user'],
'hosts': [GNT['host']],
'host_string': GNT['host'],
'key_filename': GNT['ident'],
}
return e
else:
print "Could not initialize environment for target {t}.".format(t=target)
return None
def _run_task(task, args=None, kwargs=None):
from fabfile import targets
if targets:
for target in targets:
env = _build_env(target)
if env:
with fab_settings(** env):
_run_task_core(task, args, kwargs)
else:
_run_task_core(task, args, kwargs)
def _run_task_core(task, args, kwargs):
if task:
if args:
task(* args)
elif kwargs:
task(** kwargs)
else:
task()
def _cron_command(f, u, c, filename):
template = 'echo "{f} {u} {c}" > /etc/cron.d/{filename}'
cmd = template.format(f=f, u=u, c=c, filename=filename)
return cmd
def _load_template(filename):
data = None
with open ('templates/'+filename, "r") as f:
data = f.read()
return data
def _request_input(question, value, required, options=None):
if value:
return value
else:
if options:
print question+" :"
print "* Options Below."+(" Enter to skip." if not required else "")
for opt in options:
print "| -- "+opt
print "* Select option:",
else:
print question+":",
if required:
value = None
while not value:
value = raw_input()
if not value:
print "Value required. Please try again. Ctrl+C to cancel."
print question+":",
elif options and (not value in options):
print "Must select one of the options. Ctrl+C to cancel."
print question+":",
value = None
return value
else:
while not value:
value = raw_input()
if not value:
return None
elif options and (not value in options):
print "Must select one of the options. Enter to skip. Ctrl+C to cancel."
print question+":",
value = None
return value
def _request_continue():
print "Continue (y/n)?",
confirm = raw_input()
return confirm and confirm.lower() == "y"
def _append_to_file(lines, filename):
print "Appending to file..."
print ""
sudo("echo '' >> {f}".format(f=filename))
for line in lines:
t = "echo '{line}' >> {f}"
c = t.format(line=line.replace('"','\"'), f=filename)
sudo(c) | unknown | codeparrot/codeparrot-clean | ||
kind: Service
apiVersion: v1
metadata:
name: the-service
spec:
selector:
deployment: hello
type: LoadBalancer
ports:
- protocol: TCP
port: 8666
targetPort: 8080 | unknown | github | https://github.com/kubernetes/kubernetes | hack/testdata/kustomize/service.yaml |
/*
* Copyright 2012-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docker.compose.core;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
/**
* Tests for {@link DockerEnv}.
*
* @author Moritz Halbritter
* @author Andy Wilkinson
* @author Phillip Webb
*/
class DockerEnvTests {
@Test
void createWhenEnvIsNullReturnsEmpty() {
DockerEnv env = new DockerEnv(null);
assertThat(env.asMap()).isEmpty();
}
@Test
void createWhenEnvIsEmptyReturnsEmpty() {
DockerEnv env = new DockerEnv(Collections.emptyList());
assertThat(env.asMap()).isEmpty();
}
@Test
void createParsesEnv() {
DockerEnv env = new DockerEnv(List.of("a=b", "c"));
assertThat(env.asMap()).containsExactly(entry("a", "b"), entry("c", null));
}
} | java | github | https://github.com/spring-projects/spring-boot | core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/DockerEnvTests.java |
__author__ = 'rcj1492'
__created__ = '2017.05'
__license__ = 'MIT'
'''
list services
list instances (ec2, heroku)
TODO: list images
TODO: list containers
TODO: list instances on other platforms (gcp, azure, bluemix, rackspace)
'''
_list_details = {
'title': 'List',
'description': 'Generates a list of the resources of a specific type. Only the service resource type is supported, but docker oriented and remote host kinds of resources are coming.',
'help': 'lists the instances of a resource type',
'benefit': 'Provides a way to find existing resources.'
}
from pocketlab.init import fields_model
def list(resource_type, platform_option, region_name='', paginate=False, all_info=False):
title = 'list'
# validate inputs
if isinstance(platform_option, str):
if platform_option:
platform_option = [platform_option]
input_fields = {
'resource_type': resource_type,
'platform_option': platform_option,
'region_name': region_name
}
for key, value in input_fields.items():
if value:
object_title = '%s(%s=%s)' % (title, key, str(value))
fields_model.validate(value, '.%s' % key, object_title)
# retrieve window size
from os import popen
console_rows, console_columns = popen('stty size', 'r').read().split()
console_rows = int(console_rows)
console_columns = int(console_columns)
# construct default print out fields
exit_msg = ''
formatted_rows = []
table_headers = []
# list services
if resource_type == 'services':
# construct registry client
from pocketlab import __module__
from labpack.storage.appdata import appdataClient
registry_client = appdataClient(collection_name='Registry Data', prod_name=__module__)
# walk registry to compile list of services
from tabulate import tabulate
from labpack.records.settings import load_settings
service_list = []
left_width = 0
table_headers = ['Service', 'Path']
for file_path in registry_client.localhost.walk(registry_client.collection_folder):
try:
details = load_settings(file_path)
service_name = details['service_name']
service_root = details['service_root']
if len(service_name) > left_width:
left_width = len(service_name)
service_list.append([service_name, service_root])
except:
pass
# format list of services
for row in service_list:
row_width = left_width + 2 + len(row[1])
path_text = row[1]
if row_width > console_columns:
cut_char = row_width - console_columns
left_index = (len(row[1]) - cut_char - 12) * -1
if left_index > -1:
path_text = '%s...' % row[1]
else:
path_text = '%s...%s' % (row[1][0:9], row[1][left_index:])
formatted_rows.append([row[0], path_text])
# list instances
elif resource_type == 'instances':
# determine platform name
if not platform_option:
from copy import deepcopy
from labpack.parsing.grammar import join_words
platform_list = deepcopy(fields_model.components['.platform_name']['discrete_values'])
if len(platform_list) > 2:
platform_list = platform_list[0:2]
platform_options = join_words(platform_list, operator='disjunction')
raise ValueError('list instances requires a platform name (eg. %s)' % platform_options)
platform_name = platform_option[0]
# compile service list
from pocketlab.methods.service import compile_services
service_list = compile_services()
# construct empty instance list
instance_list = []
# process heroku
if platform_name == 'heroku':
# compile instances
print('Compiling instance list from heroku ... ', end='', flush=True)
from pocketlab.methods.heroku import compile_instances
instance_list = compile_instances(service_list)
print('done.')
# process ec2
elif platform_name == 'ec2':
# TODO compile across accounts and regions
# compile instances
print('Compiling instance list from ec2 ... ', end='', flush=True)
from pocketlab.methods.aws import compile_instances
instance_list = compile_instances(region_name)
print('done.')
# TODO add http code ???
# format list of instances
table_headers = [ 'Name', 'Machine', 'Services', 'Env', 'IP Address', 'State' ]
instance_keys = [ 'name', 'machine', 'services', 'environment', 'ip_address', 'state' ]
if all_info:
table_headers.pop()
instance_keys.pop()
# table_headers.insert(0, 'Name')
# instance_keys.insert(0, 'name')
table_headers.extend(['Region', 'Login', 'Instance Id', 'Image Id', 'Tags', 'State'])
instance_keys.extend(['region', 'login', 'id', 'image', 'tags', 'state'])
for instance in instance_list:
instance_row = []
for key in instance_keys:
instance_row.append(instance[key])
formatted_rows.append(instance_row)
# list images
elif resource_type == 'images':
pass
# list containers
elif resource_type == 'containers':
container_headers = [ 'NAMES', 'STATUS', 'IMAGE', 'PORTS']
# print out list
if formatted_rows:
from tabulate import tabulate
# handle pagination
if paginate and len(formatted_rows) + 5 > console_rows:
page_rows = []
for i in range(len(formatted_rows)):
page_rows.append(formatted_rows[i])
if len(page_rows) + 4 == console_rows:
table_text = tabulate(page_rows, headers=table_headers)
table_text += '\n[press any key for more]'
print(table_text)
page_rows = []
input()
elif i + 1 == len(formatted_rows):
table_text = tabulate(page_rows, headers=table_headers)
if len(page_rows) + 5 == console_rows:
table_text += '\n[press any key for more]'
print(table_text)
if len(page_rows) + 5 == console_rows:
input()
# no pagination
else:
table_text = tabulate(formatted_rows, headers=table_headers)
print(table_text)
return exit_msg | unknown | codeparrot/codeparrot-clean | ||
"""Master process which detects hardware and launches controllers."""
import collections
import json
import logging
import multiprocessing
import select
import shutil
import socket
import threading
import time
from pathlib import Path
import pyudev
import setproctitle
from .devices import BOARDS
LOGGER = logging.getLogger(__name__)
class Connection:
"""
A connection to a device.
This wraps a ``socket.socket`` providing encoding and decoding so that
consumers of this class can send and receive JSON-compatible typed data
rather than needing to worry about lower-level details.
"""
def __init__(self, socket):
"""Wrap the given socket."""
self.socket = socket
self.data = b''
def close(self):
"""Close the connection."""
self.socket.close()
def send(self, message):
"""Send the given JSON-compatible message over the connection."""
line = json.dumps(message).encode('utf-8') + b'\n'
self.socket.sendall(line)
def receive(self):
"""Receive a single message from the connection."""
while b'\n' not in self.data:
message = self.socket.recv(4096)
if message == b'':
return None
self.data += message
line = self.data.split(b'\n', 1)[0]
self.data = self.data[len(line) + 1:]
return json.loads(line.decode('utf-8'))
class BoardRunner(multiprocessing.Process):
"""Control process for one board."""
def __init__(self, board, root_dir, **kwargs):
super().__init__(**kwargs)
self.board = board
self.socket_path = (
Path(root_dir) / type(board).board_type_id / board.name(board.node)
)
self._prepare_socket_path()
self.connections = {}
def _prepare_socket_path(self):
try:
self.socket_path.parent.mkdir(parents=True)
except FileExistsError:
if self.socket_path.exists():
LOGGER.warning('removing old %r', self.socket_path)
self._delete_socket_path()
def _delete_socket_path(self):
try:
self.socket_path.unlink()
except FileNotFoundError:
pass
def _create_server_socket(self):
server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_socket.bind(str(self.socket_path))
server_socket.listen(5)
self.socket_path.chmod(0o777)
LOGGER.info('Listening on: %s', self.socket_path)
setproctitle.setproctitle('robotd {}: {}'.format(
type(self.board).board_type_id,
type(self.board).name(self.board.node),
))
return server_socket
def broadcast(self, message):
"""Broadcast a message over all connections."""
message = dict(message)
message['broadcast'] = True
for connection in self.connections.values():
try:
connection.send(message)
except ConnectionRefusedError:
self.connections.remove(connection)
def _send_board_status(self, connection):
board_status = self.board.status()
LOGGER.debug('Sending board status: %s', board_status)
connection.send(board_status)
def _send_command_response(self, connection, response):
message = {'response': response}
LOGGER.debug('Sending command response: %s', message)
connection.send(message)
def run(self):
"""
Control this board.
This is the entry point from the control subprocess and its job is to:
* Create and manage the UNIX socket in `/var/robotd`,
* Pass on commands to the `board`,
* Call `make_safe` whenever the last user disconnects,
* Deal with error handling and shutdown.
"""
server_socket = self._create_server_socket()
self.board.broadcast = self.broadcast
self.board.start()
try:
while True:
self._process_connections(server_socket)
finally:
self.board.make_safe()
def _process_connections(self, server_socket):
connection_sockets = list(self.connections.keys())
# Wait until one of the sockets is ready to read.
readable, _, errorable = select.select(
# connections that want to read
[server_socket] + connection_sockets,
# connections that want to write
[],
# connections that want to error
connection_sockets,
)
# New connections
if server_socket in readable:
new_socket, _ = server_socket.accept()
new_connection = Connection(new_socket)
readable.append(new_socket)
self.connections[new_socket] = new_connection
LOGGER.info('New connection at: %s', self.socket_path)
self._send_board_status(new_connection)
dead_sockets = []
for sock in readable:
try:
connection = self.connections[sock]
except KeyError:
continue
command = connection.receive()
if command is None:
dead_sockets.append(sock)
continue
if command != {}:
response = self.board.command(command)
if response is not None:
self._send_command_response(connection, response)
self._send_board_status(connection)
dead_sockets.extend(errorable)
self._close_dead_sockets(dead_sockets)
if dead_sockets and not self.connections:
LOGGER.info('Last connection closed')
self.board.make_safe()
def _close_dead_sockets(self, dead_sockets):
for sock in dead_sockets:
try:
del self.connections[sock]
except KeyError:
pass
sock.close()
def cleanup(self):
"""
Clean up the UNIX socket if it's been left around.
Called from the parent process.
"""
self._delete_socket_path()
self.board.stop()
class MasterProcess(object):
"""The mighty God object which manages the controllers."""
def __init__(self, root_dir):
self.runners = collections.defaultdict(dict)
self.context = pyudev.Context()
self.root_dir = Path(root_dir)
self.root_dir.mkdir(mode=0o755, parents=True, exist_ok=True)
self.clear_socket_files()
self.runners_lock = threading.Lock()
# Init the startup boards
for board_type in BOARDS:
if board_type.create_on_startup:
self._start_board_instance(board_type, 'startup')
def clear_socket_files(self):
for path in self.root_dir.iterdir():
shutil.rmtree(str(path))
def tick(self):
"""Poll udev for any new or missing boards."""
for board_type in BOARDS:
if hasattr(board_type, 'lookup_keys'):
nodes = self.context.list_devices(**board_type.lookup_keys)
initialized_nodes = [n for n in nodes if n.is_initialized]
self._process_device_list(board_type, initialized_nodes)
def cleanup(self):
"""Shut down all the controllers."""
for board_type in BOARDS:
self._process_device_list(board_type, [])
self.stop_monitor()
def _process_device_list(self, board_type, nodes):
with self.runners_lock:
nodes_by_path = {
x.device_path: x
for x in nodes
if board_type.included(x)
}
actual_paths = set(nodes_by_path.keys())
expected_paths = set(self.runners[board_type].keys())
missing_paths = expected_paths - actual_paths
new_paths = actual_paths - expected_paths
for new_device in new_paths:
LOGGER.info(
'Detected new %s: %s (%s)',
board_type.__name__,
new_device,
board_type.name(nodes_by_path[new_device]),
)
self._start_board_instance(
board_type,
new_device,
node=nodes_by_path[new_device],
)
for dead_device in missing_paths:
LOGGER.info('Disconnected %s: %s', board_type.__name__, dead_device)
runner = self.runners[board_type][dead_device]
runner.terminate()
runner.join()
runner.cleanup()
del self.runners[board_type][dead_device]
def _start_board_instance(self, board_type, new_device, **kwargs):
instance = board_type(**kwargs)
runner = BoardRunner(instance, self.root_dir)
runner.start()
self.runners[board_type][new_device] = runner
def launch_monitor(self):
self.monitor_stop_flag = False
self.monitor_thread = threading.Thread(target=self._monitor_thread)
self.monitor_thread.start()
def stop_monitor(self):
self.monitor_stop_flag = True
self.monitor_thread.join()
def _monitor_thread(self):
while True:
if self.monitor_stop_flag:
return
time.sleep(0.5)
with self.runners_lock:
for board_type, runners in list(self.runners.items()):
for device_id, runner_process in list(runners.items()):
if not runner_process.is_alive():
LOGGER.info('Dead worker: %s(%s)', board_type, device_id)
# This worker has died and needs to be reaped
del self.runners[board_type][device_id]
def main(**kwargs):
"""Main entry point."""
master = MasterProcess(**kwargs)
setproctitle.setproctitle('robotd master')
master.launch_monitor()
try:
while True:
master.tick()
time.sleep(1)
except KeyboardInterrupt:
master.cleanup()
def main_cmdline():
"""Command line entry point."""
import argparse
parser = argparse.ArgumentParser()
default_root_dir = Path('/var/robotd')
parser.add_argument(
'--root-dir',
type=Path,
help='directory to run root of robotd at (defaults to {})'.format(
default_root_dir,
),
default=default_root_dir,
)
args = parser.parse_args()
main(root_dir=args.root_dir)
if __name__ == '__main__':
main_cmdline() | unknown | codeparrot/codeparrot-clean |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.