file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/coffee/__about__.py | Python | # SPDX-FileCopyrightText: 2024-present Will McGugan <willmcgugan@gmail.com>
#
# SPDX-License-Identifier: MIT
__version__ = "0.0.1"
| willmcgugan/coffee | 22 | Coffee shop with Textual | Python | willmcgugan | Will McGugan | |
src/coffee/__init__.py | Python | # SPDX-FileCopyrightText: 2024-present Will McGugan <willmcgugan@gmail.com>
#
# SPDX-License-Identifier: MIT
| willmcgugan/coffee | 22 | Coffee shop with Textual | Python | willmcgugan | Will McGugan | |
src/coffee/__main__.py | Python | import asyncio
from dataclasses import dataclass
from decimal import Decimal
from textual import work
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical, VerticalScroll, Center
from textual.events import Resize
from textual.widgets import (
Button,
Input,
Static,
Label,
ContentSwitcher,
Markdown,
)
from textual.reactive import reactive
ABOUT_MD = """\
### About
This was a Sunday afternoon coding session, just for fun.
It has no connection to terminal.shop.
Brought to you by @willmcgugan, head code monkey at Textualize.
"""
@dataclass
class Product:
name: str
sku: str
price: Decimal
description: str
PRODUCTS = [
Product(
name="nil blend coffee",
sku="whole bean | medium roast | 12oz",
price=Decimal("25"),
description="Dive into the rich taste of Nil, our delicious semi-sweet coffee with notes of chocolate, peanut butter, and a hint of fig.",
),
Product(
name="None blend coffee",
sku="whole bean | light roast | 500g",
price=Decimal("19.95"),
description="Delicious honey method coffee, with hints of caramel",
),
]
@dataclass
class Question:
q: str
a: str
FAQS = [
Question(
"where do you ship?",
"We don't ship. But if you visit @willmcgugan, he may make you a cup of coffee.",
),
Question(
"is your coffee ethically sourced?",
"Not sure. I get it from the place around the corner.",
),
Question(
"is ordering via ssh secure?", "it is. But you can't order anything from here."
),
Question(
"how do you store my data?",
"We don't store anything. Close the browser and it is though we never met.",
),
Question(
"I only want to drink Nil / None, do you offer a subscription?",
"The coffee is made up, so no, we don't offer a subscription.",
),
Question(
"Will Nil / None make me a better developer?",
"Coffee is known to give super-human coding prowess. So yes.",
),
Question(
"Does coffee from the command line taste better than regular coffee?",
"Depends on your shell and OS.",
),
]
class Column(Vertical):
pass
class NonFocusableVerticalScroll(VerticalScroll, can_focus=False):
pass
class Footer(Horizontal):
def compose(self) -> ComposeResult:
yield Label("Footer goes here")
class Panel(Vertical):
def __init__(self, label: str, id: str) -> None:
self.label = label
super().__init__(id=id)
def compose(self) -> ComposeResult:
yield VerticalScroll(classes="content")
yield Footer()
class OrderCounter(Horizontal):
order_count = reactive(0, recompose=True)
def compose(self) -> ComposeResult:
yield Label("-", classes="minus")
yield Label(str(self.order_count), classes="count")
yield Label("+", classes="plus")
class ProductWidget(Vertical, can_focus=True):
order_count: reactive[int] = reactive(0)
BINDINGS = [
("minus", "order(-1)"),
("plus", "order(+1)"),
]
def __init__(self, product: Product, classes: str) -> None:
self.product = product
super().__init__(classes=classes)
def compose(self) -> ComposeResult:
yield Static(self.product.name, classes="name")
yield Static(self.product.sku, classes="sku")
yield Static(f"${self.product.price:.02f}", classes="price")
yield Static(self.product.description, classes="description")
yield OrderCounter().data_bind(ProductWidget.order_count)
def action_order(self, delta: int) -> None:
self.order_count = max(0, self.order_count + delta)
class ProductsPanel(Vertical):
def compose(self) -> ComposeResult:
with NonFocusableVerticalScroll():
for product in PRODUCTS:
yield ProductWidget(product, classes="auto-focus")
yield Label(
"[b]tab[/] [dim]next product[/] [b]+[/] [dim]add[/dim] [b]-[/] [dim]remove[/dim] [b]c[/] [dim]cart[/] [b]q[/] [dim]quit[/dim]",
classes="footer",
)
class AboutPanel(Vertical):
def compose(self) -> ComposeResult:
with Vertical(classes="content auto-focus"):
yield Markdown(ABOUT_MD)
yield Label("[b]↑↓[/] [dim]scroll[/] [b]c[/] [dim]cart[/]", classes="footer")
class FAQPanel(Vertical):
def compose(self) -> ComposeResult:
with VerticalScroll(classes="content auto-focus"):
for question in FAQS:
yield Static(question.q, classes="question")
yield Static(question.a, classes="answer")
yield Label(
"[b]↑↓[/] [dim]scroll[/] [b]c[/] [dim]cart[/]",
classes="footer",
)
class CartPanel(Vertical):
BINDINGS = [("escape", "blur")]
def compose(self) -> ComposeResult:
with VerticalScroll(classes="content auto-focus"):
yield Label("name")
yield Input("", placeholder="Your name")
yield Label("Credit card")
yield Input("", placeholder="XXXX-XXXX-XXXX-XXXX")
yield Label("Address 1")
yield Input()
yield Label("Address 2")
yield Input()
yield Label("Zip / Postcode")
yield Input()
yield Button("Place order", variant="success")
yield Label(
"[b]tab[/] [dim]next[/] [b]shift+tab[/] [dim]previous[/] [b]escape[/] [dim]exit form[/dim]",
classes="footer",
)
def action_blur(self) -> None:
if self.app.focused:
self.query_one(VerticalScroll).focus()
@work
async def on_button_pressed(self):
self.query_one(".content").loading = True
self.notify("Nothing is really happening. Please wait five seconds.")
await asyncio.sleep(5)
self.notify("And we are back. Again, nothing happened.")
self.query_one(".content").loading = False
class Header(Container):
active_panel = reactive("shop", recompose=True)
def compose(self) -> ComposeResult:
active_panel = self.active_panel
yield Label("[b not dim]terminal")
yield Label(
"[not dim]s[/] shop", classes="active" if active_panel == "shop" else ""
)
yield Label(
"[not dim]a[/] about", classes="active" if active_panel == "about" else ""
)
yield Label(
"[not dim]f[/] faq", classes="active" if active_panel == "faq" else ""
)
yield Label(
"[not dim]c[/] cart", classes="active" if active_panel == "cart" else ""
)
class CoffeeApp(App):
CSS_PATH = "coffee.tcss"
DEFAULT_CLASSES = "narrow"
active_panel: reactive[str] = reactive("shop")
BINDINGS = [
("s", "switch_panel('shop')"),
("a", "switch_panel('about')"),
("f", "switch_panel('faq')"),
("c", "switch_panel('cart')"),
("q", "quit"),
]
def compose(self) -> ComposeResult:
with Column():
with Center():
yield Header().data_bind(CoffeeApp.active_panel)
with ContentSwitcher(initial="shop"):
yield ProductsPanel(id="shop")
yield AboutPanel(id="about")
yield FAQPanel(id="faq")
yield CartPanel(id="cart")
def on_app_focus(self) -> None:
self.query("ContentSwitcher #shop .auto-focus").first().focus()
def action_switch_panel(self, panel: str) -> None:
self.active_panel = panel
self.query_one(ContentSwitcher).current = panel
self.query(f"ContentSwitcher #{panel} .auto-focus").first().focus()
def on_resize(self, event: Resize) -> None:
self.query_one("Screen").set_class(self.size.width < 60, "narrow")
if __name__ == "__main__":
app = CoffeeApp()
app.run()
| willmcgugan/coffee | 22 | Coffee shop with Textual | Python | willmcgugan | Will McGugan | |
tests/__init__.py | Python | # SPDX-FileCopyrightText: 2024-present Will McGugan <willmcgugan@gmail.com>
#
# SPDX-License-Identifier: MIT
| willmcgugan/coffee | 22 | Coffee shop with Textual | Python | willmcgugan | Will McGugan | |
examples/color.py | Python | import declare
from declare import Declare
class Color:
"""A color object with RGB, and alpha components."""
red = declare.Int(0)
green = declare.Int(0)
blue = declare.Int(0)
alpha = declare.Float(1.0)
@red.validate
@green.validate
@blue.validate
def _validate_component(self, component: int) -> int:
"""Restrict RGB to 0 -> 255."""
return max(0, min(255, component))
@alpha.validate
def _validate_alpha(self, alpha: float) -> float:
return max(0.0, min(1.0, alpha))
@alpha.watch
def _watch_alpha(self, old_alpha: float, alpha: float) -> None:
print(f"alpha changed from {old_alpha} to {alpha}!")
class Palette:
name = declare.Str("")
colors = Declare[list[Color]]([])
if __name__ == "__main__":
red = Color()
red.red = 300
red.alpha = 0.5
print(red.red, red.green, red.blue)
palette = Palette()
palette.colors = [Color()]
| willmcgugan/declare | 66 | Syntactical sugar for Python class attributes | Python | willmcgugan | Will McGugan | |
src/declare/__init__.py | Python | from __future__ import annotations
from ._declare import Declare as Declare
from ._declare import watch as watch
__all__ = [
"Declare",
"Int",
"Float",
"Bool",
"Str",
"Bytes",
"watch",
]
Int: type[Declare[int]] = Declare
Float: type[Declare[float]] = Declare
Bool: type[Declare[bool]] = Declare
Str: type[Declare[str]] = Declare
Bytes: type[Declare[bytes]] = Declare
| willmcgugan/declare | 66 | Syntactical sugar for Python class attributes | Python | willmcgugan | Will McGugan | |
src/declare/_declare.py | Python | from __future__ import annotations
from copy import copy
from typing import Any, TYPE_CHECKING, Generic, Type, TypeVar, cast, overload
if TYPE_CHECKING:
from collections.abc import Callable
from typing_extensions import TypeAlias
ObjectType = TypeVar("ObjectType")
ValueType = TypeVar("ValueType")
Validator: TypeAlias = "Callable[[ObjectType, ValueType], ValueType]"
Watcher: TypeAlias = "Callable[[ObjectType, ValueType | None, ValueType], None]"
ValidateMethodType = TypeVar("ValidateMethodType", bound=Validator)
WatchMethodType = TypeVar("WatchMethodType", bound=Watcher)
class NoValue:
"""Sentinel type."""
_NO_VALUE = NoValue()
class DeclareError(Exception):
"""Raised when an Declare related error occurs,"""
class ValidateDecorator(Generic[ValidateMethodType]):
"""Validate decorator.
Decorate a Widget method to make it a validator for the attribute.
"""
def __init__(self, declare: Declare | None = None) -> None:
self._declare = declare
self._validator: ValidateMethodType | None = None
@overload
def __call__(self) -> ValidateDecorator[ValidateMethodType]: ...
@overload
def __call__(self, method: ValidateMethodType) -> ValidateMethodType: ...
def __call__(
self, method: ValidateMethodType | None = None
) -> ValidateMethodType | ValidateDecorator[ValidateMethodType]:
if method is None:
return self
assert self._declare is not None
if self._declare._validator is not None:
raise DeclareError(f"A validator has already been set on {self._declare!r}")
self._declare._validator = method
return method
class WatchDecorator(Generic[WatchMethodType]):
"""Validate decorator.
Decorate a Widget method to make it a validator for the attribute.
"""
def __init__(self, declare: Declare | None = None) -> None:
self._declare = declare
@overload
def __call__(self) -> WatchDecorator[WatchMethodType]: ...
@overload
def __call__(self, method: WatchMethodType) -> WatchMethodType: ...
def __call__(
self, method: WatchMethodType | None = None
) -> WatchMethodType | WatchDecorator[WatchMethodType]:
if method is None:
return self
assert self._declare is not None
self._declare._watchers.add(method)
return method
class Declare(Generic[ValueType]):
"""A descriptor to declare attributes."""
def __init__(
self,
default: ValueType,
*,
validate: Validator | None = None,
watchers: set[Watcher] | None = None,
) -> None:
self._name = ""
self._private_name = ""
self._default = default
self._validator = validate
self._watchers = set(watchers) if watchers is not None else set()
self._copy_default = not isinstance(default, (int, float, bool, str, complex))
def copy(self) -> Declare[ValueType]:
"""Return a copy of the Declare descriptor.
Returns:
A Declare descriptor.
"""
declare = Declare(
self._default,
validate=self._validator,
watchers=set(self._watchers),
)
return declare
def __call__(
self,
default: ValueType | NoValue = _NO_VALUE,
*,
validate: Validator | None = None,
watchers: set[Watcher] | None = None,
) -> Declare[ValueType]:
"""Update the declaration.
Args:
default: New default.
validate: A validator function.
watchers: A set of watch functions.
Returns:
A new Declare.
"""
declare = self.copy()
if not isinstance(default, NoValue):
declare._default = default
if validate is not None:
declare._validator = validate
if watchers is not None:
declare._watchers = set(watchers)
return declare
def __set_name__(self, owner: Type, name: str) -> None:
self._owner = owner
self._name = name
self._private_name = f"__declare_private_{name}"
@overload
def __get__(
self: Declare[ValueType], obj: None, obj_type: type[ObjectType]
) -> Declare[ValueType]: ...
@overload
def __get__(
self: Declare[ValueType], obj: ObjectType, obj_type: type[ObjectType]
) -> ValueType: ...
def __get__(
self: Declare[ValueType], obj: ObjectType | None, obj_type: type[ObjectType]
) -> Declare[ValueType] | ValueType:
if obj is None:
return self
if isinstance((value := getattr(obj, self._private_name, _NO_VALUE)), NoValue):
value = copy(self._default) if self._copy_default else self._default
setattr(obj, self._private_name, value)
return value
else:
return value
def __set__(self, obj: object, value: ValueType) -> None:
if self._watchers:
current_value = getattr(obj, self._name, None)
new_value = (
value if self._validator is None else self._validator(obj, value)
)
setattr(obj, self._private_name, new_value)
if current_value != new_value:
for watcher in self._watchers:
watcher(obj, current_value, new_value)
else:
setattr(
obj,
self._private_name,
value if self._validator is None else self._validator(obj, value),
)
@property
def optional(self) -> Declare[ValueType | None]:
"""Make the type optional."""
# We're just changing the type, so this doesn't do anything at runtime.
return cast("Declare[ValueType | None]", self)
@property
def validate(self) -> ValidateDecorator:
"""Decorator to define a validator."""
return ValidateDecorator(self)
@property
def watch(self) -> WatchDecorator:
"""Decorator to create a watcher."""
return WatchDecorator(self)
def watch(
obj: ObjectType,
attribute_name: str,
callback: Watcher,
):
declare: Declare = getattr(obj.__class__, attribute_name)
def _callback(_obj: ObjectType, old: Any, new: Any):
if _obj != obj:
return
callback(obj, old, new)
declare._watchers.add(_callback)
| willmcgugan/declare | 66 | Syntactical sugar for Python class attributes | Python | willmcgugan | Will McGugan | |
tests/test_declare.py | Python | from typing import List
import declare
from declare import Declare, watch
def test_predefined():
class Foo:
my_int = declare.Int(1)
my_float = declare.Float(3.14)
my_bool = declare.Bool(True)
my_str = declare.Str("Foo")
my_bytes = declare.Bytes(b"bar")
foo = Foo()
assert foo.my_int == 1
assert foo.my_float == 3.14
assert foo.my_bool == True
assert foo.my_str == "Foo"
assert foo.my_bytes == b"bar"
def test_validate():
class Foo:
positive = declare.Int(0)
@positive.validate
def _validate_positive(self, value: int) -> int:
return max(0, value)
foo = Foo()
foo.positive = -1
assert foo.positive == 0
foo.positive = 1
assert foo.positive == 1
def test_watch() -> None:
changes0: list[tuple[int, int]] = []
changes1: list[tuple[int, int]] = []
changes2: list[tuple[int, int]] = []
changes3: list[tuple[int, int]] = []
class Foo:
value0 = declare.Int(0)
value1 = declare.Int(0)
@value0.watch
def _watch_value0(self, old: int, new: int) -> None:
changes0.append((old, new))
@value0.watch
def _watch_value1(self, old: int, new: int) -> None:
changes1.append((old, new))
foo0 = Foo()
foo0.value0 = 1
assert changes0 == [(0, 1)]
assert changes1 == [(0, 1)]
foo0.value0 = 2
assert changes0 == [(0, 1), (1, 2)]
assert changes1 == [(0, 1), (1, 2)]
def callback(obj: Foo, old: int, new: int):
changes3.append((old, new))
foo1 = Foo()
watch(foo0, "value1", callback)
foo0.value1 = 3
foo1.value1 = 4
assert changes0 == [(0, 1), (1, 2)]
assert changes1 == [(0, 1), (1, 2)]
assert changes3 == [(0, 3)]
def test_custom():
class Foo:
things = Declare[List[str]](["foo", "bar"])
foo = Foo()
assert foo.things == ["foo", "bar"]
| willmcgugan/declare | 66 | Syntactical sugar for Python class attributes | Python | willmcgugan | Will McGugan | |
src/faqtory/__main__.py | Python | from .cli import run
if __name__ == "__main__":
run()
| willmcgugan/faqtory | 232 | A tool to generate FAQ.md documents and automatically suggest answers to issues | Python | willmcgugan | Will McGugan | |
src/faqtory/cli.py | Python | from __future__ import annotations
from pathlib import Path
import sys
from rich.console import Console
from rich.panel import Panel
from rich.syntax import Syntax
from rich.traceback import install
from .models import Config
from .questions import read_questions
from . import templates
import click
from importlib.metadata import version
install()
CONFIG_PATH = "./faq.yml"
QUESTIONS_PATH = "./questions"
TEMPLATES_PATH = ".faq"
FAQ_PATH = "./FAQ.md"
FAQ_URL = "https://github.com/willmcgugan/faqtory/blob/main/FAQ.md"
QUESTIONS_README = """
# Questions
Your questions should go in this directory.
Question files should be named with the extension ".question.md".
"""
FAQ_TEMPLATE = """
# Frequently Asked Questions
{%- for question in questions %}
- [{{ question.title }}](#{{ question.slug }})
{%- endfor %}
{%- for question in questions %}
<a name="{{ question.slug }}"></a>
## {{ question.title }}
{{ question.body }}
{%- endfor %}
<hr>
Generated by [FAQtory](https://github.com/willmcgugan/faqtory)
"""
SUGGEST_TEMPLATE = """\
{%- if questions -%}
{% if questions|length == 1 %}
We found the following entry in the [FAQ]({{ faq_url }}) which you may find helpful:
{%- else %}
We found the following entries in the [FAQ]({{ faq_url }}) which you may find helpful:
{%- endif %}
{% for question in questions %}
- [{{ question.title }}]({{ faq_url }}#{{ question.slug }})
{%- endfor %}
Feel free to close this issue if you found an answer in the FAQ. Otherwise, please give us a little time to review.
{%- else -%}
Thank you for your issue. Give us a little time to review it.
PS. You might want to check the [FAQ]({{ faq_url }}) if you haven't done so already.
{%- endif %}
This is an automated reply, generated by [FAQtory](https://github.com/willmcgugan/faqtory)
"""
@click.group()
@click.version_option(version("faqtory"))
def run():
pass
@run.command()
@click.option(
"-c", "--config", help="Path to config file", default=CONFIG_PATH, metavar="PATH"
)
@click.option(
"--questions", help="Path to questions", default=QUESTIONS_PATH, metavar="PATH"
)
@click.option(
"--templates", help="Path to templates", default=TEMPLATES_PATH, metavar="PATH"
)
@click.option(
"--output", help="Path to generated FAQ", default=FAQ_PATH, metavar="PATH"
)
@click.option("--faq-url", help="FAQ URL", default=FAQ_URL, metavar="PATH")
@click.option(
"--overwrite/--no-overwrite",
help="Overwrite files if they exist",
default=False,
)
def init(
config: str,
questions: str,
templates: str,
output: str,
faq_url: str,
overwrite: bool,
) -> None:
"""Initialise a repository for FAQtory"""
console = Console()
error_console = Console(stderr=True)
DEFAULT_CONFIG = f"""\
# FAQtory settings
faq_url: "{faq_url}" # Replace this with the URL to your FAQ.md!
questions_path: "{questions}" # Where questions should be stored
output_path: "{output}" # Where FAQ.md should be generated
templates_path: "{templates}" # Path to templates\
"""
def write_path(path: Path, text: str) -> bool:
try:
with path.open("w" if overwrite else "x") as write_file:
write_file.write(text)
except FileExistsError:
error_console.print(
f"[red]⚠[/] File {str(path)!r} exists, use [b]--overwrite[/b] to update"
)
return False
except Exception as error:
error_console.print(f"[red]⚠[/] Unable to write {path}; {error}")
return False
console.print(f"[green]✔[/] Wrote {str(path)!r}")
return True
def make_directory(path: Path) -> bool:
try:
path.mkdir(parents=True, exist_ok=True)
except Exception as error:
error_console.print(f"unable to create {str(path)!r} directory; {error}")
return False
console.print(f"[green]✔[/] Directory {str(path)!r} created (or exists)")
return True
if write_path(Path(config), DEFAULT_CONFIG):
console.print(
Panel(
Syntax(DEFAULT_CONFIG, "yaml", line_numbers=True, word_wrap=True),
title=config,
),
)
make_directory(Path(questions))
make_directory(Path(templates))
readme_path = Path(questions) / "README.md"
write_path(readme_path, QUESTIONS_README)
write_path(Path(templates) / "FAQ.md", FAQ_TEMPLATE)
write_path(Path(templates) / "suggest.md", SUGGEST_TEMPLATE)
@run.command()
@click.option(
"-c",
"--config",
help="Path to config file",
default=CONFIG_PATH,
metavar="PATH",
)
@click.option("-o", "--output", help="Path to output, or - for stdout", default="")
def build(config: str, output: str) -> None:
"""Build FAQ.md"""
console = Console(stderr=True)
config_data = Config.read(Path(config))
questions = read_questions(config_data.questions_path)
faq = templates.render_faq(config_data.templates_path, questions=questions)
faq_path = output or config_data.output_path
if faq_path == "-":
print(faq)
else:
try:
Path(faq_path).write_text(faq)
except OSError as error:
console.print("[red]⚠[/] failed to write faq;", error)
sys.exit(-1)
else:
console.print(
f'[green]✔[/] wrote FAQ with {len(questions)} questions to "{faq_path}"'
)
@run.command()
@click.argument("query")
@click.option(
"-c", "--config", help="Path to config file", default=CONFIG_PATH, metavar="PATH"
)
def suggest(query: str, config: str) -> None:
"""Suggest FAQ entries"""
config_data = Config.read(Path(config))
questions = read_questions(config_data.questions_path)
scored_results = [(question.match(query), question) for question in questions]
scored_results.sort(key=lambda result: result[0], reverse=True)
results = [question for ratio, question in scored_results if ratio > 50]
suggest = templates.render_suggest(
config_data.templates_path,
questions=results,
faq_url=config_data.faq_url,
)
print(suggest)
| willmcgugan/faqtory | 232 | A tool to generate FAQ.md documents and automatically suggest answers to issues | Python | willmcgugan | Will McGugan | |
src/faqtory/models.py | Python | from __future__ import annotations
import string
from pathlib import Path
from typing import List
from thefuzz import fuzz
import frontmatter
from yaml import load, Loader
from pydantic import BaseModel
class Question(BaseModel):
title: str
body: str
alt_titles: List[str] = []
@property
def slug(self) -> str:
"""Create a slug from the title.
Returns:
str: Slug suitable for use in an anchor.
"""
chars_to_remove = string.punctuation
chars_to_remove = chars_to_remove.replace("-", "").replace("_", "")
slug = self.title.lower()
slug = slug.translate(str.maketrans("", "", chars_to_remove))
slug = slug.replace(" ", "-")
return slug
@classmethod
def read(cls, path: Path) -> "Question":
"""Read a question (Markdown with frontmatter)
Args:
path (str): Path to markdown.
Returns:
Question: A Question object
"""
question_data = frontmatter.load(path)
content = question_data.content
metadata = question_data.metadata
question = cls(
title=metadata.get("title", ""),
body=content,
alt_titles=metadata.get("alt_titles", []),
)
return question
@property
def titles(self) -> list[str]:
"""Get all titles including alternatives"""
return [self.title, *self.alt_titles]
def match(self, query: str) -> int:
"""Match this question against a query"""
return max(fuzz.partial_ratio(query, title) for title in self.titles)
class Config(BaseModel):
questions_path: str
output_path: str
templates_path: str
faq_url: str
@classmethod
def read(cls, path: Path) -> "Config":
with open(path, "rb") as config_file:
config_data = load(config_file, Loader=Loader)
def get_str(key: str) -> str:
return config_data.get(key, "")
config = cls(
questions_path=get_str("questions_path"),
output_path=get_str("output_path"),
templates_path=get_str("templates_path"),
faq_url=get_str("faq_url"),
)
return config
| willmcgugan/faqtory | 232 | A tool to generate FAQ.md documents and automatically suggest answers to issues | Python | willmcgugan | Will McGugan | |
src/faqtory/questions.py | Python | from __future__ import annotations
from pathlib import Path
from .models import Question
def read_questions(path: str) -> list[Question]:
questions: list[Question] = []
for question_path in Path(path).glob("*.question.md"):
question = Question.read(question_path)
questions.append(question)
questions.sort(key=lambda question: question.title.lower())
return questions
| willmcgugan/faqtory | 232 | A tool to generate FAQ.md documents and automatically suggest answers to issues | Python | willmcgugan | Will McGugan | |
src/faqtory/templates.py | Python | from __future__ import annotations
from jinja2 import Environment, FileSystemLoader, select_autoescape
def render_faq(templates_path: str, **template_args) -> str:
"""Render FAQ.md"""
env = Environment(
loader=FileSystemLoader(templates_path), autoescape=select_autoescape()
)
template = env.get_template("FAQ.md")
result = template.render(**template_args)
return result
def render_suggest(templates_path: str, **template_args) -> str:
"""Render suggest.md"""
env = Environment(
loader=FileSystemLoader(templates_path), autoescape=select_autoescape()
)
template = env.get_template("suggest.md")
result = template.render(**template_args)
return result
| willmcgugan/faqtory | 232 | A tool to generate FAQ.md documents and automatically suggest answers to issues | Python | willmcgugan | Will McGugan | |
lomond_accel/__init__.py | Python | from ._version import __version__
from ._mask import mask
from ._utf8validator import Utf8Validator
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
lomond_accel/_mask.c | C | /* Generated by Cython 0.25.2 */
/* BEGIN: Cython Metadata
{
"distutils": {
"depends": []
},
"module_name": "lomond_accel._mask"
}
END: Cython Metadata */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000)
#error Cython requires Python 2.6+ or Python 3.2+.
#else
#define CYTHON_ABI "0_25_2"
#include <stddef.h>
#ifndef offsetof
#define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#ifndef HAVE_LONG_LONG
#if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000)
#define HAVE_LONG_LONG
#endif
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
#define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
#define CYTHON_COMPILING_IN_PYPY 1
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 0
#undef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 0
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#undef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#undef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 1
#undef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 0
#undef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 0
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#elif defined(PYSTON_VERSION)
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#if PY_MAJOR_VERSION < 3
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#elif !defined(CYTHON_USE_PYLONG_INTERNALS)
#define CYTHON_USE_PYLONG_INTERNALS 1
#endif
#ifndef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 1
#endif
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#if PY_VERSION_HEX < 0x030300F0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#elif !defined(CYTHON_USE_UNICODE_WRITER)
#define CYTHON_USE_UNICODE_WRITER 1
#endif
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#ifndef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 1
#endif
#ifndef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 1
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#undef SHIFT
#undef BASE
#undef MASK
#endif
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
#define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyClass_Type
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_FASTCALL
#define METH_FASTCALL 0x80
typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args,
Py_ssize_t nargs, PyObject *kwnames);
#else
#define __Pyx_PyCFunctionFast _PyCFunctionFast
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
#define CYTHON_PEP393_ENABLED 1
#define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\
0 : _PyUnicode_Ready((PyObject *)(op)))
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
#define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
#define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
#define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
#define CYTHON_PEP393_ENABLED 0
#define PyUnicode_1BYTE_KIND 1
#define PyUnicode_2BYTE_KIND 2
#define PyUnicode_4BYTE_KIND 4
#define __Pyx_PyUnicode_READY(op) (0)
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
#define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
#define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
#define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
#endif
#if CYTHON_COMPILING_IN_PYPY
#define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
#else
#define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
#define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
#define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
#define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
#define PyObject_Malloc(s) PyMem_Malloc(s)
#define PyObject_Free(p) PyMem_Free(p)
#define PyObject_Realloc(p) PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
#define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
#define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
#else
#define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
#define PyObject_ASCII(o) PyObject_Repr(o)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyStringObject PyUnicodeObject
#define PyString_Type PyUnicode_Type
#define PyString_Check PyUnicode_Check
#define PyString_CheckExact PyUnicode_CheckExact
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
#define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
#define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
#if PY_MAJOR_VERSION >= 3
#define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyNumber_Int PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBoolObject PyLongObject
#endif
#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
#ifndef PyUnicode_InternFromString
#define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
#endif
#endif
#if PY_VERSION_HEX < 0x030200A4
typedef long Py_hash_t;
#define __Pyx_PyInt_FromHash_t PyInt_FromLong
#define __Pyx_PyInt_AsHash_t PyInt_AsLong
#else
#define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
#define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func))
#else
#define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#if CYTHON_USE_ASYNC_SLOTS
#if PY_VERSION_HEX >= 0x030500B1
#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
#else
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
} __Pyx_PyAsyncMethodsStruct;
#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
#endif
#else
#define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
#endif
#ifndef CYTHON_MAYBE_UNUSED_VAR
# if defined(__cplusplus)
template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
# else
# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
# endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
# define CYTHON_NCP_UNUSED
# else
# define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifndef CYTHON_INLINE
#if defined(__clang__)
#define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
#elif defined(__GNUC__)
#define CYTHON_INLINE __inline__
#elif defined(_MSC_VER)
#define CYTHON_INLINE __inline
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_INLINE inline
#else
#define CYTHON_INLINE
#endif
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif
#define __PYX_ERR(f_index, lineno, Ln_error) \
{ \
__pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \
}
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
#endif
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#define __PYX_HAVE__lomond_accel___mask
#define __PYX_HAVE_API__lomond_accel___mask
#include <string.h>
#include <stdio.h>
#include "pythread.h"
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#ifdef PYREX_WITHOUT_ASSERTIONS
#define CYTHON_WITHOUT_ASSERTIONS
#endif
typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\
(sizeof(type) < sizeof(Py_ssize_t)) ||\
(sizeof(type) > sizeof(Py_ssize_t) &&\
likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX) &&\
(!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
v == (type)PY_SSIZE_T_MIN))) ||\
(sizeof(type) == sizeof(Py_ssize_t) &&\
(is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX))) )
#if defined (__cplusplus) && __cplusplus >= 201103L
#include <cstdlib>
#define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER) && defined (_M_X64)
#define __Pyx_sst_abs(value) _abs64(value)
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
#define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
#define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
#define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
#if PY_MAJOR_VERSION < 3
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u)
{
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return (size_t)(u_end - u - 1);
}
#else
#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen
#endif
#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False))
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
const char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
if (strcmp(default_encoding_c, "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
char ascii_chars[128];
int c;
for (c = 0; c < 128; c++) {
ascii_chars[c] = c;
}
__Pyx_sys_getdefaultencoding_not_ascii = 1;
ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
if (!ascii_chars_u) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
PyErr_Format(
PyExc_ValueError,
"This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
default_encoding_c);
goto bad;
}
Py_DECREF(ascii_chars_u);
Py_DECREF(ascii_chars_b);
}
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c));
if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
/* Test for GCC > 2.95 */
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static PyObject *__pyx_m;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
static const char *__pyx_f[] = {
"lomond_accel/_mask.pyx",
"type.pxd",
"bool.pxd",
"complex.pxd",
};
/*--- Type declarations ---*/
/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*SetupContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefNannyAPIStruct;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
#define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
if (acquire_gil) {\
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
PyGILState_Release(__pyx_gilstate_save);\
} else {\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
}
#else
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
#define __Pyx_RefNannyFinishContext()\
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
#define __Pyx_RefNannyDeclarations
#define __Pyx_RefNannySetupContext(name, acquire_gil)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XINCREF(r) Py_XINCREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_XGOTREF(r)
#define __Pyx_XGIVEREF(r)
#endif
#define __Pyx_XDECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_XDECREF(tmp);\
} while (0)
#define __Pyx_DECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_DECREF(tmp);\
} while (0)
#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);
/* RaiseArgTupleInvalid.proto */
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);
/* RaiseDoubleKeywords.proto */
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);
/* ParseKeywords.proto */
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
const char* function_name);
/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
/* CodeObjectCache.proto */
typedef struct {
PyCodeObject* code_object;
int code_line;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
int count;
int max_count;
__Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);
/* PyIdentifierFromString.proto */
#if !defined(__Pyx_PyIdentifier_FromString)
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s)
#else
#define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s)
#endif
#endif
/* ModuleImport.proto */
static PyObject *__Pyx_ImportModule(const char *name);
/* TypeImport.proto */
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict);
/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
/* Module declarations from 'cpython.version' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
/* Module declarations from 'libc.string' */
/* Module declarations from 'libc.stdio' */
/* Module declarations from 'cpython.object' */
/* Module declarations from 'cpython.ref' */
/* Module declarations from 'cpython.exc' */
/* Module declarations from 'cpython.module' */
/* Module declarations from 'cpython.mem' */
/* Module declarations from 'cpython.tuple' */
/* Module declarations from 'cpython.list' */
/* Module declarations from 'cpython.sequence' */
/* Module declarations from 'cpython.mapping' */
/* Module declarations from 'cpython.iterator' */
/* Module declarations from 'cpython.number' */
/* Module declarations from 'cpython.int' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.bool' */
static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0;
/* Module declarations from 'cpython.long' */
/* Module declarations from 'cpython.float' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.complex' */
static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0;
/* Module declarations from 'cpython.string' */
/* Module declarations from 'cpython.unicode' */
/* Module declarations from 'cpython.dict' */
/* Module declarations from 'cpython.instance' */
/* Module declarations from 'cpython.function' */
/* Module declarations from 'cpython.method' */
/* Module declarations from 'cpython.weakref' */
/* Module declarations from 'cpython.getargs' */
/* Module declarations from 'cpython.pythread' */
/* Module declarations from 'cpython.pystate' */
/* Module declarations from 'cpython.cobject' */
/* Module declarations from 'cpython.oldbuffer' */
/* Module declarations from 'cpython.set' */
/* Module declarations from 'cpython.buffer' */
/* Module declarations from 'cpython.bytes' */
/* Module declarations from 'cpython.pycapsule' */
/* Module declarations from 'cpython' */
/* Module declarations from 'libc.stdint' */
/* Module declarations from 'lomond_accel._mask' */
#define __Pyx_MODULE_NAME "lomond_accel._mask"
int __pyx_module_is_main_lomond_accel___mask = 0;
/* Implementation of 'lomond_accel._mask' */
static PyObject *__pyx_builtin_range;
static const char __pyx_k_i[] = "i";
static const char __pyx_k_data[] = "data";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_mask[] = "mask";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_range[] = "range";
static const char __pyx_k_in_buf[] = "in_buf";
static const char __pyx_k_data_len[] = "data_len";
static const char __pyx_k_mask_buf[] = "mask_buf";
static const char __pyx_k_uint32_msk[] = "uint32_msk";
static const char __pyx_k_uint64_msk[] = "uint64_msk";
static const char __pyx_k_lomond_accel__mask[] = "lomond_accel._mask";
static const char __pyx_k_Users_will_projects_lomond_acce[] = "/Users/will/projects/lomond-accel/lomond_accel/_mask.pyx";
static PyObject *__pyx_kp_s_Users_will_projects_lomond_acce;
static PyObject *__pyx_n_s_data;
static PyObject *__pyx_n_s_data_len;
static PyObject *__pyx_n_s_i;
static PyObject *__pyx_n_s_in_buf;
static PyObject *__pyx_n_s_lomond_accel__mask;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_mask;
static PyObject *__pyx_n_s_mask_buf;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_uint32_msk;
static PyObject *__pyx_n_s_uint64_msk;
static PyObject *__pyx_pf_12lomond_accel_5_mask_mask(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data); /* proto */
static PyObject *__pyx_tuple_;
static PyObject *__pyx_codeobj__2;
/* "lomond_accel/_mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(object mask, object data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
/* Python wrapper */
static PyObject *__pyx_pw_12lomond_accel_5_mask_1mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_12lomond_accel_5_mask_mask[] = "Note, this function mutates it's `data` argument\n ";
static PyMethodDef __pyx_mdef_12lomond_accel_5_mask_1mask = {"mask", (PyCFunction)__pyx_pw_12lomond_accel_5_mask_1mask, METH_VARARGS|METH_KEYWORDS, __pyx_doc_12lomond_accel_5_mask_mask};
static PyObject *__pyx_pw_12lomond_accel_5_mask_1mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_mask = 0;
PyObject *__pyx_v_data = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("mask (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_mask,&__pyx_n_s_data,0};
PyObject* values[2] = {0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("mask", 1, 2, 2, 1); __PYX_ERR(0, 10, __pyx_L3_error)
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "mask") < 0)) __PYX_ERR(0, 10, __pyx_L3_error)
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 2) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
}
__pyx_v_mask = values[0];
__pyx_v_data = values[1];
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("mask", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 10, __pyx_L3_error)
__pyx_L3_error:;
__Pyx_AddTraceback("lomond_accel._mask.mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_12lomond_accel_5_mask_mask(__pyx_self, __pyx_v_mask, __pyx_v_data);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_12lomond_accel_5_mask_mask(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data) {
Py_ssize_t __pyx_v_data_len;
Py_ssize_t __pyx_v_i;
unsigned char *__pyx_v_in_buf;
unsigned char const *__pyx_v_mask_buf;
uint32_t __pyx_v_uint32_msk;
uint64_t __pyx_v_uint64_msk;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
char *__pyx_t_6;
uint64_t *__pyx_t_7;
long __pyx_t_8;
uint32_t *__pyx_t_9;
Py_ssize_t __pyx_t_10;
Py_ssize_t __pyx_t_11;
__Pyx_RefNannySetupContext("mask", 0);
__Pyx_INCREF(__pyx_v_mask);
__Pyx_INCREF(__pyx_v_data);
/* "lomond_accel/_mask.pyx":21
* uint64_t uint64_msk
*
* assert len(mask) == 4 # <<<<<<<<<<<<<<
*
* if not isinstance(mask, bytes):
*/
#ifndef CYTHON_WITHOUT_ASSERTIONS
if (unlikely(!Py_OptimizeFlag)) {
__pyx_t_1 = PyObject_Length(__pyx_v_mask); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 21, __pyx_L1_error)
if (unlikely(!((__pyx_t_1 == 4) != 0))) {
PyErr_SetNone(PyExc_AssertionError);
__PYX_ERR(0, 21, __pyx_L1_error)
}
}
#endif
/* "lomond_accel/_mask.pyx":23
* assert len(mask) == 4
*
* if not isinstance(mask, bytes): # <<<<<<<<<<<<<<
* mask = bytes(mask)
*
*/
__pyx_t_2 = PyBytes_Check(__pyx_v_mask);
__pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0);
if (__pyx_t_3) {
/* "lomond_accel/_mask.pyx":24
*
* if not isinstance(mask, bytes):
* mask = bytes(mask) # <<<<<<<<<<<<<<
*
* if isinstance(data, bytearray):
*/
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_INCREF(__pyx_v_mask);
__Pyx_GIVEREF(__pyx_v_mask);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_mask);
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyBytes_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_DECREF_SET(__pyx_v_mask, __pyx_t_5);
__pyx_t_5 = 0;
/* "lomond_accel/_mask.pyx":23
* assert len(mask) == 4
*
* if not isinstance(mask, bytes): # <<<<<<<<<<<<<<
* mask = bytes(mask)
*
*/
}
/* "lomond_accel/_mask.pyx":26
* mask = bytes(mask)
*
* if isinstance(data, bytearray): # <<<<<<<<<<<<<<
* data = <bytearray>data
* else:
*/
__pyx_t_3 = PyByteArray_Check(__pyx_v_data);
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
/* "lomond_accel/_mask.pyx":27
*
* if isinstance(data, bytearray):
* data = <bytearray>data # <<<<<<<<<<<<<<
* else:
* data = bytearray(data)
*/
__pyx_t_5 = __pyx_v_data;
__Pyx_INCREF(__pyx_t_5);
__Pyx_DECREF_SET(__pyx_v_data, __pyx_t_5);
__pyx_t_5 = 0;
/* "lomond_accel/_mask.pyx":26
* mask = bytes(mask)
*
* if isinstance(data, bytearray): # <<<<<<<<<<<<<<
* data = <bytearray>data
* else:
*/
goto __pyx_L4;
}
/* "lomond_accel/_mask.pyx":29
* data = <bytearray>data
* else:
* data = bytearray(data) # <<<<<<<<<<<<<<
*
* data_len = len(data)
*/
/*else*/ {
__pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_data);
__Pyx_GIVEREF(__pyx_v_data);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data);
__pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyByteArray_Type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF_SET(__pyx_v_data, __pyx_t_4);
__pyx_t_4 = 0;
}
__pyx_L4:;
/* "lomond_accel/_mask.pyx":31
* data = bytearray(data)
*
* data_len = len(data) # <<<<<<<<<<<<<<
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
*/
__pyx_t_1 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 31, __pyx_L1_error)
__pyx_v_data_len = __pyx_t_1;
/* "lomond_accel/_mask.pyx":32
*
* data_len = len(data)
* in_buf = <unsigned char*>PyByteArray_AsString(data) # <<<<<<<<<<<<<<
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
* uint32_msk = (<uint32_t*>mask_buf)[0]
*/
if (!(likely(PyByteArray_CheckExact(__pyx_v_data))||((__pyx_v_data) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytearray", Py_TYPE(__pyx_v_data)->tp_name), 0))) __PYX_ERR(0, 32, __pyx_L1_error)
__pyx_t_6 = PyByteArray_AsString(((PyObject*)__pyx_v_data)); if (unlikely(__pyx_t_6 == NULL)) __PYX_ERR(0, 32, __pyx_L1_error)
__pyx_v_in_buf = ((unsigned char *)__pyx_t_6);
/* "lomond_accel/_mask.pyx":33
* data_len = len(data)
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask) # <<<<<<<<<<<<<<
* uint32_msk = (<uint32_t*>mask_buf)[0]
*
*/
__pyx_t_6 = PyBytes_AsString(__pyx_v_mask); if (unlikely(__pyx_t_6 == NULL)) __PYX_ERR(0, 33, __pyx_L1_error)
__pyx_v_mask_buf = ((unsigned char const *)__pyx_t_6);
/* "lomond_accel/_mask.pyx":34
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
* uint32_msk = (<uint32_t*>mask_buf)[0] # <<<<<<<<<<<<<<
*
* # TODO: align in_data ptr to achieve even faster speeds
*/
__pyx_v_uint32_msk = (((uint32_t *)__pyx_v_mask_buf)[0]);
/* "lomond_accel/_mask.pyx":39
* # does it need in python ?! malloc() always aligns to sizeof(long) bytes
*
* if sizeof(size_t) >= 8: # <<<<<<<<<<<<<<
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk
*/
__pyx_t_2 = (((sizeof(size_t)) >= 8) != 0);
if (__pyx_t_2) {
/* "lomond_accel/_mask.pyx":40
*
* if sizeof(size_t) >= 8:
* uint64_msk = uint32_msk # <<<<<<<<<<<<<<
* uint64_msk = (uint64_msk << 32) | uint32_msk
*
*/
__pyx_v_uint64_msk = __pyx_v_uint32_msk;
/* "lomond_accel/_mask.pyx":41
* if sizeof(size_t) >= 8:
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk # <<<<<<<<<<<<<<
*
* while data_len >= 8:
*/
__pyx_v_uint64_msk = ((__pyx_v_uint64_msk << 32) | __pyx_v_uint32_msk);
/* "lomond_accel/_mask.pyx":43
* uint64_msk = (uint64_msk << 32) | uint32_msk
*
* while data_len >= 8: # <<<<<<<<<<<<<<
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8
*/
while (1) {
__pyx_t_2 = ((__pyx_v_data_len >= 8) != 0);
if (!__pyx_t_2) break;
/* "lomond_accel/_mask.pyx":44
*
* while data_len >= 8:
* (<uint64_t*>in_buf)[0] ^= uint64_msk # <<<<<<<<<<<<<<
* in_buf += 8
* data_len -= 8
*/
__pyx_t_7 = ((uint64_t *)__pyx_v_in_buf);
__pyx_t_8 = 0;
(__pyx_t_7[__pyx_t_8]) = ((__pyx_t_7[__pyx_t_8]) ^ __pyx_v_uint64_msk);
/* "lomond_accel/_mask.pyx":45
* while data_len >= 8:
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8 # <<<<<<<<<<<<<<
* data_len -= 8
*
*/
__pyx_v_in_buf = (__pyx_v_in_buf + 8);
/* "lomond_accel/_mask.pyx":46
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8
* data_len -= 8 # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_data_len = (__pyx_v_data_len - 8);
}
/* "lomond_accel/_mask.pyx":39
* # does it need in python ?! malloc() always aligns to sizeof(long) bytes
*
* if sizeof(size_t) >= 8: # <<<<<<<<<<<<<<
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk
*/
}
/* "lomond_accel/_mask.pyx":49
*
*
* while data_len >= 4: # <<<<<<<<<<<<<<
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4
*/
while (1) {
__pyx_t_2 = ((__pyx_v_data_len >= 4) != 0);
if (!__pyx_t_2) break;
/* "lomond_accel/_mask.pyx":50
*
* while data_len >= 4:
* (<uint32_t*>in_buf)[0] ^= uint32_msk # <<<<<<<<<<<<<<
* in_buf += 4
* data_len -= 4
*/
__pyx_t_9 = ((uint32_t *)__pyx_v_in_buf);
__pyx_t_8 = 0;
(__pyx_t_9[__pyx_t_8]) = ((__pyx_t_9[__pyx_t_8]) ^ __pyx_v_uint32_msk);
/* "lomond_accel/_mask.pyx":51
* while data_len >= 4:
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4 # <<<<<<<<<<<<<<
* data_len -= 4
*
*/
__pyx_v_in_buf = (__pyx_v_in_buf + 4);
/* "lomond_accel/_mask.pyx":52
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4
* data_len -= 4 # <<<<<<<<<<<<<<
*
* for i in range(0, data_len):
*/
__pyx_v_data_len = (__pyx_v_data_len - 4);
}
/* "lomond_accel/_mask.pyx":54
* data_len -= 4
*
* for i in range(0, data_len): # <<<<<<<<<<<<<<
* in_buf[i] ^= mask_buf[i]
*/
__pyx_t_1 = __pyx_v_data_len;
for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) {
__pyx_v_i = __pyx_t_10;
/* "lomond_accel/_mask.pyx":55
*
* for i in range(0, data_len):
* in_buf[i] ^= mask_buf[i] # <<<<<<<<<<<<<<
*/
__pyx_t_11 = __pyx_v_i;
(__pyx_v_in_buf[__pyx_t_11]) = ((__pyx_v_in_buf[__pyx_t_11]) ^ (__pyx_v_mask_buf[__pyx_v_i]));
}
/* "lomond_accel/_mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(object mask, object data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("lomond_accel._mask.mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_mask);
__Pyx_XDECREF(__pyx_v_data);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
#if PY_VERSION_HEX < 0x03020000
{ PyObject_HEAD_INIT(NULL) NULL, 0, NULL },
#else
PyModuleDef_HEAD_INIT,
#endif
"_mask",
0, /* m_doc */
-1, /* m_size */
__pyx_methods /* m_methods */,
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_kp_s_Users_will_projects_lomond_acce, __pyx_k_Users_will_projects_lomond_acce, sizeof(__pyx_k_Users_will_projects_lomond_acce), 0, 0, 1, 0},
{&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1},
{&__pyx_n_s_data_len, __pyx_k_data_len, sizeof(__pyx_k_data_len), 0, 0, 1, 1},
{&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1},
{&__pyx_n_s_in_buf, __pyx_k_in_buf, sizeof(__pyx_k_in_buf), 0, 0, 1, 1},
{&__pyx_n_s_lomond_accel__mask, __pyx_k_lomond_accel__mask, sizeof(__pyx_k_lomond_accel__mask), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 0, 0, 1, 1},
{&__pyx_n_s_mask_buf, __pyx_k_mask_buf, sizeof(__pyx_k_mask_buf), 0, 0, 1, 1},
{&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_n_s_uint32_msk, __pyx_k_uint32_msk, sizeof(__pyx_k_uint32_msk), 0, 0, 1, 1},
{&__pyx_n_s_uint64_msk, __pyx_k_uint64_msk, sizeof(__pyx_k_uint64_msk), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 54, __pyx_L1_error)
return 0;
__pyx_L1_error:;
return -1;
}
static int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
/* "lomond_accel/_mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(object mask, object data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
__pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_mask, __pyx_n_s_data, __pyx_n_s_data_len, __pyx_n_s_i, __pyx_n_s_in_buf, __pyx_n_s_mask_buf, __pyx_n_s_uint32_msk, __pyx_n_s_uint64_msk); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple_);
__Pyx_GIVEREF(__pyx_tuple_);
__pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_will_projects_lomond_acce, __pyx_n_s_mask, 10, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 2, __pyx_L1_error);
return 0;
__pyx_L1_error:;
return -1;
}
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC init_mask(void); /*proto*/
PyMODINIT_FUNC init_mask(void)
#else
PyMODINIT_FUNC PyInit__mask(void); /*proto*/
PyMODINIT_FUNC PyInit__mask(void)
#endif
{
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannyDeclarations
#if CYTHON_REFNANNY
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
if (!__Pyx_RefNanny) {
PyErr_Clear();
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
if (!__Pyx_RefNanny)
Py_FatalError("failed to import 'refnanny' module");
}
#endif
__Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__mask(void)", 0);
if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 2, __pyx_L1_error)
#ifdef __Pyx_CyFunction_USED
if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_Coroutine_USED
if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_StopAsyncIteration_USED
if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
/*--- Library function declarations ---*/
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Module creation code ---*/
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4("_mask", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 2, __pyx_L1_error)
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 2, __pyx_L1_error)
#if CYTHON_COMPILING_IN_PYPY
Py_INCREF(__pyx_b);
#endif
if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 2, __pyx_L1_error);
/*--- Initialize various global constants etc. ---*/
if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
if (__pyx_module_is_main_lomond_accel___mask) {
if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 2, __pyx_L1_error)
if (!PyDict_GetItemString(modules, "lomond_accel._mask")) {
if (unlikely(PyDict_SetItemString(modules, "lomond_accel._mask", __pyx_m) < 0)) __PYX_ERR(0, 2, __pyx_L1_error)
}
}
#endif
/*--- Builtin init code ---*/
if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
/*--- Constants init code ---*/
if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
/*--- Global init code ---*/
/*--- Variable export code ---*/
/*--- Function export code ---*/
/*--- Type init code ---*/
/*--- Type import code ---*/
__pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type",
#if CYTHON_COMPILING_IN_PYPY
sizeof(PyTypeObject),
#else
sizeof(PyHeapTypeObject),
#endif
0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(1, 9, __pyx_L1_error)
__pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) __PYX_ERR(2, 8, __pyx_L1_error)
__pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) __PYX_ERR(3, 15, __pyx_L1_error)
/*--- Variable import code ---*/
/*--- Function import code ---*/
/*--- Execution code ---*/
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
/* "lomond_accel/_mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(object mask, object data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
__pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_12lomond_accel_5_mask_1mask, NULL, __pyx_n_s_lomond_accel__mask); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_mask, __pyx_t_1) < 0) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "lomond_accel/_mask.pyx":2
*
* from cpython cimport PyBytes_AsString # <<<<<<<<<<<<<<
*
* #from cpython cimport PyByteArray_AsString # cython still not exports that
*/
__pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/*--- Wrapped vars code ---*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
if (__pyx_m) {
if (__pyx_d) {
__Pyx_AddTraceback("init lomond_accel._mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
}
Py_DECREF(__pyx_m); __pyx_m = 0;
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init lomond_accel._mask");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if PY_MAJOR_VERSION < 3
return;
#else
return __pyx_m;
#endif
}
/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule((char *)modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, (char *)"RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif
/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
/* RaiseArgTupleInvalid */
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
PyErr_Format(PyExc_TypeError,
"%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
func_name, more_or_less, num_expected,
(num_expected == 1) ? "" : "s", num_found);
}
/* RaiseDoubleKeywords */
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AsString(kw_name));
#endif
}
/* ParseKeywords */
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
continue;
}
name = first_kw_arg;
#if PY_MAJOR_VERSION < 3
if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) {
while (*name) {
if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
&& _PyString_Eq(**name, key)) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
if ((**argname == key) || (
(CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
&& _PyString_Eq(**argname, key))) {
goto arg_passed_twice;
}
argname++;
}
}
} else
#endif
if (likely(PyUnicode_Check(key))) {
while (*name) {
int cmp = (**name == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**name, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
int cmp = (**argname == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**argname, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) goto arg_passed_twice;
argname++;
}
}
} else
goto invalid_keyword_type;
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, key);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%.200s() got an unexpected keyword argument '%.200s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = (*call)(func, arg, kw);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* CodeObjectCache */
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
int start = 0, mid = 0, end = count - 1;
if (end >= 0 && code_line > entries[end].code_line) {
return count;
}
while (start < end) {
mid = start + (end - start) / 2;
if (code_line < entries[mid].code_line) {
end = mid;
} else if (code_line > entries[mid].code_line) {
start = mid + 1;
} else {
return mid;
}
}
if (code_line <= entries[mid].code_line) {
return mid;
} else {
return mid + 1;
}
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
PyCodeObject* code_object;
int pos;
if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
return NULL;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
return NULL;
}
code_object = __pyx_code_cache.entries[pos].code_object;
Py_INCREF(code_object);
return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
int pos, i;
__Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
if (unlikely(!code_line)) {
return;
}
if (unlikely(!entries)) {
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
if (likely(entries)) {
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = 64;
__pyx_code_cache.count = 1;
entries[0].code_line = code_line;
entries[0].code_object = code_object;
Py_INCREF(code_object);
}
return;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
PyCodeObject* tmp = entries[pos].code_object;
entries[pos].code_object = code_object;
Py_DECREF(tmp);
return;
}
if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
int new_max = __pyx_code_cache.max_count + 64;
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
__pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry));
if (unlikely(!entries)) {
return;
}
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = new_max;
}
for (i=__pyx_code_cache.count; i>pos; i--) {
entries[i] = entries[i-1];
}
entries[pos].code_line = code_line;
entries[pos].code_object = code_object;
__pyx_code_cache.count++;
Py_INCREF(code_object);
}
/* AddTraceback */
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(filename);
#else
py_srcfile = PyUnicode_FromString(filename);
#endif
if (!py_srcfile) goto bad;
if (c_line) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_code = __Pyx_PyCode_New(
0,
0,
0,
0,
0,
__pyx_empty_bytes, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
py_line,
__pyx_empty_bytes /*PyObject *lnotab*/
);
Py_DECREF(py_srcfile);
Py_DECREF(py_funcname);
return py_code;
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
py_code = __pyx_find_code_object(c_line ? c_line : py_line);
if (!py_code) {
py_code = __Pyx_CreateCodeObjectForTraceback(
funcname, c_line, py_line, filename);
if (!py_code) goto bad;
__pyx_insert_code_object(c_line ? c_line : py_line, py_code);
}
py_frame = PyFrame_New(
PyThreadState_GET(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
__pyx_d, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
__Pyx_PyFrame_SetLineNumber(py_frame, py_line);
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) -1, const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(long) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
/* CIntFromPyVerify */
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
{\
func_type value = func_value;\
if (sizeof(target_type) < sizeof(func_type)) {\
if (unlikely(value != (func_type) (target_type) value)) {\
func_type zero = 0;\
if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
return (target_type) -1;\
if (is_unsigned && unlikely(value < zero))\
goto raise_neg_overflow;\
else\
goto raise_overflow;\
}\
}\
return (target_type) value;\
}
/* CIntFromPy */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) -1, const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(long) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (long) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0])
case -2:
if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
}
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
long val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (long) -1;
}
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to long");
return (long) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
/* CIntFromPy */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) -1, const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0])
case -2:
if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
}
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
int val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (int) -1;
}
} else {
int val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
/* CheckBinaryVersion */
static int __Pyx_check_binary_version(void) {
char ctversion[4], rtversion[4];
PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
char message[200];
PyOS_snprintf(message, sizeof(message),
"compiletime version %s of module '%.100s' "
"does not match runtime version %s",
ctversion, __Pyx_MODULE_NAME, rtversion);
return PyErr_WarnEx(NULL, message, 1);
}
return 0;
}
/* ModuleImport */
#ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
static PyObject *__Pyx_ImportModule(const char *name) {
PyObject *py_name = 0;
PyObject *py_module = 0;
py_name = __Pyx_PyIdentifier_FromString(name);
if (!py_name)
goto bad;
py_module = PyImport_Import(py_name);
Py_DECREF(py_name);
return py_module;
bad:
Py_XDECREF(py_name);
return 0;
}
#endif
/* TypeImport */
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
size_t size, int strict)
{
PyObject *py_module = 0;
PyObject *result = 0;
PyObject *py_name = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
py_module = __Pyx_ImportModule(module_name);
if (!py_module)
goto bad;
py_name = __Pyx_PyIdentifier_FromString(class_name);
if (!py_name)
goto bad;
result = PyObject_GetAttr(py_module, py_name);
Py_DECREF(py_name);
py_name = 0;
Py_DECREF(py_module);
py_module = 0;
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if (!strict && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd",
module_name, class_name, basicsize, size);
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
}
else if ((size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd",
module_name, class_name, basicsize, size);
goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(py_module);
Py_XDECREF(result);
return NULL;
}
#endif
/* InitStrings */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else
if (t->is_unicode | t->is_str) {
if (t->intern) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->encoding) {
*t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
} else {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
}
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
__Pyx_sys_getdefaultencoding_not_ascii &&
#endif
PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
char* defenc_c;
PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
if (!defenc) return NULL;
defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
{
char* end = defenc_c + PyBytes_GET_SIZE(defenc);
char* c;
for (c = defenc_c; c < end; c++) {
if ((unsigned char) (*c) >= 128) {
PyUnicode_AsASCIIString(o);
return NULL;
}
}
}
#endif
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
#else
if (__Pyx_PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (PyUnicode_IS_ASCII(o)) {
*length = PyUnicode_GET_LENGTH(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else
return PyUnicode_AsUTF8AndSize(o, length);
#endif
#endif
} else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#endif
{
char* result;
int r = PyBytes_AsStringAndSize(o, &result, length);
if (unlikely(r < 0)) {
return NULL;
} else {
return result;
}
}
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
int is_true = x == Py_True;
if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
else return PyObject_IsTrue(x);
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
PyNumberMethods *m;
#endif
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(x) || PyLong_Check(x))
#else
if (PyLong_Check(x))
#endif
return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = PyNumber_Int(x);
}
else if (m && m->nb_long) {
name = "long";
res = PyNumber_Long(x);
}
#else
if (m && m->nb_int) {
name = "int";
res = PyNumber_Long(x);
}
#endif
#else
res = PyNumber_Int(x);
#endif
if (res) {
#if PY_MAJOR_VERSION < 3
if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
if (!PyLong_Check(res)) {
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
name, name, Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject *x;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(b))) {
if (sizeof(Py_ssize_t) >= sizeof(long))
return PyInt_AS_LONG(b);
else
return PyInt_AsSsize_t(x);
}
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)b)->ob_digit;
const Py_ssize_t size = Py_SIZE(b);
if (likely(__Pyx_sst_abs(size) <= 1)) {
ival = likely(size) ? digits[0] : 0;
if (size == -1) ival = -ival;
return ival;
} else {
switch (size) {
case 2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
}
}
#endif
return PyLong_AsSsize_t(b);
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
return PyInt_FromSize_t(ival);
}
#endif /* Py_PYTHON_H */
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
lomond_accel/_mask.pyx | Cython | # https://github.com/aio-libs/aiohttp
from cpython cimport PyBytes_AsString
#from cpython cimport PyByteArray_AsString # cython still not exports that
cdef extern from "Python.h":
char* PyByteArray_AsString(bytearray ba) except NULL
from libc.stdint cimport uint32_t, uint64_t, uintmax_t
def mask(bytes mask, bytearray data):
"""Note, this function mutates it's `data` argument
"""
cdef:
Py_ssize_t data_len, i
# bit operations on signed integers are implementation-specific
unsigned char * in_buf
const unsigned char * mask_buf
uint32_t uint32_msk
uint64_t uint64_msk
assert len(mask) == 4
if not isinstance(mask, bytes):
mask = bytes(mask)
if isinstance(data, bytearray):
data = <bytearray>data
else:
data = bytearray(data)
data_len = len(data)
in_buf = <unsigned char*>PyByteArray_AsString(data)
mask_buf = <const unsigned char*>PyBytes_AsString(mask)
uint32_msk = (<uint32_t*>mask_buf)[0]
# TODO: align in_data ptr to achieve even faster speeds
# does it need in python ?! malloc() always aligns to sizeof(long) bytes
if sizeof(size_t) >= 8:
uint64_msk = uint32_msk
uint64_msk = (uint64_msk << 32) | uint32_msk
while data_len >= 8:
(<uint64_t*>in_buf)[0] ^= uint64_msk
in_buf += 8
data_len -= 8
while data_len >= 4:
(<uint32_t*>in_buf)[0] ^= uint32_msk
in_buf += 4
data_len -= 4
for i in range(0, data_len):
in_buf[i] ^= mask_buf[i]
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
lomond_accel/_utf8validator.pyx | Cython | # coding=utf-8
###############################################################################
##
## Copyright 2011 Tavendo GmbH
##
## Note:
##
## This code is a Python implementation of the algorithm
##
## "Flexible and Economical UTF-8 Decoder"
##
## by Bjoern Hoehrmann
##
## bjoern@hoehrmann.de
## http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
##
## 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.
##
###############################################################################
## DFA transitions
cdef extern from "dfa.h":
cdef char* UTF8VALIDATOR_DFA
cdef extern from "Python.h":
int PyObject_AsReadBuffer(object, void**, Py_ssize_t*) except -1
DEF _UTF8_ACCEPT = 0
DEF _UTF8_REJECT = 1
cdef class Utf8Validator(object):
"""
Incremental UTF-8 validator with constant memory consumption (minimal state).
Implements the algorithm "Flexible and Economical UTF-8 Decoder" by
Bjoern Hoehrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/).
"""
UTF8_ACCEPT = 0
UTF8_REJECT = 1
cdef public int i
cdef public int state
cdef public int codepoint
def __init__(self):
self.reset()
def decode(self, b):
"""
Eat one UTF-8 octet, and validate on the fly.
Returns UTF8_ACCEPT when enough octets have been consumed, in which case
self.codepoint contains the decoded Unicode code point.
Returns UTF8_REJECT when invalid UTF-8 was encountered.
Returns some other positive integer when more octets need to be eaten.
"""
cdef int type = UTF8VALIDATOR_DFA[b]
if self.state != _UTF8_ACCEPT:
self.codepoint = (b & 0x3f) | (self.codepoint << 6)
else:
self.codepoint = (0xff >> type) & b
self.state = UTF8VALIDATOR_DFA[256 + self.state * 16 + type]
return self.state
def reset(self):
"""
Reset validator to start new incremental UTF-8 decode/validation.
"""
self.state = _UTF8_ACCEPT
self.codepoint = 0
self.i = 0
def validate(self, ba):
"""
Incrementally validate a chunk of bytes provided as bytearray.
Will return a quad (valid?, endsOnCodePoint?, currentIndex, totalIndex).
As soon as an octet is encountered which renders the octet sequence
invalid, a quad with valid? == False is returned. currentIndex returns
the index within the currently consumed chunk, and totalIndex the
index within the total consumed sequence that was the point of bail out.
When valid? == True, currentIndex will be len(ba) and totalIndex the
total amount of consumed bytes.
"""
cdef int state = self.state
cdef int i=0, b
cdef unsigned char* buf
cdef Py_ssize_t buf_len
PyObject_AsReadBuffer(ba, <void**>&buf, &buf_len)
for i in range(buf_len):
b = buf[i]
## optimized version of decode(), since we are not interested in actual code points
state = UTF8VALIDATOR_DFA[256 + (state << 4) + UTF8VALIDATOR_DFA[b]]
if state == _UTF8_REJECT:
self.i += i
self.state = state
return False, False, i, self.i
i = buf_len
self.i += i
self.state = state
return True, state == _UTF8_ACCEPT, i, self.i | willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
lomond_accel/dfa.h | C/C++ Header | static const char UTF8VALIDATOR_DFA[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // s7..s8
};
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
lomond_accel/mask.c | C | /* Generated by Cython 0.25.2 */
/* BEGIN: Cython Metadata
{
"distutils": {
"depends": []
},
"module_name": "lomond_accel.mask"
}
END: Cython Metadata */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000)
#error Cython requires Python 2.6+ or Python 3.2+.
#else
#define CYTHON_ABI "0_25_2"
#include <stddef.h>
#ifndef offsetof
#define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#ifndef HAVE_LONG_LONG
#if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000)
#define HAVE_LONG_LONG
#endif
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
#define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
#define CYTHON_COMPILING_IN_PYPY 1
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 0
#undef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 0
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#undef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#undef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 1
#undef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 0
#undef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 0
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#elif defined(PYSTON_VERSION)
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#undef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 0
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#undef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 0
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_PYSTON 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#ifndef CYTHON_USE_TYPE_SLOTS
#define CYTHON_USE_TYPE_SLOTS 1
#endif
#if PY_MAJOR_VERSION < 3
#undef CYTHON_USE_ASYNC_SLOTS
#define CYTHON_USE_ASYNC_SLOTS 0
#elif !defined(CYTHON_USE_ASYNC_SLOTS)
#define CYTHON_USE_ASYNC_SLOTS 1
#endif
#if PY_VERSION_HEX < 0x02070000
#undef CYTHON_USE_PYLONG_INTERNALS
#define CYTHON_USE_PYLONG_INTERNALS 0
#elif !defined(CYTHON_USE_PYLONG_INTERNALS)
#define CYTHON_USE_PYLONG_INTERNALS 1
#endif
#ifndef CYTHON_USE_PYLIST_INTERNALS
#define CYTHON_USE_PYLIST_INTERNALS 1
#endif
#ifndef CYTHON_USE_UNICODE_INTERNALS
#define CYTHON_USE_UNICODE_INTERNALS 1
#endif
#if PY_VERSION_HEX < 0x030300F0
#undef CYTHON_USE_UNICODE_WRITER
#define CYTHON_USE_UNICODE_WRITER 0
#elif !defined(CYTHON_USE_UNICODE_WRITER)
#define CYTHON_USE_UNICODE_WRITER 1
#endif
#ifndef CYTHON_AVOID_BORROWED_REFS
#define CYTHON_AVOID_BORROWED_REFS 0
#endif
#ifndef CYTHON_ASSUME_SAFE_MACROS
#define CYTHON_ASSUME_SAFE_MACROS 1
#endif
#ifndef CYTHON_UNPACK_METHODS
#define CYTHON_UNPACK_METHODS 1
#endif
#ifndef CYTHON_FAST_THREAD_STATE
#define CYTHON_FAST_THREAD_STATE 1
#endif
#ifndef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 1
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#undef SHIFT
#undef BASE
#undef MASK
#endif
#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
#define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyClass_Type
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_FASTCALL
#define METH_FASTCALL 0x80
typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args,
Py_ssize_t nargs, PyObject *kwnames);
#else
#define __Pyx_PyCFunctionFast _PyCFunctionFast
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)))))
#else
#define __Pyx_PyFastCFunction_Check(func) 0
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
#define CYTHON_PEP393_ENABLED 1
#define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\
0 : _PyUnicode_Ready((PyObject *)(op)))
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
#define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
#define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
#define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
#else
#define CYTHON_PEP393_ENABLED 0
#define PyUnicode_1BYTE_KIND 1
#define PyUnicode_2BYTE_KIND 2
#define PyUnicode_4BYTE_KIND 4
#define __Pyx_PyUnicode_READY(op) (0)
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
#define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
#define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
#define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
#define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
#define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
#define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
#endif
#if CYTHON_COMPILING_IN_PYPY
#define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
#else
#define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
#define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
#define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
#define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
#endif
#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
#define PyObject_Malloc(s) PyMem_Malloc(s)
#define PyObject_Free(p) PyMem_Free(p)
#define PyObject_Realloc(p) PyMem_Realloc(p)
#endif
#if CYTHON_COMPILING_IN_PYSTON
#define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
#else
#define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
#define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
#else
#define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
#define PyObject_ASCII(o) PyObject_Repr(o)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyStringObject PyUnicodeObject
#define PyString_Type PyUnicode_Type
#define PyString_Check PyUnicode_Check
#define PyString_CheckExact PyUnicode_CheckExact
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
#define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
#define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
#if PY_MAJOR_VERSION >= 3
#define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyNumber_Int PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBoolObject PyLongObject
#endif
#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
#ifndef PyUnicode_InternFromString
#define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
#endif
#endif
#if PY_VERSION_HEX < 0x030200A4
typedef long Py_hash_t;
#define __Pyx_PyInt_FromHash_t PyInt_FromLong
#define __Pyx_PyInt_AsHash_t PyInt_AsLong
#else
#define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
#define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func))
#else
#define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
#endif
#if CYTHON_USE_ASYNC_SLOTS
#if PY_VERSION_HEX >= 0x030500B1
#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
#else
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
} __Pyx_PyAsyncMethodsStruct;
#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
#endif
#else
#define __Pyx_PyType_AsAsync(obj) NULL
#endif
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
#endif
#ifndef CYTHON_MAYBE_UNUSED_VAR
# if defined(__cplusplus)
template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
# else
# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
# endif
#endif
#ifndef CYTHON_NCP_UNUSED
# if CYTHON_COMPILING_IN_CPYTHON
# define CYTHON_NCP_UNUSED
# else
# define CYTHON_NCP_UNUSED CYTHON_UNUSED
# endif
#endif
#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
#ifndef CYTHON_INLINE
#if defined(__clang__)
#define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
#elif defined(__GNUC__)
#define CYTHON_INLINE __inline__
#elif defined(_MSC_VER)
#define CYTHON_INLINE __inline
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_INLINE inline
#else
#define CYTHON_INLINE
#endif
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
#define __Pyx_truncl trunc
#else
#define __Pyx_truncl truncl
#endif
#define __PYX_ERR(f_index, lineno, Ln_error) \
{ \
__pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \
}
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
#endif
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#define __PYX_HAVE__lomond_accel__mask
#define __PYX_HAVE_API__lomond_accel__mask
#include <string.h>
#include <stdio.h>
#include "pythread.h"
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#ifdef PYREX_WITHOUT_ASSERTIONS
#define CYTHON_WITHOUT_ASSERTIONS
#endif
typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_uchar_cast(c) ((unsigned char)c)
#define __Pyx_long_cast(x) ((long)x)
#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\
(sizeof(type) < sizeof(Py_ssize_t)) ||\
(sizeof(type) > sizeof(Py_ssize_t) &&\
likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX) &&\
(!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
v == (type)PY_SSIZE_T_MIN))) ||\
(sizeof(type) == sizeof(Py_ssize_t) &&\
(is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
v == (type)PY_SSIZE_T_MAX))) )
#if defined (__cplusplus) && __cplusplus >= 201103L
#include <cstdlib>
#define __Pyx_sst_abs(value) std::abs(value)
#elif SIZEOF_INT >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) abs(value)
#elif SIZEOF_LONG >= SIZEOF_SIZE_T
#define __Pyx_sst_abs(value) labs(value)
#elif defined (_MSC_VER) && defined (_M_X64)
#define __Pyx_sst_abs(value) _abs64(value)
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define __Pyx_sst_abs(value) llabs(value)
#elif defined (__GNUC__)
#define __Pyx_sst_abs(value) __builtin_llabs(value)
#else
#define __Pyx_sst_abs(value) ((value<0) ? -value : value)
#endif
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
#define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
#if PY_MAJOR_VERSION < 3
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u)
{
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return (size_t)(u_end - u - 1);
}
#else
#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen
#endif
#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False))
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_ASSUME_SAFE_MACROS
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
#else
#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
#endif
#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
const char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
if (strcmp(default_encoding_c, "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
char ascii_chars[128];
int c;
for (c = 0; c < 128; c++) {
ascii_chars[c] = c;
}
__Pyx_sys_getdefaultencoding_not_ascii = 1;
ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
if (!ascii_chars_u) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
PyErr_Format(
PyExc_ValueError,
"This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
default_encoding_c);
goto bad;
}
Py_DECREF(ascii_chars_u);
Py_DECREF(ascii_chars_b);
}
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (!sys) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
Py_DECREF(sys);
if (!default_encoding) goto bad;
default_encoding_c = PyBytes_AsString(default_encoding);
if (!default_encoding_c) goto bad;
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c));
if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
/* Test for GCC > 2.95 */
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* !__GNUC__ or GCC < 2.95 */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static PyObject *__pyx_m;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static PyObject *__pyx_empty_unicode;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
static const char *__pyx_f[] = {
"lomond_accel/mask.pyx",
"type.pxd",
"bool.pxd",
"complex.pxd",
};
/*--- Type declarations ---*/
/* --- Runtime support code (head) --- */
/* Refnanny.proto */
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*SetupContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefNannyAPIStruct;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
#define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
if (acquire_gil) {\
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
PyGILState_Release(__pyx_gilstate_save);\
} else {\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
}
#else
#define __Pyx_RefNannySetupContext(name, acquire_gil)\
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
#define __Pyx_RefNannyFinishContext()\
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
#define __Pyx_RefNannyDeclarations
#define __Pyx_RefNannySetupContext(name, acquire_gil)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XINCREF(r) Py_XINCREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_XGOTREF(r)
#define __Pyx_XGIVEREF(r)
#endif
#define __Pyx_XDECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_XDECREF(tmp);\
} while (0)
#define __Pyx_DECREF_SET(r, v) do {\
PyObject *tmp = (PyObject *) r;\
r = v; __Pyx_DECREF(tmp);\
} while (0)
#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
/* PyObjectGetAttrStr.proto */
#if CYTHON_USE_TYPE_SLOTS
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
/* GetBuiltinName.proto */
static PyObject *__Pyx_GetBuiltinName(PyObject *name);
/* RaiseArgTupleInvalid.proto */
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);
/* RaiseDoubleKeywords.proto */
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);
/* ParseKeywords.proto */
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
const char* function_name);
/* ArgTypeTest.proto */
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
const char *name, int exact);
/* PyObjectCall.proto */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
/* CodeObjectCache.proto */
typedef struct {
PyCodeObject* code_object;
int code_line;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
int count;
int max_count;
__Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
/* AddTraceback.proto */
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename);
/* CIntToPy.proto */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
/* CIntFromPy.proto */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
/* CIntFromPy.proto */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
/* CheckBinaryVersion.proto */
static int __Pyx_check_binary_version(void);
/* PyIdentifierFromString.proto */
#if !defined(__Pyx_PyIdentifier_FromString)
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s)
#else
#define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s)
#endif
#endif
/* ModuleImport.proto */
static PyObject *__Pyx_ImportModule(const char *name);
/* TypeImport.proto */
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict);
/* InitStrings.proto */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
/* Module declarations from 'cpython.version' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
/* Module declarations from 'libc.string' */
/* Module declarations from 'libc.stdio' */
/* Module declarations from 'cpython.object' */
/* Module declarations from 'cpython.ref' */
/* Module declarations from 'cpython.exc' */
/* Module declarations from 'cpython.module' */
/* Module declarations from 'cpython.mem' */
/* Module declarations from 'cpython.tuple' */
/* Module declarations from 'cpython.list' */
/* Module declarations from 'cpython.sequence' */
/* Module declarations from 'cpython.mapping' */
/* Module declarations from 'cpython.iterator' */
/* Module declarations from 'cpython.number' */
/* Module declarations from 'cpython.int' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.bool' */
static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0;
/* Module declarations from 'cpython.long' */
/* Module declarations from 'cpython.float' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.complex' */
static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0;
/* Module declarations from 'cpython.string' */
/* Module declarations from 'cpython.unicode' */
/* Module declarations from 'cpython.dict' */
/* Module declarations from 'cpython.instance' */
/* Module declarations from 'cpython.function' */
/* Module declarations from 'cpython.method' */
/* Module declarations from 'cpython.weakref' */
/* Module declarations from 'cpython.getargs' */
/* Module declarations from 'cpython.pythread' */
/* Module declarations from 'cpython.pystate' */
/* Module declarations from 'cpython.cobject' */
/* Module declarations from 'cpython.oldbuffer' */
/* Module declarations from 'cpython.set' */
/* Module declarations from 'cpython.buffer' */
/* Module declarations from 'cpython.bytes' */
/* Module declarations from 'cpython.pycapsule' */
/* Module declarations from 'cpython' */
/* Module declarations from 'libc.stdint' */
/* Module declarations from 'lomond_accel.mask' */
#define __Pyx_MODULE_NAME "lomond_accel.mask"
int __pyx_module_is_main_lomond_accel__mask = 0;
/* Implementation of 'lomond_accel.mask' */
static PyObject *__pyx_builtin_range;
static const char __pyx_k_i[] = "i";
static const char __pyx_k_data[] = "data";
static const char __pyx_k_main[] = "__main__";
static const char __pyx_k_mask[] = "mask";
static const char __pyx_k_test[] = "__test__";
static const char __pyx_k_range[] = "range";
static const char __pyx_k_in_buf[] = "in_buf";
static const char __pyx_k_data_len[] = "data_len";
static const char __pyx_k_mask_buf[] = "mask_buf";
static const char __pyx_k_uint32_msk[] = "uint32_msk";
static const char __pyx_k_uint64_msk[] = "uint64_msk";
static const char __pyx_k_lomond_accel_mask[] = "lomond_accel.mask";
static const char __pyx_k_Users_will_projects_lomond_acce[] = "/Users/will/projects/lomond-accel/lomond_accel/mask.pyx";
static PyObject *__pyx_kp_s_Users_will_projects_lomond_acce;
static PyObject *__pyx_n_s_data;
static PyObject *__pyx_n_s_data_len;
static PyObject *__pyx_n_s_i;
static PyObject *__pyx_n_s_in_buf;
static PyObject *__pyx_n_s_lomond_accel_mask;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_mask;
static PyObject *__pyx_n_s_mask_buf;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_uint32_msk;
static PyObject *__pyx_n_s_uint64_msk;
static PyObject *__pyx_pf_12lomond_accel_4mask_mask(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data); /* proto */
static PyObject *__pyx_tuple_;
static PyObject *__pyx_codeobj__2;
/* "lomond_accel/mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(bytes mask, bytearray data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
/* Python wrapper */
static PyObject *__pyx_pw_12lomond_accel_4mask_1mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_12lomond_accel_4mask_mask[] = "Note, this function mutates it's `data` argument\n ";
static PyMethodDef __pyx_mdef_12lomond_accel_4mask_1mask = {"mask", (PyCFunction)__pyx_pw_12lomond_accel_4mask_1mask, METH_VARARGS|METH_KEYWORDS, __pyx_doc_12lomond_accel_4mask_mask};
static PyObject *__pyx_pw_12lomond_accel_4mask_1mask(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_mask = 0;
PyObject *__pyx_v_data = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("mask (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_mask,&__pyx_n_s_data,0};
PyObject* values[2] = {0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("mask", 1, 2, 2, 1); __PYX_ERR(0, 10, __pyx_L3_error)
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "mask") < 0)) __PYX_ERR(0, 10, __pyx_L3_error)
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 2) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
}
__pyx_v_mask = ((PyObject*)values[0]);
__pyx_v_data = ((PyObject*)values[1]);
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("mask", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 10, __pyx_L3_error)
__pyx_L3_error:;
__Pyx_AddTraceback("lomond_accel.mask.mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), (&PyBytes_Type), 1, "mask", 1))) __PYX_ERR(0, 10, __pyx_L1_error)
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyByteArray_Type), 1, "data", 1))) __PYX_ERR(0, 10, __pyx_L1_error)
__pyx_r = __pyx_pf_12lomond_accel_4mask_mask(__pyx_self, __pyx_v_mask, __pyx_v_data);
/* function exit code */
goto __pyx_L0;
__pyx_L1_error:;
__pyx_r = NULL;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_12lomond_accel_4mask_mask(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data) {
Py_ssize_t __pyx_v_data_len;
Py_ssize_t __pyx_v_i;
unsigned char *__pyx_v_in_buf;
unsigned char const *__pyx_v_mask_buf;
uint32_t __pyx_v_uint32_msk;
uint64_t __pyx_v_uint64_msk;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
char *__pyx_t_6;
uint64_t *__pyx_t_7;
long __pyx_t_8;
uint32_t *__pyx_t_9;
Py_ssize_t __pyx_t_10;
Py_ssize_t __pyx_t_11;
__Pyx_RefNannySetupContext("mask", 0);
__Pyx_INCREF(__pyx_v_mask);
__Pyx_INCREF(__pyx_v_data);
/* "lomond_accel/mask.pyx":21
* uint64_t uint64_msk
*
* assert len(mask) == 4 # <<<<<<<<<<<<<<
*
* if not isinstance(mask, bytes):
*/
#ifndef CYTHON_WITHOUT_ASSERTIONS
if (unlikely(!Py_OptimizeFlag)) {
if (unlikely(__pyx_v_mask == Py_None)) {
PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()");
__PYX_ERR(0, 21, __pyx_L1_error)
}
__pyx_t_1 = PyBytes_GET_SIZE(__pyx_v_mask); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 21, __pyx_L1_error)
if (unlikely(!((__pyx_t_1 == 4) != 0))) {
PyErr_SetNone(PyExc_AssertionError);
__PYX_ERR(0, 21, __pyx_L1_error)
}
}
#endif
/* "lomond_accel/mask.pyx":23
* assert len(mask) == 4
*
* if not isinstance(mask, bytes): # <<<<<<<<<<<<<<
* mask = bytes(mask)
*
*/
__pyx_t_2 = PyBytes_Check(__pyx_v_mask);
__pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0);
if (__pyx_t_3) {
/* "lomond_accel/mask.pyx":24
*
* if not isinstance(mask, bytes):
* mask = bytes(mask) # <<<<<<<<<<<<<<
*
* if isinstance(data, bytearray):
*/
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_INCREF(__pyx_v_mask);
__Pyx_GIVEREF(__pyx_v_mask);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_mask);
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyBytes_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 24, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_DECREF_SET(__pyx_v_mask, ((PyObject*)__pyx_t_5));
__pyx_t_5 = 0;
/* "lomond_accel/mask.pyx":23
* assert len(mask) == 4
*
* if not isinstance(mask, bytes): # <<<<<<<<<<<<<<
* mask = bytes(mask)
*
*/
}
/* "lomond_accel/mask.pyx":26
* mask = bytes(mask)
*
* if isinstance(data, bytearray): # <<<<<<<<<<<<<<
* data = <bytearray>data
* else:
*/
__pyx_t_3 = PyByteArray_Check(__pyx_v_data);
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
/* "lomond_accel/mask.pyx":27
*
* if isinstance(data, bytearray):
* data = <bytearray>data # <<<<<<<<<<<<<<
* else:
* data = bytearray(data)
*/
__pyx_t_5 = __pyx_v_data;
__Pyx_INCREF(__pyx_t_5);
__Pyx_DECREF_SET(__pyx_v_data, ((PyObject*)__pyx_t_5));
__pyx_t_5 = 0;
/* "lomond_accel/mask.pyx":26
* mask = bytes(mask)
*
* if isinstance(data, bytearray): # <<<<<<<<<<<<<<
* data = <bytearray>data
* else:
*/
goto __pyx_L4;
}
/* "lomond_accel/mask.pyx":29
* data = <bytearray>data
* else:
* data = bytearray(data) # <<<<<<<<<<<<<<
*
* data_len = len(data)
*/
/*else*/ {
__pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_data);
__Pyx_GIVEREF(__pyx_v_data);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_data);
__pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)(&PyByteArray_Type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 29, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF_SET(__pyx_v_data, ((PyObject*)__pyx_t_4));
__pyx_t_4 = 0;
}
__pyx_L4:;
/* "lomond_accel/mask.pyx":31
* data = bytearray(data)
*
* data_len = len(data) # <<<<<<<<<<<<<<
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
*/
__pyx_t_1 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 31, __pyx_L1_error)
__pyx_v_data_len = __pyx_t_1;
/* "lomond_accel/mask.pyx":32
*
* data_len = len(data)
* in_buf = <unsigned char*>PyByteArray_AsString(data) # <<<<<<<<<<<<<<
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
* uint32_msk = (<uint32_t*>mask_buf)[0]
*/
__pyx_t_6 = PyByteArray_AsString(__pyx_v_data); if (unlikely(__pyx_t_6 == NULL)) __PYX_ERR(0, 32, __pyx_L1_error)
__pyx_v_in_buf = ((unsigned char *)__pyx_t_6);
/* "lomond_accel/mask.pyx":33
* data_len = len(data)
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask) # <<<<<<<<<<<<<<
* uint32_msk = (<uint32_t*>mask_buf)[0]
*
*/
__pyx_t_6 = PyBytes_AsString(__pyx_v_mask); if (unlikely(__pyx_t_6 == NULL)) __PYX_ERR(0, 33, __pyx_L1_error)
__pyx_v_mask_buf = ((unsigned char const *)__pyx_t_6);
/* "lomond_accel/mask.pyx":34
* in_buf = <unsigned char*>PyByteArray_AsString(data)
* mask_buf = <const unsigned char*>PyBytes_AsString(mask)
* uint32_msk = (<uint32_t*>mask_buf)[0] # <<<<<<<<<<<<<<
*
* # TODO: align in_data ptr to achieve even faster speeds
*/
__pyx_v_uint32_msk = (((uint32_t *)__pyx_v_mask_buf)[0]);
/* "lomond_accel/mask.pyx":39
* # does it need in python ?! malloc() always aligns to sizeof(long) bytes
*
* if sizeof(size_t) >= 8: # <<<<<<<<<<<<<<
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk
*/
__pyx_t_2 = (((sizeof(size_t)) >= 8) != 0);
if (__pyx_t_2) {
/* "lomond_accel/mask.pyx":40
*
* if sizeof(size_t) >= 8:
* uint64_msk = uint32_msk # <<<<<<<<<<<<<<
* uint64_msk = (uint64_msk << 32) | uint32_msk
*
*/
__pyx_v_uint64_msk = __pyx_v_uint32_msk;
/* "lomond_accel/mask.pyx":41
* if sizeof(size_t) >= 8:
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk # <<<<<<<<<<<<<<
*
* while data_len >= 8:
*/
__pyx_v_uint64_msk = ((__pyx_v_uint64_msk << 32) | __pyx_v_uint32_msk);
/* "lomond_accel/mask.pyx":43
* uint64_msk = (uint64_msk << 32) | uint32_msk
*
* while data_len >= 8: # <<<<<<<<<<<<<<
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8
*/
while (1) {
__pyx_t_2 = ((__pyx_v_data_len >= 8) != 0);
if (!__pyx_t_2) break;
/* "lomond_accel/mask.pyx":44
*
* while data_len >= 8:
* (<uint64_t*>in_buf)[0] ^= uint64_msk # <<<<<<<<<<<<<<
* in_buf += 8
* data_len -= 8
*/
__pyx_t_7 = ((uint64_t *)__pyx_v_in_buf);
__pyx_t_8 = 0;
(__pyx_t_7[__pyx_t_8]) = ((__pyx_t_7[__pyx_t_8]) ^ __pyx_v_uint64_msk);
/* "lomond_accel/mask.pyx":45
* while data_len >= 8:
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8 # <<<<<<<<<<<<<<
* data_len -= 8
*
*/
__pyx_v_in_buf = (__pyx_v_in_buf + 8);
/* "lomond_accel/mask.pyx":46
* (<uint64_t*>in_buf)[0] ^= uint64_msk
* in_buf += 8
* data_len -= 8 # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_data_len = (__pyx_v_data_len - 8);
}
/* "lomond_accel/mask.pyx":39
* # does it need in python ?! malloc() always aligns to sizeof(long) bytes
*
* if sizeof(size_t) >= 8: # <<<<<<<<<<<<<<
* uint64_msk = uint32_msk
* uint64_msk = (uint64_msk << 32) | uint32_msk
*/
}
/* "lomond_accel/mask.pyx":49
*
*
* while data_len >= 4: # <<<<<<<<<<<<<<
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4
*/
while (1) {
__pyx_t_2 = ((__pyx_v_data_len >= 4) != 0);
if (!__pyx_t_2) break;
/* "lomond_accel/mask.pyx":50
*
* while data_len >= 4:
* (<uint32_t*>in_buf)[0] ^= uint32_msk # <<<<<<<<<<<<<<
* in_buf += 4
* data_len -= 4
*/
__pyx_t_9 = ((uint32_t *)__pyx_v_in_buf);
__pyx_t_8 = 0;
(__pyx_t_9[__pyx_t_8]) = ((__pyx_t_9[__pyx_t_8]) ^ __pyx_v_uint32_msk);
/* "lomond_accel/mask.pyx":51
* while data_len >= 4:
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4 # <<<<<<<<<<<<<<
* data_len -= 4
*
*/
__pyx_v_in_buf = (__pyx_v_in_buf + 4);
/* "lomond_accel/mask.pyx":52
* (<uint32_t*>in_buf)[0] ^= uint32_msk
* in_buf += 4
* data_len -= 4 # <<<<<<<<<<<<<<
*
* for i in range(0, data_len):
*/
__pyx_v_data_len = (__pyx_v_data_len - 4);
}
/* "lomond_accel/mask.pyx":54
* data_len -= 4
*
* for i in range(0, data_len): # <<<<<<<<<<<<<<
* in_buf[i] ^= mask_buf[i]
*/
__pyx_t_1 = __pyx_v_data_len;
for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) {
__pyx_v_i = __pyx_t_10;
/* "lomond_accel/mask.pyx":55
*
* for i in range(0, data_len):
* in_buf[i] ^= mask_buf[i] # <<<<<<<<<<<<<<
*/
__pyx_t_11 = __pyx_v_i;
(__pyx_v_in_buf[__pyx_t_11]) = ((__pyx_v_in_buf[__pyx_t_11]) ^ (__pyx_v_mask_buf[__pyx_v_i]));
}
/* "lomond_accel/mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(bytes mask, bytearray data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("lomond_accel.mask.mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_mask);
__Pyx_XDECREF(__pyx_v_data);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
#if PY_VERSION_HEX < 0x03020000
{ PyObject_HEAD_INIT(NULL) NULL, 0, NULL },
#else
PyModuleDef_HEAD_INIT,
#endif
"mask",
0, /* m_doc */
-1, /* m_size */
__pyx_methods /* m_methods */,
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_kp_s_Users_will_projects_lomond_acce, __pyx_k_Users_will_projects_lomond_acce, sizeof(__pyx_k_Users_will_projects_lomond_acce), 0, 0, 1, 0},
{&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1},
{&__pyx_n_s_data_len, __pyx_k_data_len, sizeof(__pyx_k_data_len), 0, 0, 1, 1},
{&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1},
{&__pyx_n_s_in_buf, __pyx_k_in_buf, sizeof(__pyx_k_in_buf), 0, 0, 1, 1},
{&__pyx_n_s_lomond_accel_mask, __pyx_k_lomond_accel_mask, sizeof(__pyx_k_lomond_accel_mask), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 0, 0, 1, 1},
{&__pyx_n_s_mask_buf, __pyx_k_mask_buf, sizeof(__pyx_k_mask_buf), 0, 0, 1, 1},
{&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_n_s_uint32_msk, __pyx_k_uint32_msk, sizeof(__pyx_k_uint32_msk), 0, 0, 1, 1},
{&__pyx_n_s_uint64_msk, __pyx_k_uint64_msk, sizeof(__pyx_k_uint64_msk), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 54, __pyx_L1_error)
return 0;
__pyx_L1_error:;
return -1;
}
static int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
/* "lomond_accel/mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(bytes mask, bytearray data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
__pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_mask, __pyx_n_s_data, __pyx_n_s_data_len, __pyx_n_s_i, __pyx_n_s_in_buf, __pyx_n_s_mask_buf, __pyx_n_s_uint32_msk, __pyx_n_s_uint64_msk); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_GOTREF(__pyx_tuple_);
__Pyx_GIVEREF(__pyx_tuple_);
__pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_will_projects_lomond_acce, __pyx_n_s_mask, 10, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 2, __pyx_L1_error);
return 0;
__pyx_L1_error:;
return -1;
}
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initmask(void); /*proto*/
PyMODINIT_FUNC initmask(void)
#else
PyMODINIT_FUNC PyInit_mask(void); /*proto*/
PyMODINIT_FUNC PyInit_mask(void)
#endif
{
PyObject *__pyx_t_1 = NULL;
__Pyx_RefNannyDeclarations
#if CYTHON_REFNANNY
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
if (!__Pyx_RefNanny) {
PyErr_Clear();
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
if (!__Pyx_RefNanny)
Py_FatalError("failed to import 'refnanny' module");
}
#endif
__Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_mask(void)", 0);
if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 2, __pyx_L1_error)
#ifdef __Pyx_CyFunction_USED
if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_Coroutine_USED
if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
#ifdef __Pyx_StopAsyncIteration_USED
if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
/*--- Library function declarations ---*/
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Module creation code ---*/
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4("mask", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) __PYX_ERR(0, 2, __pyx_L1_error)
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 2, __pyx_L1_error)
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 2, __pyx_L1_error)
#if CYTHON_COMPILING_IN_PYPY
Py_INCREF(__pyx_b);
#endif
if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 2, __pyx_L1_error);
/*--- Initialize various global constants etc. ---*/
if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
if (__pyx_module_is_main_lomond_accel__mask) {
if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 2, __pyx_L1_error)
if (!PyDict_GetItemString(modules, "lomond_accel.mask")) {
if (unlikely(PyDict_SetItemString(modules, "lomond_accel.mask", __pyx_m) < 0)) __PYX_ERR(0, 2, __pyx_L1_error)
}
}
#endif
/*--- Builtin init code ---*/
if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
/*--- Constants init code ---*/
if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
/*--- Global init code ---*/
/*--- Variable export code ---*/
/*--- Function export code ---*/
/*--- Type init code ---*/
/*--- Type import code ---*/
__pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type",
#if CYTHON_COMPILING_IN_PYPY
sizeof(PyTypeObject),
#else
sizeof(PyHeapTypeObject),
#endif
0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(1, 9, __pyx_L1_error)
__pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) __PYX_ERR(2, 8, __pyx_L1_error)
__pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) __PYX_ERR(3, 15, __pyx_L1_error)
/*--- Variable import code ---*/
/*--- Function import code ---*/
/*--- Execution code ---*/
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 2, __pyx_L1_error)
#endif
/* "lomond_accel/mask.pyx":10
* from libc.stdint cimport uint32_t, uint64_t, uintmax_t
*
* def mask(bytes mask, bytearray data): # <<<<<<<<<<<<<<
* """Note, this function mutates it's `data` argument
* """
*/
__pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_12lomond_accel_4mask_1mask, NULL, __pyx_n_s_lomond_accel_mask); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_mask, __pyx_t_1) < 0) __PYX_ERR(0, 10, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "lomond_accel/mask.pyx":2
*
* from cpython cimport PyBytes_AsString # <<<<<<<<<<<<<<
*
* #from cpython cimport PyByteArray_AsString # cython still not exports that
*/
__pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error)
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error)
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/*--- Wrapped vars code ---*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
if (__pyx_m) {
if (__pyx_d) {
__Pyx_AddTraceback("init lomond_accel.mask", __pyx_clineno, __pyx_lineno, __pyx_filename);
}
Py_DECREF(__pyx_m); __pyx_m = 0;
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init lomond_accel.mask");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if PY_MAJOR_VERSION < 3
return;
#else
return __pyx_m;
#endif
}
/* --- Runtime support code --- */
/* Refnanny */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule((char *)modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, (char *)"RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif
/* GetBuiltinName */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
/* RaiseArgTupleInvalid */
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
PyErr_Format(PyExc_TypeError,
"%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
func_name, more_or_less, num_expected,
(num_expected == 1) ? "" : "s", num_found);
}
/* RaiseDoubleKeywords */
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AsString(kw_name));
#endif
}
/* ParseKeywords */
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
continue;
}
name = first_kw_arg;
#if PY_MAJOR_VERSION < 3
if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) {
while (*name) {
if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
&& _PyString_Eq(**name, key)) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
if ((**argname == key) || (
(CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
&& _PyString_Eq(**argname, key))) {
goto arg_passed_twice;
}
argname++;
}
}
} else
#endif
if (likely(PyUnicode_Check(key))) {
while (*name) {
int cmp = (**name == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**name, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
int cmp = (**argname == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**argname, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) goto arg_passed_twice;
argname++;
}
}
} else
goto invalid_keyword_type;
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, key);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%.200s() got an unexpected keyword argument '%.200s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
/* ArgTypeTest */
static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) {
PyErr_Format(PyExc_TypeError,
"Argument '%.200s' has incorrect type (expected %.200s, got %.200s)",
name, type->tp_name, Py_TYPE(obj)->tp_name);
}
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
const char *name, int exact)
{
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
if (none_allowed && obj == Py_None) return 1;
else if (exact) {
if (likely(Py_TYPE(obj) == type)) return 1;
#if PY_MAJOR_VERSION == 2
else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
#endif
}
else {
if (likely(PyObject_TypeCheck(obj, type))) return 1;
}
__Pyx_RaiseArgumentTypeInvalid(name, obj, type);
return 0;
}
/* PyObjectCall */
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
result = (*call)(func, arg, kw);
Py_LeaveRecursiveCall();
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
/* CodeObjectCache */
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
int start = 0, mid = 0, end = count - 1;
if (end >= 0 && code_line > entries[end].code_line) {
return count;
}
while (start < end) {
mid = start + (end - start) / 2;
if (code_line < entries[mid].code_line) {
end = mid;
} else if (code_line > entries[mid].code_line) {
start = mid + 1;
} else {
return mid;
}
}
if (code_line <= entries[mid].code_line) {
return mid;
} else {
return mid + 1;
}
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
PyCodeObject* code_object;
int pos;
if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
return NULL;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
return NULL;
}
code_object = __pyx_code_cache.entries[pos].code_object;
Py_INCREF(code_object);
return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
int pos, i;
__Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
if (unlikely(!code_line)) {
return;
}
if (unlikely(!entries)) {
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
if (likely(entries)) {
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = 64;
__pyx_code_cache.count = 1;
entries[0].code_line = code_line;
entries[0].code_object = code_object;
Py_INCREF(code_object);
}
return;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
PyCodeObject* tmp = entries[pos].code_object;
entries[pos].code_object = code_object;
Py_DECREF(tmp);
return;
}
if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
int new_max = __pyx_code_cache.max_count + 64;
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
__pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry));
if (unlikely(!entries)) {
return;
}
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = new_max;
}
for (i=__pyx_code_cache.count; i>pos; i--) {
entries[i] = entries[i-1];
}
entries[pos].code_line = code_line;
entries[pos].code_object = code_object;
__pyx_code_cache.count++;
Py_INCREF(code_object);
}
/* AddTraceback */
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(filename);
#else
py_srcfile = PyUnicode_FromString(filename);
#endif
if (!py_srcfile) goto bad;
if (c_line) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_code = __Pyx_PyCode_New(
0,
0,
0,
0,
0,
__pyx_empty_bytes, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
py_line,
__pyx_empty_bytes /*PyObject *lnotab*/
);
Py_DECREF(py_srcfile);
Py_DECREF(py_funcname);
return py_code;
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
py_code = __pyx_find_code_object(c_line ? c_line : py_line);
if (!py_code) {
py_code = __Pyx_CreateCodeObjectForTraceback(
funcname, c_line, py_line, filename);
if (!py_code) goto bad;
__pyx_insert_code_object(c_line ? c_line : py_line, py_code);
}
py_frame = PyFrame_New(
PyThreadState_GET(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
__pyx_d, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
__Pyx_PyFrame_SetLineNumber(py_frame, py_line);
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
/* CIntToPy */
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) -1, const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(long) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value);
#endif
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
return PyLong_FromLongLong((PY_LONG_LONG) value);
#endif
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
/* CIntFromPyVerify */
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0)
#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\
__PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1)
#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\
{\
func_type value = func_value;\
if (sizeof(target_type) < sizeof(func_type)) {\
if (unlikely(value != (func_type) (target_type) value)) {\
func_type zero = 0;\
if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\
return (target_type) -1;\
if (is_unsigned && unlikely(value < zero))\
goto raise_neg_overflow;\
else\
goto raise_overflow;\
}\
}\
return (target_type) value;\
}
/* CIntFromPy */
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) -1, const_zero = (long) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(long) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0])
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) {
return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) {
return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) {
return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (long) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (long) 0;
case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0])
case -2:
if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(long) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(long) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(long) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) {
return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])));
}
}
break;
}
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(long) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
long val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (long) -1;
}
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to long");
return (long) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
/* CIntFromPy */
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) -1, const_zero = (int) 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x))
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
goto raise_neg_overflow;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0])
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) {
return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) {
return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) {
return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]));
}
}
break;
}
#endif
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(Py_SIZE(x) < 0)) {
goto raise_neg_overflow;
}
#else
{
int result = PyObject_RichCompareBool(x, Py_False, Py_LT);
if (unlikely(result < 0))
return (int) -1;
if (unlikely(result == 1))
goto raise_neg_overflow;
}
#endif
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x))
#endif
}
} else {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)x)->ob_digit;
switch (Py_SIZE(x)) {
case 0: return (int) 0;
case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0]))
case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0])
case -2:
if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 2:
if (8 * sizeof(int) > 1 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -3:
if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 3:
if (8 * sizeof(int) > 2 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case -4:
if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
case 4:
if (8 * sizeof(int) > 3 * PyLong_SHIFT) {
if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])))
} else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) {
return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])));
}
}
break;
}
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x))
#ifdef HAVE_LONG_LONG
} else if (sizeof(int) <= sizeof(PY_LONG_LONG)) {
__PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x))
#endif
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
int val;
PyObject *v = __Pyx_PyNumber_IntOrLong(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (int) -1;
}
} else {
int val;
PyObject *tmp = __Pyx_PyNumber_IntOrLong(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
raise_overflow:
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int) -1;
raise_neg_overflow:
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
/* CheckBinaryVersion */
static int __Pyx_check_binary_version(void) {
char ctversion[4], rtversion[4];
PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
char message[200];
PyOS_snprintf(message, sizeof(message),
"compiletime version %s of module '%.100s' "
"does not match runtime version %s",
ctversion, __Pyx_MODULE_NAME, rtversion);
return PyErr_WarnEx(NULL, message, 1);
}
return 0;
}
/* ModuleImport */
#ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
static PyObject *__Pyx_ImportModule(const char *name) {
PyObject *py_name = 0;
PyObject *py_module = 0;
py_name = __Pyx_PyIdentifier_FromString(name);
if (!py_name)
goto bad;
py_module = PyImport_Import(py_name);
Py_DECREF(py_name);
return py_module;
bad:
Py_XDECREF(py_name);
return 0;
}
#endif
/* TypeImport */
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
size_t size, int strict)
{
PyObject *py_module = 0;
PyObject *result = 0;
PyObject *py_name = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
py_module = __Pyx_ImportModule(module_name);
if (!py_module)
goto bad;
py_name = __Pyx_PyIdentifier_FromString(class_name);
if (!py_name)
goto bad;
result = PyObject_GetAttr(py_module, py_name);
Py_DECREF(py_name);
py_name = 0;
Py_DECREF(py_module);
py_module = 0;
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if (!strict && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd",
module_name, class_name, basicsize, size);
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
}
else if ((size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd",
module_name, class_name, basicsize, size);
goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(py_module);
Py_XDECREF(result);
return NULL;
}
#endif
/* InitStrings */
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else
if (t->is_unicode | t->is_str) {
if (t->intern) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->encoding) {
*t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
} else {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
}
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str));
}
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
__Pyx_sys_getdefaultencoding_not_ascii &&
#endif
PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
char* defenc_c;
PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
if (!defenc) return NULL;
defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
{
char* end = defenc_c + PyBytes_GET_SIZE(defenc);
char* c;
for (c = defenc_c; c < end; c++) {
if ((unsigned char) (*c) >= 128) {
PyUnicode_AsASCIIString(o);
return NULL;
}
}
}
#endif
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
#else
if (__Pyx_PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (PyUnicode_IS_ASCII(o)) {
*length = PyUnicode_GET_LENGTH(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else
return PyUnicode_AsUTF8AndSize(o, length);
#endif
#endif
} else
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#endif
{
char* result;
int r = PyBytes_AsStringAndSize(o, &result, length);
if (unlikely(r < 0)) {
return NULL;
} else {
return result;
}
}
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
int is_true = x == Py_True;
if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
else return PyObject_IsTrue(x);
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) {
#if CYTHON_USE_TYPE_SLOTS
PyNumberMethods *m;
#endif
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(x) || PyLong_Check(x))
#else
if (PyLong_Check(x))
#endif
return __Pyx_NewRef(x);
#if CYTHON_USE_TYPE_SLOTS
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = PyNumber_Int(x);
}
else if (m && m->nb_long) {
name = "long";
res = PyNumber_Long(x);
}
#else
if (m && m->nb_int) {
name = "int";
res = PyNumber_Long(x);
}
#endif
#else
res = PyNumber_Int(x);
#endif
if (res) {
#if PY_MAJOR_VERSION < 3
if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
if (!PyLong_Check(res)) {
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
name, name, Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject *x;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(b))) {
if (sizeof(Py_ssize_t) >= sizeof(long))
return PyInt_AS_LONG(b);
else
return PyInt_AsSsize_t(x);
}
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_USE_PYLONG_INTERNALS
const digit* digits = ((PyLongObject*)b)->ob_digit;
const Py_ssize_t size = Py_SIZE(b);
if (likely(__Pyx_sst_abs(size) <= 1)) {
ival = likely(size) ? digits[0] : 0;
if (size == -1) ival = -ival;
return ival;
} else {
switch (size) {
case 2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -2:
if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -3:
if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case 4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
case -4:
if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) {
return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]));
}
break;
}
}
#endif
return PyLong_AsSsize_t(b);
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
return PyInt_FromSize_t(ival);
}
#endif /* Py_PYTHON_H */
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
setup.py | Python | from setuptools import Extension, setup, find_packages
from Cython.Build import cythonize
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet'
]
# http://bit.ly/2alyerp
with open('lomond_accel/_version.py') as f:
exec(f.read())
with open('README.md') as f:
long_desc = f.read()
extensions = [
Extension('lomond_accel.mask', ['lomond_accel/_mask.pyx']),
Extension('lomond_accel.utf8validator', ['lomond_accel/_utf8validator.pyx']),
]
setup(
name='lomond-accel',
packages=find_packages(),
ext_modules=cythonize(extensions)
)
| willmcgugan/lomond-accel | 2 | Python | willmcgugan | Will McGugan | ||
shuffileid.py | Python | from random import Random
from typing import List
class ShuffleID:
"""An algorithm to shuffle an unsigned integer.
Each integer in a range of 2**bit_size should map to exactly one other integer in the same range. The
operation can be efficiently reversed.
"""
def __init__(self, bit_size: int, shuffles: List[List[int]]) -> None:
self.bit_size = bit_size
self.shuffles = shuffles
self._size = bit_size // 2
self._x_mask = (2 ** self._size) - 1
self._y_mask = self._x_mask << self._size
self._max_shuffle = 2 ** self._size
@classmethod
def from_seed(cls, bit_size: int, seed: int, rounds: int = 5) -> "ShuffleID":
"""Initialize from a random seed (the 'secret')."""
max_shuffle = 2 ** (bit_size // 2)
size = 2 ** (bit_size // 2) * 2
randrange = Random(seed).randrange
shuffles = [
[randrange(max_shuffle) for _ in range(size)] for _round in range(rounds)
]
return cls(bit_size, shuffles)
def encode(self, value: int) -> int:
"""Encode an integer."""
size = self._size
x = value & self._x_mask
y = (value & self._y_mask) >> size
max_shuffle = self._max_shuffle
for shuffle in self.shuffles:
x = (x + shuffle[y]) % max_shuffle
y = (y + shuffle[x + size]) % max_shuffle
encoded = (y << size) | x
return encoded
def decode(self, value: int) -> int:
"""Decode an integer."""
size = self._size
x = value & self._x_mask
y = (value & self._y_mask) >> size
max_shuffle = self._max_shuffle
for shuffle in reversed(self.shuffles):
y = (y - shuffle[x + size]) % max_shuffle
x = (x - shuffle[y]) % max_shuffle
encoded = (y << size) | x
return encoded
if __name__ == "__main__":
from rich import print
from rich.columns import Columns
from rich.color import Color
from rich.color_triplet import ColorTriplet
from rich.panel import Panel
from rich.style import Style
from rich.text import Text
from rich.table import Table
styles = [
Style(
bold=True,
color=Color.from_triplet(ColorTriplet((15 - n) * 16, n * 16, 255)),
)
for n in range(16)
]
columns = Columns()
def render_numbers(numbers, name):
grid = Table.grid(padding=1)
for row in range(16):
row = [
Text(
str(numbers[row * 16 + col]),
style=styles[numbers[row * 16 + col] % 16],
)
for col in range(16)
]
grid.add_row(*row)
columns.add_renderable(Panel.fit(grid, title=name))
numbers = list(range(256))
render_numbers(numbers, "Ordered")
shuffle_id = ShuffleID.from_seed(8, 5, rounds=5)
shuffled = [shuffle_id.encode(value) for value in range(256)]
render_numbers(shuffled, "Shuffled")
decoded = [shuffle_id.decode(value) for value in shuffled]
render_numbers(decoded, "Unshuffled")
print(columns)
| willmcgugan/shuffleid | 6 | Python | willmcgugan | Will McGugan | ||
tree.py | Python | # /// script
# dependencies = [
# "textual>=0.85.2",
# "rich>=13.9.4",
# ]
# ///
import asyncio
import grp
import itertools
import mimetypes
import pwd
import threading
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from stat import filemode
from rich import filesize
from rich.highlighter import Highlighter
from rich.syntax import Syntax
from rich.text import Text
from textual import events, on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.cache import LRUCache
from textual.containers import Horizontal, ScrollableContainer
from textual.message import Message
from textual.reactive import reactive, var
from textual.screen import ModalScreen
from textual.suggester import Suggester
from textual.validation import ValidationResult, Validator
from textual.widgets import DirectoryTree, Footer, Input, Label, Static, Tree
from textual.widgets.directory_tree import DirEntry
from textual.worker import get_current_worker
class DirectoryHighlighter(Highlighter):
"""Highlights directories in green, anything else in red.
This is a [Rich highlighter](https://rich.readthedocs.io/en/latest/highlighting.html),
which can stylize Text based on dynamic criteria.
Here we are highlighting valid directory paths in green, and invalid directory paths in red.
"""
def highlight(self, text: Text) -> None:
path = Path(text.plain).expanduser().resolve()
if path.is_dir():
text.stylize("green")
else:
text.stylize("red")
class DirectoryValidator(Validator):
"""Validate a string is a valid directory path.
This is a Textual [Validator](https://textual.textualize.io/widgets/input/#validating-input) used by
the input widget.
"""
def validate(self, value: str) -> ValidationResult:
path = Path(value).expanduser().resolve()
if path.is_dir():
return self.success()
else:
return self.failure("Directory required", value)
class ListDirCache:
"""A cache for listing a directory (not a Rich / Textual object).
This class is responsible for listing directories, and caching the results.
Listing a directory is a blocking operation, which is why we defer the work to a thread.
"""
def __init__(self) -> None:
self._cache: LRUCache[tuple[str, int], list[Path]] = LRUCache(100)
self._lock = threading.Lock()
async def listdir(self, path: Path, size: int) -> list[Path]:
cache_key = (str(path), size)
def iterdir_thread(path: Path) -> list[Path]:
"""Run iterdir in a thread.
Returns:
A list of paths.
"""
return list(itertools.islice(path.iterdir(), size))
with self._lock:
if cache_key in self._cache:
paths = self._cache[cache_key]
else:
paths = await asyncio.to_thread(iterdir_thread, path)
self._cache[cache_key] = paths
return paths
class DirectorySuggester(Suggester):
"""Suggest a directory.
This is a [Suggester](https://textual.textualize.io/api/suggester/#textual.suggester.Suggester) instance,
used by the Input widget to suggest auto-completions.
"""
def __init__(self) -> None:
self._cache = ListDirCache()
super().__init__()
async def get_suggestion(self, value: str) -> str | None:
"""Suggest the first matching directory."""
try:
path = Path(value)
name = path.name
children = await self._cache.listdir(
path.expanduser() if path.is_dir() else path.parent.expanduser(), 100
)
possible_paths = [
f"{sibling_path}/"
for sibling_path in children
if sibling_path.name.lower().startswith(name.lower())
and sibling_path.is_dir()
]
if possible_paths:
possible_paths.sort(key=str.__len__)
suggestion = possible_paths[0]
if "~" in value:
home = str(Path("~").expanduser())
suggestion = suggestion.replace(home, "~", 1)
return suggestion
except FileNotFoundError:
pass
return None
class PathComponent(Label):
"""Clickable component in a path.
A simple widget that displays text with a hover effect, that sends
a message when clicked.
"""
DEFAULT_CSS = """
PathComponent {
&:hover { text-style: reverse; }
}
"""
def on_click(self, event: events.Click) -> None:
self.post_message(PathNavigator.NewPath(Path(self.name or "")))
class InfoBar(Horizontal):
"""A widget to display information regarding a file, such as user / size / modification date."""
DEFAULT_CSS = """
InfoBar {
margin: 0 1;
height: 1;
dock: bottom;
.error { color: ansi_bright_red; }
.mode { color: ansi_red; }
.user-name { color: ansi_green; }
.group-name { color: ansi_yellow; }
.file-size {
color: ansi_magenta;
text-style: bold;
}
.modified-time { color: ansi_cyan; }
Label { margin: 0 1 0 0; }
}
"""
path: reactive[Path] = reactive(Path, recompose=True)
@staticmethod
def datetime_to_ls_format(date_time: datetime) -> str:
"""Convert a datetime object to a string format similar to ls -la output."""
if date_time.year == datetime.now().year:
# For dates in the current year, use format: "day month HH:MM"
return date_time.strftime("%d %b %H:%M")
else:
# For dates not in the current year, use format: "day month year"
return date_time.strftime("%d %b %Y")
def compose(self) -> ComposeResult:
try:
stat = self.path.stat()
except Exception:
yield Label("failed to get file info", classes="error")
else:
user_name = pwd.getpwuid(stat.st_uid).pw_name
group_name = grp.getgrgid(stat.st_gid).gr_name
modified_time = datetime.fromtimestamp(stat.st_mtime)
yield Label(filemode(stat.st_mode), classes="mode")
yield Label(user_name, classes="user-name")
yield Label(group_name, classes="group-name")
yield Label(
self.datetime_to_ls_format(modified_time), classes="modified-time"
)
if not self.path.is_dir():
label = Label(filesize.decimal(stat.st_size), classes="file-size")
label.tooltip = f"{stat.st_size} bytes"
yield label
class PathDisplay(Horizontal):
"""A widget to display the path at the top of the UI.
Not just simple text, this consists of clickable path components.
"""
DEFAULT_CSS = """
PathDisplay {
layout: horizontal;
height: 1;
dock: top;
align: center top;
text-style: bold;
color: ansi_green;
.separator { margin: 0 0; }
}
"""
path: reactive[Path] = reactive(Path, recompose=True)
def compose(self) -> ComposeResult:
path = self.path.resolve().absolute()
yield Label("📁 ", classes="separator")
components = str(path).split("/")
root_component = PathComponent("/", name="/")
root_component.tooltip = "/"
yield root_component
for index, component in enumerate(components, 1):
partial_path = "/".join(components[:index])
component_label = PathComponent(component, name=partial_path)
component_label.tooltip = partial_path
yield component_label
if index > 1 and index < len(components):
yield Label("/", classes="separator")
class PathScreen(ModalScreen[str | None]):
"""A [Modal screen](https://textual.textualize.io/guide/screens/#modal-screens) containing an editable path.
This is displayed when the user summons the "goto" functionality.
As a modal screen, it is displayed on top of the previous screen, but only the widgets
her will be usable.
"""
BINDINGS = [("escape", "dismiss", "cancel")]
CSS = """
PathScreen {
align: center top;
Horizontal {
margin-left: 1;
height: 1;
dock: top;
}
Input {
padding: 0 1;
border: none !important;
height: 1;
&>.input--placeholder, &>.input--suggestion {
text-style: dim not bold !important;
color: ansi_default;
}
&.-valid {
text-style: bold;
color: ansi_green;
}
&.-invalid {
text-style: bold;
color: ansi_red;
}
}
}
"""
def __init__(self, path: str) -> None:
super().__init__()
self.path = path.rstrip("/") + "/"
def compose(self) -> ComposeResult:
with Horizontal():
yield Label("📂")
# The validator and suggester instances pack a lot of functionality in to this input.
yield Input(
value=self.path,
validators=[DirectoryValidator()],
suggester=DirectorySuggester(),
classes="-ansi-colors",
)
yield (footer := Footer(classes="-ansi-colors"))
footer.compact = True
@on(Input.Submitted)
def on_input_submitted(self, event: Input.Submitted) -> None:
"""If the user submits the input (with enter), we return the value of the input to the caller."""
self.dismiss(event.input.value)
def action_dismiss(self):
"""If the user dismisses the screen with the escape key, we return None to the caller."""
self.dismiss(None)
class PreviewWindow(ScrollableContainer):
"""Widget to show a preview of a file.
A scrollable container that contains a [Rich Syntax](https://rich.readthedocs.io/en/latest/syntax.html) object
which highlights and formats text.
"""
ALLOW_MAXIMIZE = True
DEFAULT_CSS = """
PreviewWindow {
width: 1fr;
height: 1fr;
border: heavy blank;
overflow-y: scroll;
&:focus { border: heavy ansi_blue; }
#content { width: auto; }
&.-preview-unavailable {
overflow: auto;
hatch: right ansi_black;
align: center middle;
text-style: bold;
color: ansi_red;
}
}
"""
DEFAULT_CLASSES = "-ansi-scrollbar"
path: var[Path] = var(Path)
@work(exclusive=True)
async def update_syntax(self, path: Path) -> None:
"""Update the preview in a worker.
A worker runs the code in a concurrent asyncio Task.
Args:
path: A Path to the file to get the content for.
"""
worker = get_current_worker()
content = self.query_one("#content", Static)
if path.is_file():
_file_type, encoding = mimetypes.guess_type(str(path))
# A text file, we can attempt to syntax highlight it
def read_lines() -> list[str] | None:
"""A function to read lines from path in a thread."""
try:
with open(path, "rt", encoding=encoding or "utf-8") as text_file:
return text_file.readlines(1024 * 32)
except Exception:
# We could be more precise with error handling here, but for now
# we will treat all errors as fails.
return None
# Read the lines in a thread so as not to pause the UI
lines = await asyncio.to_thread(read_lines)
if lines is None:
self.call_later(content.update, "Preview not available")
self.add_class("-preview-unavailable")
return
if worker.is_cancelled:
return
code = "".join(lines)
lexer = Syntax.guess_lexer(str(path), code)
try:
syntax = Syntax(
code,
lexer,
word_wrap=False,
indent_guides=True,
line_numbers=True,
theme="ansi_light",
)
except Exception:
return
content.update(syntax)
self.remove_class("-preview-unavailable")
def watch_path(self, path: Path) -> None:
self.update_syntax(path)
def compose(self) -> ComposeResult:
yield Static("", id="content")
class PathNavigator(Horizontal):
"""The top-level widget, containing the directory tree and preview window."""
DEFAULT_CSS = """
PathNavigator {
height: auto;
max-height: 100%;
DirectoryTree {
height: auto;
max-height: 100%;
width: 1fr;
border: heavy blank;
&:focus { border: heavy ansi_blue; }
}
PreviewWindow { display: None; }
&.-show-preview {
PreviewWindow { display: block; }
}
}
"""
BINDINGS = [
Binding("r", "reload", "reload", tooltip="Refresh tree from filesystem"),
Binding("g", "goto", "go to", tooltip="Go to a new root path"),
Binding("p", "toggle_preview", "preview", tooltip="Toggle the preview pane"),
]
path: reactive[Path] = reactive(Path)
show_preview: reactive[bool] = reactive(False)
@dataclass
class NewPath(Message):
"""Message sent when the path is updated."""
path: Path
def __init__(self, path: Path) -> None:
super().__init__()
self.path = path
def validate_path(self, path: Path) -> Path:
"""Called to validate the path reactive."""
return path.expanduser().resolve()
def on_mount(self) -> None:
self.post_message(PathNavigator.NewPath(self.path))
def watch_show_preview(self, show_preview: bool) -> None:
self.set_class(show_preview, "-show-preview")
@on(Tree.NodeHighlighted)
def on_node_highlighted(self, event: Tree.NodeHighlighted[DirEntry]) -> None:
if event.node.data is not None:
self.query_one(InfoBar).path = event.node.data.path
self.query_one(PreviewWindow).path = event.node.data.path
@on(NewPath)
def on_new_path(self, event: NewPath) -> None:
event.stop()
if not event.path.is_dir():
self.notify(
f"'{self.path}' is not a directory",
title="Change Directory",
severity="error",
)
else:
self.path = event.path
self.query_one(DirectoryTree).path = event.path
self.query_one(PathDisplay).path = event.path
def compose(self) -> ComposeResult:
yield PathDisplay()
tree = DirectoryTree(self.path, classes="-ansi -ansi-scrollbar")
tree.guide_depth = 3
tree.show_root = False
tree.center_scroll = True
yield tree
yield PreviewWindow()
yield InfoBar()
async def action_reload(self) -> None:
tree = self.query_one(DirectoryTree)
if tree.cursor_node is None:
await tree.reload()
self.notify("👍 Reloaded directory contents", title="Directory")
else:
reload_node = tree.cursor_node.parent
assert reload_node is not None and reload_node.data is not None
path = reload_node.data.path
await tree.reload_node(reload_node)
self.notify(f"👍 Reloaded {str(path)!r}", title="Reload")
@work
async def action_goto(self) -> None:
"""Action to goto a new path.
This is a worker, because we want to wait on another screen without pausing the event loop.
Without the "@work" decorator, the UI would be frozen.
"""
new_path = await self.app.push_screen_wait(PathScreen(str(self.path)))
if new_path is not None:
self.post_message(PathNavigator.NewPath(Path(new_path)))
async def action_toggle_preview(self) -> None:
self.show_preview = not self.show_preview
self.screen.minimize()
class NavigatorApp(App):
"""The App class.
Most app's (like this one) don't contain a great deal of functionality.
They exist to provide CSS, and to create the initial UI.
"""
CSS = """
Screen {
height: auto;
max-height: 80vh;
border: none;
Footer { margin: 0 1 !important; }
&.-maximized-view {
height: 100vh;
hatch: right ansi_black;
}
.-maximized { margin: 1 2; }
}
"""
ALLOW_IN_MAXIMIZED_VIEW = ""
INLINE_PADDING = 0
def compose(self) -> ComposeResult:
yield PathNavigator(Path("~/"))
footer = Footer(classes="-ansi-colors")
footer.compact = True
yield footer
def on_mount(self) -> None:
"""Highlight the first line of the directory tree on startup."""
self.query_one(DirectoryTree).cursor_line = 0
def run():
"""A function to run the app."""
# We want ANSI color rather than truecolor.
app = NavigatorApp(ansi_color=True)
# Running inline will display the app below the prompt, rather than go fullscreen.
app.run(inline=True)
if __name__ == "__main__":
run()
| willmcgugan/terminal-tree | 183 | Python | willmcgugan | Will McGugan | ||
textual_markdown/__main__.py | Python | import sys
from .browser_app import BrowserApp
if __name__ == "__main__":
app = BrowserApp()
app.run()
| willmcgugan/textual-markdown | 504 | Python | willmcgugan | Will McGugan | ||
textual_markdown/browser_app.py | Python | from __future__ import annotations
import sys
from textual.app import App, ComposeResult
from textual.reactive import var
from textual.widget import Widget
from textual.widgets import Footer
from .widgets import MarkdownBrowser
class BrowserApp(App):
BINDINGS = [
("t", "toggle_toc", "TOC"),
("b", "back", "Back"),
("f", "forward", "Forward"),
]
path = var("")
def compose(self) -> ComposeResult:
yield Footer()
yield MarkdownBrowser()
@property
def browser(self) -> MarkdownBrowser:
return self.query_one(MarkdownBrowser)
def on_load(self) -> None:
try:
path = sys.argv[1]
except IndexError:
self.exit(message="Usage: python -m textual_markdown PATH")
else:
self.path = path
async def on_mount(self) -> None:
self.browser.focus()
if not await self.browser.go(self.path):
self.exit(message=f"Unable to load {self.path!r}")
async def load(self, path: str) -> None:
await self.browser.go(path)
def action_toggle_toc(self) -> None:
self.browser.show_toc = not self.browser.show_toc
async def action_back(self) -> None:
await self.browser.back()
async def action_forward(self) -> None:
await self.browser.forward()
if __name__ == "__main__":
app = BrowserApp()
app.run()
| willmcgugan/textual-markdown | 504 | Python | willmcgugan | Will McGugan | ||
textual_markdown/navigator.py | Python | from __future__ import annotations
from pathlib import Path
class Navigator:
"""Manages a stack of paths like a browser."""
def __init__(self) -> None:
self.stack: list[Path] = []
self.index = 0
@property
def location(self) -> Path:
"""The current location.
Returns:
A path for the current document.
"""
if not self.stack:
return Path(".")
return self.stack[self.index]
def go(self, path: str) -> Path:
"""Go to a new document.
Args:
path: Path to new document.
Returns:
Path: New location.
"""
new_path = self.location.parent / Path(path)
self.stack = self.stack[: self.index + 1]
new_path = new_path.absolute()
self.stack.append(new_path)
self.index = len(self.stack) - 1
return new_path
def back(self) -> bool:
"""Go back in the stack.
Returns:
True if the location changed, otherwise False.
"""
if self.index:
self.index -= 1
return True
return False
def forward(self) -> bool:
"""Go forward in the stack.
Returns:
True if the location changed, otherwise False.
"""
if self.index < len(self.stack) - 1:
self.index += 1
return True
return False
| willmcgugan/textual-markdown | 504 | Python | willmcgugan | Will McGugan | ||
textual_markdown/widgets.py | Python | from __future__ import annotations
from pathlib import Path
from typing import Iterable, TypeAlias
from markdown_it import MarkdownIt
from rich.style import Style
from rich.syntax import Syntax
from rich.text import Text
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.message import Message
from textual.reactive import reactive, var
from textual.widget import Widget
from textual.widgets import DataTable, Static, Tree
from .navigator import Navigator
TOC: TypeAlias = "list[tuple[int, str, str]]"
class Block(Static):
"""The base class for a Markdown Element."""
DEFAULT_CSS = """
Block {
height: auto;
}
"""
def __init__(self, *args, **kwargs) -> None:
self.blocks: list[Block] = []
super().__init__(*args, **kwargs)
def compose(self) -> ComposeResult:
yield from self.blocks
self.blocks.clear()
def set_content(self, text: Text) -> None:
self.update(text)
async def action_link(self, href: str) -> None:
await self.emit(MarkdownDocument.LinkClicked(href, sender=self))
class Header(Block):
"""Base class for a Markdown header."""
DEFAULT_CSS = """
Header {
color: $text;
}
"""
class H1(Header):
"""An H1 Markdown header."""
DEFAULT_CSS = """
H1 {
background: $accent-darken-2;
border: wide $background;
content-align: center middle;
padding: 1;
text-style: bold;
color: $text;
}
"""
class H2(Header):
"""An H2 Markdown header."""
DEFAULT_CSS = """
H2 {
background: $panel;
border: wide $background;
text-align: center;
text-style: underline;
color: $text;
padding: 1;
text-style: bold;
}
"""
class H3(Header):
"""An H3 Markdown header."""
DEFAULT_CSS = """
H3 {
background: $surface;
text-style: bold;
color: $text;
border-bottom: wide $foreground;
width: auto;
}
"""
class H4(Header):
"""An H4 Markdown header."""
DEFAULT_CSS = """
H4 {
text-style: underline;
margin: 1 0;
}
"""
class H5(Header):
"""An H5 Markdown header."""
DEFAULT_CSS = """
H5 {
text-style: bold;
color: $text;
margin: 1 0;
}
"""
class H6(Header):
"""An H6 Markdown header."""
DEFAULT_CSS = """
H6 {
text-style: bold;
color: $text-muted;
margin: 1 0;
}
"""
class Paragraph(Block):
"""A paragraph Markdown block."""
DEFAULT_CSS = """
MarkdownDocument > Paragraph {
margin: 0 0 1 0;
}
"""
class BlockQuote(Block):
"""A block quote Markdown block."""
DEFAULT_CSS = """
BlockQuote {
background: $boost;
border-left: outer $success;
margin: 1 0;
padding: 0 1;
}
BlockQuote > BlockQuote {
margin-left: 2;
margin-top: 1;
}
"""
class BulletList(Block):
"""A Bullet list Markdown block."""
DEFAULT_CSS = """
BulletList {
margin: 0;
padding: 0 0;
}
BulletList BulletList {
margin: 0;
padding-top: 0;
}
"""
class OrderedList(Block):
"""An ordered list Markdown block."""
DEFAULT_CSS = """
OrderedList {
margin: 0;
padding: 0 0;
}
OrderedList OrderedList {
margin: 0;
padding-top: 0;
}
"""
class Table(Block):
"""A Table markdown Block."""
DEFAULT_CSS = """
Table {
margin: 1 0;
}
Table > DataTable {
width: 100%;
height: auto;
}
"""
def compose(self) -> ComposeResult:
def flatten(block: Block) -> Iterable[Block]:
for block in block.blocks:
if block.blocks:
yield from flatten(block)
yield block
headers: list[Text] = []
rows: list[list[Text]] = []
for block in flatten(self):
if isinstance(block, TH):
headers.append(block.render())
elif isinstance(block, TR):
rows.append([])
elif isinstance(block, TD):
rows[-1].append(block.render())
table = DataTable(zebra_stripes=True)
table.can_focus = False
table.add_columns(*headers)
table.add_rows([row for row in rows if row])
yield table
self.blocks.clear()
class TBody(Block):
"""A table body Markdown block."""
DEFAULT_CSS = """
"""
class THead(Block):
"""A table head Markdown block."""
DEFAULT_CSS = """
"""
class TR(Block):
"""A table row Markdown block."""
DEFAULT_CSS = """
"""
class TH(Block):
"""A table header Markdown block."""
DEFAULT_CSS = """
"""
class TD(Block):
"""A table data Markdown block."""
DEFAULT_CSS = """
"""
class Bullet(Widget):
"""A bullet widget."""
DEFAULT_CSS = """
Bullet {
width: auto;
}
"""
symbol = reactive("● ")
def render(self) -> Text:
return Text(self.symbol)
class ListItem(Block):
"""A list item Markdown block."""
DEFAULT_CSS = """
ListItem {
layout: horizontal;
margin-right: 1;
height: auto;
}
ListItem > Vertical {
width: 1fr;
height: auto;
}
"""
def __init__(self, bullet: str) -> None:
self.bullet = bullet
super().__init__()
def compose(self) -> ComposeResult:
bullet = Bullet()
bullet.symbol = self.bullet
yield bullet
yield Vertical(*self.blocks)
self.blocks.clear()
class Fence(Block):
"""A fence Markdown block."""
DEFAULT_CSS = """
Fence {
margin: 1 0;
overflow: auto;
width: 100%;
height: auto;
max-height: 20;
}
Fence > * {
width: auto;
}
"""
def __init__(self, code: str, lexer: str) -> None:
self.code = code
self.lexer = lexer
super().__init__()
def compose(self) -> ComposeResult:
yield Static(
Syntax(
self.code,
lexer=self.lexer,
word_wrap=False,
indent_guides=True,
padding=(1, 2),
theme="material",
),
expand=True,
shrink=False,
)
HEADINGS = {"h1": H1, "h2": H2, "h3": H3, "h4": H4, "h5": H5, "h6": H6}
NUMERALS = " ⅠⅡⅢⅣⅤⅥ"
class MarkdownDocument(Widget):
DEFAULT_CSS = """
MarkdownDocument {
height: auto;
margin: 0 4 1 4;
layout: vertical;
}
.em {
text-style: italic;
}
.strong {
text-style: bold;
}
.s {
text-style: strike;
}
.code_inline {
text-style: bold dim;
}
"""
COMPONENT_CLASSES = {"em", "strong", "s", "code_inline"}
class TOCUpdated(Message, bubble=True):
"""The table of contents was updated."""
def __init__(self, toc: TOC, *, sender: Widget) -> None:
super().__init__(sender=sender)
self.toc = toc
class TOCSelected(Message, bubble=True):
"""An item in the TOC was selected."""
def __init__(self, block_id: str, *, sender: Widget) -> None:
super().__init__(sender=sender)
self.block_id = block_id
class LinkClicked(Message, bubble=True):
"""A link in the document was clicked."""
def __init__(self, href: str, *, sender: Widget) -> None:
super().__init__(sender=sender)
self.href = href
async def load(self, path: Path) -> bool:
"""Load a new Markdown document.
Args:
path: Path to the document.
Returns:
True on success, or False if the document could not be read.
"""
try:
markdown = path.read_text(encoding="utf-8")
except Exception:
return False
await self.query("Block").remove()
await self.update(markdown)
return True
async def update(self, markdown: str) -> None:
"""Update the document with new Markdown.
Args:
markdown: A string containing Markdown.
"""
output: list[Block] = []
stack: list[Block] = []
parser = MarkdownIt("gfm-like")
content = Text()
block_id: int = 0
toc: TOC = []
for token in parser.parse(markdown):
if token.type == "heading_open":
block_id += 1
stack.append(HEADINGS[token.tag](id=f"block{block_id}"))
elif token.type == "paragraph_open":
stack.append(Paragraph())
elif token.type == "blockquote_open":
stack.append(BlockQuote())
elif token.type == "bullet_list_open":
stack.append(BulletList())
elif token.type == "ordered_list_open":
stack.append(OrderedList())
elif token.type == "list_item_open":
stack.append(ListItem(f"{token.info}. " if token.info else "● "))
elif token.type == "table_open":
stack.append(Table())
elif token.type == "tbody_open":
stack.append(TBody())
elif token.type == "thead_open":
stack.append(THead())
elif token.type == "tr_open":
stack.append(TR())
elif token.type == "th_open":
stack.append(TH())
elif token.type == "td_open":
stack.append(TD())
elif token.type.endswith("_close"):
block = stack.pop()
if token.type == "heading_close":
heading = block.render().plain
level = int(token.tag[1:])
toc.append((level, heading, block.id))
if stack:
stack[-1].blocks.append(block)
else:
output.append(block)
elif token.type == "inline":
style_stack: list[Style] = [Style()]
content = Text()
if token.children:
for child in token.children:
if child.type == "text":
content.append(child.content, style_stack[-1])
elif child.type == "code_inline":
content.append(
child.content,
style_stack[-1]
+ self.get_component_rich_style(
"code_inline", partial=True
),
)
elif child.type == "em_open":
style_stack.append(
style_stack[-1]
+ self.get_component_rich_style("em", partial=True)
)
elif child.type == "strong_open":
style_stack.append(
style_stack[-1]
+ self.get_component_rich_style("strong", partial=True)
)
elif child.type == "s_open":
style_stack.append(
style_stack[-1]
+ self.get_component_rich_style("s", partial=True)
)
elif child.type == "link_open":
href = child.attrs.get("href", "")
action = f"link({href!r})"
style_stack.append(
style_stack[-1] + Style.from_meta({"@click": action})
)
elif child.type == "image":
href = child.attrs.get("src", "")
alt = child.attrs.get("alt", "")
action = f"link({href!r})"
style_stack.append(
style_stack[-1] + Style.from_meta({"@click": action})
)
content.append("🖼 ", style_stack[-1])
if alt:
content.append(f"({alt})", style_stack[-1])
for grandchild in child.children:
content.append(grandchild.content, style_stack[-1])
style_stack.pop()
elif child.type.endswith("_close"):
style_stack.pop()
stack[-1].set_content(content)
elif token.type == "fence":
output.append(
Fence(
token.content.rstrip(),
token.info,
)
)
await self.emit(MarkdownDocument.TOCUpdated(toc, sender=self))
await self.mount(*output)
class MarkdownTOC(Widget, can_focus_children=True):
DEFAULT_CSS = """
MarkdownTOC {
width: auto;
background: $panel;
border-right: wide $background;
}
MarkdownTOC > Tree {
padding: 1;
width: auto;
}
"""
toc: reactive[TOC | None] = reactive(None, init=False)
def compose(self) -> ComposeResult:
tree = Tree("TOC")
tree.show_root = False
tree.show_guides = True
tree.guide_depth = 4
tree.auto_expand = False
yield tree
def watch_toc(self, toc: TOC) -> None:
"""Triggered when the TOC changes."""
self.set_toc(toc)
def set_toc(self, toc: TOC) -> None:
"""Set the Table of Contents.
Args:
toc: Table of contents.
"""
tree = self.query_one(Tree)
tree.clear()
root = tree.root
for level, name, block_id in toc:
node = root
for _ in range(level - 1):
if node._children:
node = node._children[-1]
node.expand()
node.allow_expand = True
else:
node = node.add(NUMERALS[level], expand=True)
node.add_leaf(f"[dim]{NUMERALS[level]}[/] {name}", {"block_id": block_id})
async def on_tree_node_selected(self, message: Tree.NodeSelected) -> None:
node_data = message.node.data
if node_data is not None:
await self.emit(
MarkdownDocument.TOCSelected(node_data["block_id"], sender=self)
)
class MarkdownBrowser(Vertical, can_focus=True, can_focus_children=True):
DEFAULT_CSS = """
MarkdownBrowser {
height: 1fr;
scrollbar-gutter: stable;
}
MarkdownTOC {
dock:left;
}
MarkdownBrowser > MarkdownTOC {
display: none;
}
MarkdownBrowser.-show-toc > MarkdownTOC {
display: block;
}
"""
show_toc = reactive(True)
top_block = reactive("")
navigator: var[Navigator] = var(Navigator)
@property
def document(self) -> MarkdownDocument:
"""The Markdown document object."""
return self.query_one(MarkdownDocument)
async def go(self, location: str) -> bool:
"""Navigate to a new document path."""
return await self.document.load(self.navigator.go(location))
async def back(self) -> None:
"""Go back one level in the history."""
if self.navigator.back():
await self.document.load(self.navigator.location)
async def forward(self) -> None:
"""Go forward one level in the history."""
if self.navigator.forward():
await self.document.load(self.navigator.location)
async def on_markdown_document_link_clicked(
self, message: MarkdownDocument.LinkClicked
) -> None:
message.stop()
await self.go(message.href)
def watch_show_toc(self, show_toc: bool) -> None:
self.set_class(show_toc, "-show-toc")
def compose(self) -> ComposeResult:
yield MarkdownTOC()
yield MarkdownDocument()
def on_markdown_document_tocupdated(
self, message: MarkdownDocument.TOCUpdated
) -> None:
self.query_one(MarkdownTOC).toc = message.toc
message.stop()
def on_markdown_document_tocselected(
self, message: MarkdownDocument.TOCSelected
) -> None:
block_selector = f"#{message.block_id}"
block = self.query_one(block_selector, Block)
self.scroll_to_widget(block, top=True)
message.stop()
| willmcgugan/textual-markdown | 504 | Python | willmcgugan | Will McGugan | ||
redirect.go | Go | // The redirect command redirects all HTTP requests to a target URL.
package main
import (
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
target, err := url.Parse(os.Getenv("TARGET"))
if err != nil {
log.Fatalf("error parsing TARGET: %v", err)
}
if !target.IsAbs() {
log.Fatal("TARGET must be absolute URL")
}
status, _ := strconv.Atoi(os.Getenv("STATUS"))
if status == 0 {
status = http.StatusFound
}
handle := func(w http.ResponseWriter, r *http.Request) {
u := *(r.URL)
u.Scheme = ""
u.Host = ""
u.Path = strings.TrimPrefix(u.Path, "/")
dst := target.ResolveReference(&u).String()
http.Redirect(w, r, dst, status)
}
log.Print("Listening on port " + port)
log.Fatal(http.ListenAndServe(":"+port, http.HandlerFunc(handle)))
}
| willnorris/redirect | 0 | A simple redirecting web server | Go | willnorris | Will Norris | tailscale |
main.go | Go | package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/netip"
"os"
"os/exec"
"strconv"
"sync"
"github.com/bwesterb/go-zonefile"
)
var origin = flag.String("origin", "", "Origin for the zone to update")
var fZone = flag.String("fzone", "", "Forward zone to use for the server")
var rZone = flag.String("rzone", "", "Reverse zone to use for the server")
var bind = flag.String("bind", ":8080", "Bind address for the server")
var secret = flag.String("secret", "", "Secret to allow updates")
var updateMutex = &sync.Mutex{}
func main() {
flag.Parse()
s := http.Server{
Addr: *bind,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
query := r.URL.Query()
if query.Get("secret") != *secret {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Forbidden"))
return
}
name := query.Get("name")
ip := query.Get("ip")
if name == "" || ip == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Missing name or ip"))
return
}
if err := Set(name, ip); err != nil {
log.Printf("Error setting record: %v", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Error: %v", err)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}),
}
s.ListenAndServe()
}
func Set(name string, ip string) error {
updateMutex.Lock()
defer updateMutex.Unlock()
nip, err := netip.ParseAddr(ip)
if err != nil {
return fmt.Errorf("invalid IP address: %v", err)
}
rname := fmt.Sprintf("%s.%s.", name, *origin)
if nip.Is6() {
if err = UpdateRecordInFile(*fZone, name, "AAAA", ip); err != nil {
return fmt.Errorf("could not update forward AAAA record: %v", err)
}
ipb := nip.As16()
ipHex := fmt.Sprintf("%x", ipb)
rHex := ""
for i := len(ipHex); i > 0; i -= 1 {
rHex += fmt.Sprintf("%s.", ipHex[i-1:i])
}
xformIP := fmt.Sprintf("%sip6.arpa.", rHex)
if err = UpdateRecordInFile(*rZone, xformIP, "PTR", rname); err != nil {
return fmt.Errorf("could not update reverse A PTR record: %v", err)
}
} else {
if err = UpdateRecordInFile(*fZone, name, "A", ip); err != nil {
return fmt.Errorf("could not update forward A record: %v", err)
}
ipb := nip.As4()
xformIP := fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", ipb[3], ipb[2], ipb[1], ipb[0])
if err = UpdateRecordInFile(*rZone, xformIP, "PTR", rname); err != nil {
return fmt.Errorf("could not update reverse A PTR record: %v", err)
}
}
// try now to reload
cmd := exec.Command("/usr/bin/systemctl", "reload", "nsd")
err = cmd.Run()
return err
}
func UpdateRecordInFile(fName string, name, rtype, value string) error {
file, err := os.OpenFile(fName, os.O_RDWR, 0644)
if err != nil {
return err
}
defer file.Close()
currentData, err := io.ReadAll(file)
if err != nil {
return err
}
zf, perr := zonefile.Load(currentData)
if perr != nil {
return perr
}
soaOK := false
rcrdFnd := false
for _, e := range zf.Entries() {
if bytes.Equal(e.Type(), []byte(rtype)) && bytes.Equal(e.Domain(), []byte(name)) {
rcrdFnd = true
if err := e.SetValue(0, []byte(value)); err != nil {
log.Print("Could not set value:", err)
return err
}
}
if !bytes.Equal(e.Type(), []byte("SOA")) {
continue
}
vs := e.Values()
if len(vs) != 7 {
return fmt.Errorf("wrong number of parameters to SOA line")
}
serial, err := strconv.Atoi(string(vs[2]))
if err != nil {
log.Print("Could not parse serial:", err)
return err
}
e.SetValue(2, []byte(strconv.Itoa(serial+1)))
soaOK = true
}
if !soaOK {
return fmt.Errorf("could not find SOA entry")
}
if !rcrdFnd {
// add
if rtype == "PTR" {
rr, err := zonefile.ParseEntry([]byte(fmt.Sprintf("%s IN %s %s", name, rtype, value)))
if err != nil {
return err
}
zf.AddEntry(rr)
} else {
rr, err := zonefile.ParseEntry([]byte(fmt.Sprintf("%s %s %s", name, rtype, value)))
if err != nil {
return err
}
zf.AddEntry(rr)
}
}
if err := file.Truncate(0); err != nil {
return err
}
if _, err := file.Seek(0, 0); err != nil {
return err
}
if _, err := file.Write(zf.Save()); err != nil {
return err
}
if !rcrdFnd {
file.WriteString("\n")
}
return nil
}
| willscott/pdns | 0 | Minimal dynamic dns API | Go | willscott | Will | |
app.py | Python | import os
import plotly
from io import BytesIO
from pathlib import Path
from typing import List
from openai import AsyncAssistantEventHandler, AsyncOpenAI, OpenAI
from literalai.helper import utc_now
import chainlit as cl
from chainlit.config import config
from chainlit.element import Element
from openai.types.beta.threads.runs import RunStep
async_openai_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
sync_openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
assistant = sync_openai_client.beta.assistants.retrieve(
os.environ.get("OPENAI_ASSISTANT_ID")
)
config.ui.name = assistant.name
class EventHandler(AsyncAssistantEventHandler):
def __init__(self, assistant_name: str) -> None:
super().__init__()
self.current_message: cl.Message = None
self.current_step: cl.Step = None
self.current_tool_call = None
self.assistant_name = assistant_name
async def on_run_step_created(self, run_step: RunStep) -> None:
cl.user_session.set("run_step", run_step)
async def on_text_created(self, text) -> None:
self.current_message = await cl.Message(author=self.assistant_name, content="").send()
async def on_text_delta(self, delta, snapshot):
if delta.value:
await self.current_message.stream_token(delta.value)
async def on_text_done(self, text):
await self.current_message.update()
if text.annotations:
print(text.annotations)
for annotation in text.annotations:
if annotation.type == "file_path":
response = await async_openai_client.files.with_raw_response.content(annotation.file_path.file_id)
file_name = annotation.text.split("/")[-1]
try:
fig = plotly.io.from_json(response.content)
element = cl.Plotly(name=file_name, figure=fig)
await cl.Message(
content="",
elements=[element]).send()
except Exception as e:
element = cl.File(content=response.content, name=file_name)
await cl.Message(
content="",
elements=[element]).send()
# Hack to fix links
if annotation.text in self.current_message.content and element.chainlit_key:
self.current_message.content = self.current_message.content.replace(annotation.text, f"/project/file/{element.chainlit_key}?session_id={cl.context.session.id}")
await self.current_message.update()
async def on_tool_call_created(self, tool_call):
self.current_tool_call = tool_call.id
self.current_step = cl.Step(name=tool_call.type, type="tool")
self.current_step.show_input = "python"
self.current_step.start = utc_now()
await self.current_step.send()
async def on_tool_call_delta(self, delta, snapshot):
if snapshot.id != self.current_tool_call:
self.current_tool_call = snapshot.id
self.current_step = cl.Step(name=delta.type, type="tool")
self.current_step.start = utc_now()
if snapshot.type == "code_interpreter":
self.current_step.show_input = "python"
if snapshot.type == "function":
self.current_step.name = snapshot.function.name
self.current_step.language = "json"
await self.current_step.send()
if delta.type == "function":
pass
if delta.type == "code_interpreter":
if delta.code_interpreter.outputs:
for output in delta.code_interpreter.outputs:
if output.type == "logs":
self.current_step.output += output.logs
self.current_step.language = "markdown"
self.current_step.end = utc_now()
await self.current_step.update()
elif output.type == "image":
self.current_step.language = "json"
self.current_step.output = output.image.model_dump_json()
else:
if delta.code_interpreter.input:
await self.current_step.stream_token(delta.code_interpreter.input, is_input=True)
async def on_event(self, event) -> None:
if event.event == "error":
return cl.ErrorMessage(content=str(event.data.message)).send()
async def on_exception(self, exception: Exception) -> None:
return cl.ErrorMessage(content=str(exception)).send()
async def on_tool_call_done(self, tool_call):
self.current_step.end = utc_now()
await self.current_step.update()
async def on_image_file_done(self, image_file, message):
image_id = image_file.file_id
response = await async_openai_client.files.with_raw_response.content(image_id)
image_element = cl.Image(
name=image_id,
content=response.content,
display="inline",
size="large"
)
if not self.current_message.elements:
self.current_message.elements = []
self.current_message.elements.append(image_element)
await self.current_message.update()
@cl.step(type="tool")
async def speech_to_text(audio_file):
response = await async_openai_client.audio.transcriptions.create(
model="whisper-1", file=audio_file
)
return response.text
async def upload_files(files: List[Element]):
file_ids = []
for file in files:
uploaded_file = await async_openai_client.files.create(
file=Path(file.path), purpose="assistants"
)
file_ids.append(uploaded_file.id)
return file_ids
async def process_files(files: List[Element]):
# Upload files if any and get file_ids
file_ids = []
if len(files) > 0:
file_ids = await upload_files(files)
return [
{
"file_id": file_id,
"tools": [{"type": "code_interpreter"}, {"type": "file_search"}] if file.mime in ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/markdown", "application/pdf", "text/plain"] else [{"type": "code_interpreter"}],
}
for file_id, file in zip(file_ids, files)
]
@cl.set_starters
async def set_starters():
return [
cl.Starter(
label="Run Tesla stock analysis",
message="Make a data analysis on the tesla-stock-price.csv file I previously uploaded.",
icon="/public/write.svg",
),
cl.Starter(
label="Run a data analysis on my CSV",
message="Make a data analysis on the next CSV file I will upload.",
icon="/public/write.svg",
)
]
@cl.on_chat_start
async def start_chat():
# Create a Thread
thread = await async_openai_client.beta.threads.create()
# Store thread ID in user session for later use
cl.user_session.set("thread_id", thread.id)
@cl.on_stop
async def stop_chat():
current_run_step: RunStep = cl.user_session.get("run_step")
if current_run_step:
await async_openai_client.beta.threads.runs.cancel(thread_id=current_run_step.thread_id, run_id=current_run_step.run_id)
@cl.on_message
async def main(message: cl.Message):
thread_id = cl.user_session.get("thread_id")
attachments = await process_files(message.elements)
# Add a Message to the Thread
oai_message = await async_openai_client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=message.content,
attachments=attachments,
)
# Create and Stream a Run
async with async_openai_client.beta.threads.runs.stream(
thread_id=thread_id,
assistant_id=assistant.id,
event_handler=EventHandler(assistant_name=assistant.name),
) as stream:
await stream.until_done()
@cl.on_audio_chunk
async def on_audio_chunk(chunk: cl.AudioChunk):
if chunk.isStart:
buffer = BytesIO()
# This is required for whisper to recognize the file type
buffer.name = f"input_audio.{chunk.mimeType.split('/')[1]}"
# Initialize the session for a new audio stream
cl.user_session.set("audio_buffer", buffer)
cl.user_session.set("audio_mime_type", chunk.mimeType)
# Write the chunks to a buffer and transcribe the whole audio at the end
cl.user_session.get("audio_buffer").write(chunk.data)
@cl.on_audio_end
async def on_audio_end(elements: list[Element]):
# Get the audio buffer from the session
audio_buffer: BytesIO = cl.user_session.get("audio_buffer")
audio_buffer.seek(0) # Move the file pointer to the beginning
audio_file = audio_buffer.read()
audio_mime_type: str = cl.user_session.get("audio_mime_type")
input_audio_el = cl.Audio(
mime=audio_mime_type, content=audio_file, name=audio_buffer.name
)
await cl.Message(
type="user_message",
content="",
elements=[input_audio_el, *elements],
).send()
whisper_input = (audio_buffer.name, audio_file, audio_mime_type)
transcription = await speech_to_text(whisper_input)
msg = cl.Message(author="You", content=transcription, elements=elements)
await main(message=msg)
| willydouhard/data-analyst | 13 | Python | willydouhard | Willy Douhard | Chainlit | |
create_assistant.py | Python | from dotenv import load_dotenv
load_dotenv()
import os
from openai import OpenAI
openai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
instructions = """You are an assistant running data analysis on CSV files.
You will use code interpreter to run the analysis.
However, instead of rendering the charts as images, you will generate a plotly figure and turn it into json.
You will create a file for each json that I can download through annotations.
"""
tools = [
{"type": "code_interpreter"},
{"type": "file_search"}
]
file = openai_client.files.create(
file=open("tesla-stock-price.csv", "rb"),
purpose='assistants'
)
assistant = openai_client.beta.assistants.create(
model="gpt-4o",
name="Data Analysis Assistant",
instructions=instructions,
temperature=0.1,
tools=tools,
tool_resources={
"code_interpreter": {
"file_ids": [file.id]
}
}
)
print(f"Assistant created with id: {assistant.id}") | willydouhard/data-analyst | 13 | Python | willydouhard | Willy Douhard | Chainlit | |
backend/build.py | Python | """Build script gets called on poetry/pip build."""
import os
import pathlib
import shutil
import subprocess
import sys
class BuildError(Exception):
"""Custom exception for build failures"""
pass
def run_subprocess(cmd: list[str], cwd: os.PathLike) -> None:
"""
Run a subprocess, allowing natural signal propagation.
Args:
cmd: Command and arguments as a list of strings
cwd: Working directory for the subprocess
"""
print(f"-- Running: {' '.join(cmd)}")
subprocess.run(cmd, cwd=cwd, check=True)
def pnpm_install(project_root, pnpm_path):
run_subprocess([pnpm_path, "install", "--frozen-lockfile"], project_root)
def pnpm_buildui(project_root, pnpm_path):
run_subprocess([pnpm_path, "build:ui"], project_root)
def copy_directory(src, dst, description):
"""Copy directory with proper error handling"""
print(f"Copying {src} to {dst}")
try:
dst.mkdir(parents=True, exist_ok=True)
shutil.copytree(src, dst, dirs_exist_ok=True)
except KeyboardInterrupt:
print("\nInterrupt received during copy operation...")
# Clean up partial copies
if dst.exists():
shutil.rmtree(dst)
raise
except Exception as e:
raise BuildError(f"Failed to copy {src} to {dst}: {str(e)}")
def copy_frontend(project_root):
"""Copy the frontend dist directory to the backend for inclusion in the package."""
backend_frontend_dir = project_root / "backend" / "looplit" / "frontend" / "dist"
frontend_dist = project_root / "frontend" / "dist"
copy_directory(frontend_dist, backend_frontend_dir, "frontend assets")
def build():
"""Main build function with proper error handling"""
print(
"\n-- Building frontend, this might take a while!\n\n"
" If you don't need to build the frontend and just want dependencies installed, use:\n"
" `poetry install --no-root`\n"
)
try:
# Find directory containing this file
backend_dir = pathlib.Path(__file__).resolve().parent
project_root = backend_dir.parent
frontend_dir = project_root / "frontend"
pnpm = shutil.which("pnpm")
if not pnpm:
raise BuildError("pnpm not found!")
pnpm_install(frontend_dir, pnpm)
pnpm_buildui(project_root, pnpm)
copy_frontend(project_root)
except KeyboardInterrupt:
print("\nBuild interrupted by user")
sys.exit(1)
except BuildError as e:
print(f"\nBuild failed: {e!s}")
sys.exit(1)
except Exception as e:
print(f"\nUnexpected error: {e!s}")
sys.exit(1)
if __name__ == "__main__":
build()
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/__init__.py | Python | import os
from dotenv import load_dotenv
env_found = load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
from looplit.logger import logger
if env_found:
logger.info("Loaded .env file")
from looplit.decorators import stateful, tool
from looplit.state import State
__all__ = ["State", "stateful", "tool"]
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/canvas.py | Python | import json
import os
from looplit.context import get_context
from looplit.decorators import tool
from looplit.state import State
SYSTEM_PROMPT = """You are an AI assistant specialized in analyzing and debugging LLM agent outputs. Your purpose is to identify issues in agent reasoning and suggest improvements to prevent similar problems.
Input:
<agent-reasoning>
{reasoning}
</agent-reasoning>
<flagged>
{flagged}
</flagged>
Task:
Analyze the root cause of the issue described by the user given the flagged part of the reasoning.
If possible, edit the instructions of the Agent. The goal is to change the instructions (root cause) to avoid the issue in a future run.
Given those modifications, replaying the state should lead to the correct result.
"""
@tool
async def update_system_prompt(
old_str: str,
new_str: str,
) -> str:
"""Update the system message in the agent reasoning `messages` field."""
try:
context = get_context()
await context.session.send_state_edit(old_str=old_str, new_str=new_str)
except:
pass
return "System prompt update suggested!"
@tool
async def update_tool_definition(
old_str: str,
new_str: str,
) -> str:
"""Update a tool call definition in the agent reasoning `tools` field. You cannot edit tool names."""
try:
context = get_context()
await context.session.send_state_edit(old_str=old_str, new_str=new_str)
except:
pass
return "Tool definition update suggested!"
tool_defs = [
update_system_prompt.openai_schema, # type: ignore
update_tool_definition.openai_schema, # type: ignore
]
async def handle_tool_calls(state: State, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "update_system_prompt":
result = await update_system_prompt(
**json.loads(tool_call.function.arguments)
)
elif tool_call.function.name == "update_tool_definition":
result = await update_tool_definition(
**json.loads(tool_call.function.arguments)
)
else:
continue
state.messages.append(
{"role": "tool", "content": result, "tool_call_id": tool_call.id}
)
async def canvas_agent(state: State) -> State:
from openai import AsyncOpenAI
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
response = await client.chat.completions.create(
model="gpt-4o",
temperature=0,
messages=state.messages,
tools=state.tools, # type: ignore
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
await handle_tool_calls(state, tool_calls)
return await canvas_agent(state)
else:
return state
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/cli/__init__.py | Python | import asyncio
import nest_asyncio
nest_asyncio.apply()
import inspect
import os
import site
import sys
from contextlib import asynccontextmanager
from importlib import util
from typing import Any, TypedDict
import click
import socketio
import uvicorn
from fastapi import FastAPI
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from watchfiles import awatch
from looplit.context import init_context
from looplit.decorators import STATEFUL_FUNCS
from looplit.logger import logger
from looplit.session import Session
from looplit.canvas import canvas_agent, State, tool_defs, SYSTEM_PROMPT
BACKEND_ROOT = os.path.dirname(os.path.dirname(__file__))
PACKAGE_ROOT = os.path.dirname(os.path.dirname(BACKEND_ROOT))
def get_build_dir(local_target: str, packaged_target: str) -> str:
"""
Get the build directory based on the UI build strategy.
Args:
local_target (str): The local target directory.
packaged_target (str): The packaged target directory.
Returns:
str: The build directory
"""
local_build_dir = os.path.join(PACKAGE_ROOT, local_target, "dist")
packaged_build_dir = os.path.join(BACKEND_ROOT, packaged_target, "dist")
if os.path.exists(local_build_dir):
return local_build_dir
elif os.path.exists(packaged_build_dir):
return packaged_build_dir
else:
raise FileNotFoundError(f"{local_target} built UI dir not found")
build_dir = get_build_dir("frontend", "frontend")
index_html_file_path = os.path.join(build_dir, "index.html")
index_html = open(index_html_file_path, encoding="utf-8").read()
def check_file(target: str):
# Define accepted file extensions for Looplit
ACCEPTED_FILE_EXTENSIONS = ("py", "py3")
_, extension = os.path.splitext(target)
# Check file extension
if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:
if extension[1:] == "":
raise click.BadArgumentUsage(
"Looplit requires raw Python (.py) files, but the provided file has no extension."
)
else:
raise click.BadArgumentUsage(
f"Looplit requires raw Python (.py) files, not {extension}."
)
if not os.path.exists(target):
raise click.BadParameter(f"File does not exist: {target}")
def load_module(target: str, force_refresh: bool = False):
"""Load the specified module."""
# Get the target's directory
target_dir = os.path.dirname(os.path.abspath(target))
# Add the target's directory to the Python path
sys.path.insert(0, target_dir)
if force_refresh:
# Get current site packages dirs
site_package_dirs = site.getsitepackages()
# Clear the modules related to the app from sys.modules
for module_name, module in list(sys.modules.items()):
if (
hasattr(module, "__file__")
and module.__file__
and module.__file__.startswith(target_dir)
and not any(module.__file__.startswith(p) for p in site_package_dirs)
):
sys.modules.pop(module_name, None)
spec = util.spec_from_file_location(target, target)
if not spec or not spec.loader:
return
module = util.module_from_spec(spec)
if not module:
return
spec.loader.exec_module(module)
sys.modules[target] = module
# Remove the target's directory from the Python path
sys.path.pop(0)
@click.command()
@click.argument("target")
@click.option("--host", default="127.0.0.1", help="The host to run the server on.")
@click.option("--port", default=8000, help="The port to run the server on.")
def run(target, host, port):
os.environ["LOOPLIT_DEBUG"] = "true"
check_file(target)
load_module(target)
logger.info(f"Found {len(STATEFUL_FUNCS.keys())} stateful functions.")
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Context manager to handle app start and shutdown."""
watch_task = None
stop_event = asyncio.Event()
async def watch_files_for_changes():
extensions = [".py"]
async for changes in awatch(os.getcwd(), stop_event=stop_event):
for change_type, file_path in changes:
file_name = os.path.basename(file_path)
file_ext = os.path.splitext(file_name)[1]
if file_ext.lower() in extensions:
logger.info(
f"File {change_type.name}: {file_name}. Reloading..."
)
# Reload the module if the module name is specified in the config
if target:
try:
load_module(target, force_refresh=True)
except Exception as e:
logger.error(f"Error reloading module: {e}")
await sio.emit("code_change", target)
break
watch_task = asyncio.create_task(watch_files_for_changes())
try:
yield
finally:
try:
if watch_task:
stop_event.set()
watch_task.cancel()
await watch_task
except asyncio.exceptions.CancelledError:
pass
# Force exit the process to avoid potential AnyIO threads still running
os._exit(0)
def restore_existing_session(sid, session_id, emit_fn, emit_call_fn):
"""Restore a session from the sessionId provided by the client."""
if session := Session.get_by_id(session_id):
session.restore(new_socket_id=sid)
session.emit = emit_fn
session.emit_call = emit_call_fn
return True
return False
# Create FastAPI app
app = FastAPI(lifespan=lifespan)
sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
asgi_app = socketio.ASGIApp(
socketio_server=sio,
socketio_path="",
)
app.mount("/ws/socket.io", asgi_app)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount(
f"/assets",
StaticFiles(
packages=[("looplit", os.path.join(build_dir, "assets"))],
),
name="assets",
)
@app.get("/looplit.svg")
async def favicon():
return FileResponse(os.path.join(build_dir, "looplit.svg"))
@app.get("/pattern.png")
async def pattern():
return FileResponse(os.path.join(build_dir, "pattern.png"))
@app.get("/{full_path:path}")
async def serve():
"""Serve the UI files."""
response = HTMLResponse(content=index_html, status_code=200)
return response
@sio.on("connect")
async def connect(sid, environ):
# Session scoped function to emit to the client
def emit_fn(event, data):
return sio.emit(event, data, to=sid)
# Session scoped function to emit to the client and wait for a response
def emit_call_fn(event, data):
return sio.call(event, data, timeout=1000000, to=sid)
session_id = environ.get("HTTP_X_LOOPLIT_SESSION_ID")
if restore_existing_session(sid, session_id, emit_fn, emit_call_fn):
return True
Session(socket_id=sid, emit=emit_fn, emit_call=emit_call_fn)
return True
@sio.on("connection_successful")
async def connection_successful(sid):
context = init_context(sid)
if context.session.restored:
return
payload = {k: v["init_state"].model_dump() for (k, v) in STATEFUL_FUNCS.items()}
await context.session.send_stateful_funcs(payload)
@sio.on("set_interrupt")
async def set_interrupt(sid, interrupt: bool):
context = init_context(sid)
context.session.interrupt = interrupt
@sio.on("stop")
async def stop(sid):
if session := Session.get(sid):
session.call_stack = []
for task in session.current_tasks:
task.cancel()
class CallPayload(TypedDict):
func_name: str
lineage_id: str
state: dict[str, Any]
@sio.on("call_stateful_func")
async def call_stateful_func(sid, payload: CallPayload):
context = init_context(sid)
func_name = payload["func_name"]
func_def = STATEFUL_FUNCS.get(func_name)
if not func_def:
logger.warn(f"Could not find stateful func '{func_name}'.")
return
context.session.initial_lineage_id = payload["lineage_id"]
context.session.call_stack = []
func = func_def["func"]
StateClass = func_def["init_state"].__class__
input_state = StateClass(**payload["state"])
if inspect.iscoroutinefunction(func):
task = asyncio.create_task(func(input_state))
context.session.current_tasks.append(task)
await task
else:
func(input_state)
class AiCanvasRequest(TypedDict):
chat_id: str
context: str
message: str
state: str
@sio.on("call_canvas_agent")
async def call_canvas_agent(sid, payload: AiCanvasRequest):
context = init_context(sid)
chat_id = payload["chat_id"]
if not chat_id in context.session.chats:
messages = [
{"role": "system", "content": SYSTEM_PROMPT.format(reasoning=payload["state"], flagged=payload["context"])},
{"role": "user", "content": payload["message"]}
]
context.session.chats[chat_id] = State(messages=messages, tools=tool_defs)
else:
last_state = context.session.chats[chat_id]
message_content = f"""<revised-reasoning>
{payload["state"]}
</revised-reasoning>
{payload["message"]}"""
last_state.messages.append({"role": "user", "content": message_content})
try:
await context.session.canvas_agent_start()
context.session.chats[chat_id] = await canvas_agent(context.session.chats[chat_id])
await context.session.canvas_agent_end(response=context.session.chats[chat_id].messages[-1].model_dump())
except Exception as e:
logger.error("Failed to run canvas agent: " + str(e))
await context.session.canvas_agent_end(error=str(e))
# Start the server
async def start():
config = uvicorn.Config(
app,
host=host,
port=port,
)
server = uvicorn.Server(config)
await server.serve()
# Run the asyncio event loop instead of uvloop to enable re entrance
asyncio.run(start())
# uvicorn.run(app, host=host, port=port)
if __name__ == "__main__":
run()
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/context.py | Python | import asyncio
from contextvars import ContextVar
from typing import Union
from lazify import LazyProxy
from looplit.session import Session
class LooplitContextException(Exception):
def __init__(self, msg="Looplit context not found", *args, **kwargs):
super().__init__(msg, *args, **kwargs)
class LooplitContext:
loop: asyncio.AbstractEventLoop
session: Session
def __init__(
self,
session: Session,
):
self.loop = asyncio.get_running_loop()
self.session = session
context_var: ContextVar[LooplitContext] = ContextVar("looplit")
def init_context(session_or_sid: Union[Session, str]) -> LooplitContext:
if not isinstance(session_or_sid, Session):
session = Session.require(session_or_sid)
else:
session = session_or_sid
context = LooplitContext(session)
context_var.set(context)
return context
def get_context() -> LooplitContext:
try:
return context_var.get()
except LookupError as e:
raise LooplitContextException() from e
context: LooplitContext = LazyProxy(get_context, enable_cache=False)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/decorators.py | Python | import functools
import inspect
import os
from asyncio import CancelledError
from datetime import datetime
from typing import Callable, TypedDict, TypeVar, Union, get_type_hints
from uuid import uuid4
from pydantic import create_model
from pydantic.fields import FieldInfo
from looplit.context import context
from looplit.logger import logger
from looplit.state import State
from looplit.utils import FUNCS_TO_TOOL_CALLS, map_tool_calls, run_sync
class FuncDef(TypedDict):
func: Callable
init_state: State
STATEFUL_FUNCS: dict[str, FuncDef] = {}
FUNCS_TO_LINEAGE_IDS: dict[str, list[str]] = {}
def stateful(init_state: State):
def decorator(function: Callable[[State], State]) -> Callable[[State], State]:
"""
Wraps a function to accept arguments as a dictionary.
Args:
function (Callable): The function to wrap.
Returns:
Callable: The wrapped function.
"""
if not os.getenv("LOOPLIT_DEBUG"):
return function
@functools.wraps(function)
async def async_wrapper(*args):
# Get the parameter names of the function
function_params = list(inspect.signature(function).parameters.keys())
# Create a dictionary of parameter names and their corresponding values from *args
params_values = {
param_name: arg for param_name, arg in zip(function_params, args)
}
is_root_call = len(context.session.call_stack) == 0
is_context_switch = (
not is_root_call
and context.session.call_stack[-1]["func_name"] != function.__name__
)
lineage_id = (
context.session.initial_lineage_id
if is_root_call
else str(uuid4())
if is_context_switch
else context.session.call_stack[-1]["lineage_id"]
)
if is_context_switch:
if not function.__name__ in FUNCS_TO_LINEAGE_IDS:
FUNCS_TO_LINEAGE_IDS[function.__name__] = []
FUNCS_TO_LINEAGE_IDS[function.__name__].append(lineage_id)
context.session.call_stack.append(
{"func_name": function.__name__, "lineage_id": lineage_id}
)
if not is_root_call:
await context.session.send_output_state(
func_name=function.__name__,
lineage_id=lineage_id,
state=args[0].copy(deep=True),
)
if not is_root_call and context.session.interrupt:
await context.session.send_interrupt(func_name=function.__name__)
await context.session.start(func_name=function.__name__)
try:
map_tool_calls(args[0].messages, STATEFUL_FUNCS.keys())
await context.session.sync_tool_calls(
FUNCS_TO_TOOL_CALLS, FUNCS_TO_LINEAGE_IDS
)
start = datetime.utcnow()
result = function(**params_values)
if inspect.iscoroutine(result):
result = await result
end = datetime.utcnow()
if not result.metadata:
result.metadata = {}
result.metadata["func_name"] = function.__name__
result.metadata["duration_ms"] = abs(
(end - start).total_seconds() * 1000
)
result.metadata["start_time"] = start.isoformat() + "Z"
result.metadata["end_time"] = end.isoformat() + "Z"
await context.session.send_output_state(
func_name=function.__name__,
lineage_id=lineage_id,
state=result.copy(deep=True),
)
return result
except CancelledError:
pass
except Exception as e:
logger.exception(e)
await context.session.send_error(lineage_id=lineage_id, error=str(e))
finally:
if context.session.call_stack:
context.session.call_stack.pop()
await context.session.end(func_name=function.__name__)
def sync_wrapper(*args):
return run_sync(async_wrapper(*args))
wrapper = (
async_wrapper if inspect.iscoroutinefunction(function) else sync_wrapper
)
STATEFUL_FUNCS[function.__name__] = {"func": wrapper, "init_state": init_state}
return wrapper
return decorator
F = TypeVar("F", bound=Callable)
def tool(func_or_ignore_args: Union[Callable, list[str], None] = None) -> Callable:
# If called directly with the function
if callable(func_or_ignore_args):
# Execute decorator logic directly
func = func_or_ignore_args
annotations = get_type_hints(func)
return_type = annotations.pop("return", None)
params = {}
for name, param in inspect.signature(func).parameters.items():
default = param.default if param.default != inspect.Parameter.empty else ...
if isinstance(default, FieldInfo):
params[name] = (param.annotation, default) # type: ignore
else:
params[name] = (param.annotation, default) # type: ignore
ParamModel = create_model(
f"{func.__name__}_params",
**params, # type: ignore
)
openai_schema = {
"type": "function",
"function": {
"name": func.__name__,
"description": func.__doc__,
"parameters": ParamModel.model_json_schema(),
},
}
anthropic_schema = {
"name": func.__name__,
"description": func.__doc__,
"input_schema": ParamModel.model_json_schema(),
}
func.openai_schema = openai_schema # type: ignore
func.anthropic_schema = anthropic_schema # type: ignore
return func
# If called with arguments
def decorator(func: F) -> F:
ignore_args = (
func_or_ignore_args if isinstance(func_or_ignore_args, list) else []
)
annotations = get_type_hints(func)
return_type = annotations.pop("return", None)
params = {}
for name, param in inspect.signature(func).parameters.items():
if name in ignore_args:
continue
default = param.default if param.default != inspect.Parameter.empty else ...
if isinstance(default, FieldInfo):
params[name] = (param.annotation, default) # type: ignore
else:
params[name] = (param.annotation, default) # type: ignore
ParamModel = create_model(
f"{func.__name__}_params",
**params, # type: ignore
)
openai_schema = {
"type": "function",
"function": {
"name": func.__name__,
"description": func.__doc__,
"parameters": ParamModel.model_json_schema(),
},
}
anthropic_schema = {
"name": func.__name__,
"description": func.__doc__,
"input_schema": ParamModel.model_json_schema(),
}
func.openai_schema = openai_schema # type: ignore
func.anthropic_schema = anthropic_schema # type: ignore
return func
return decorator
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/logger.py | Python | import logging
import sys
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout,
format="%(asctime)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.getLogger("socketio").setLevel(logging.ERROR)
logging.getLogger("engineio").setLevel(logging.ERROR)
logger = logging.getLogger("looplit")
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/session.py | Python | import asyncio
import uuid
from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional, TypedDict
from pydantic import BaseModel
from looplit.state import State
def ensure_values_serializable(data):
"""
Recursively ensures that all values in the input (dict or list) are JSON serializable.
"""
if isinstance(data, BaseModel):
return ensure_values_serializable(data.model_dump(warnings="none"))
elif isinstance(data, dict):
return {key: ensure_values_serializable(value) for key, value in data.items()}
elif isinstance(data, list):
return [ensure_values_serializable(item) for item in data]
elif isinstance(data, (str, int, float, bool, type(None))):
return data
elif isinstance(data, (tuple, set)):
return ensure_values_serializable(
list(data)
) # Convert tuples and sets to lists
else:
return str(data) # Fallback: convert other types to string
class FuncCall(TypedDict):
func_name: str
lineage_id: str
class Session:
current_tasks: List[asyncio.Task]
call_stack: List[FuncCall]
chats: dict[str, State]
initial_lineage_id: Optional[str] = None
interrupt: bool = False
def __init__(
self,
socket_id: str,
# Function to emit to the client
emit: Callable[[str, Any], Awaitable],
# Function to emit to the client and wait for a response
emit_call: Callable[[Literal["interrupt"], Any], Awaitable],
):
self.id = str(uuid.uuid4())
self.current_tasks = []
self.call_stack = []
self.chats = {}
self.socket_id = socket_id
self.emit_call = emit_call
self.emit = emit
self.restored = False
sessions_id[self.id] = self
sessions_sid[socket_id] = self
def restore(self, new_socket_id: str):
"""Associate a new socket id to the session."""
sessions_sid.pop(self.socket_id, None)
sessions_sid[new_socket_id] = self
self.socket_id = new_socket_id
self.restored = True
def delete(self):
"""Delete the session."""
sessions_sid.pop(self.socket_id, None)
sessions_id.pop(self.id, None)
@classmethod
def get(cls, socket_id: str):
"""Get session by socket id."""
return sessions_sid.get(socket_id)
@classmethod
def get_by_id(cls, session_id: str):
"""Get session by session id."""
return sessions_id.get(session_id)
@classmethod
def require(cls, socket_id: str):
"""Throws an exception if the session is not found."""
if session := cls.get(socket_id):
return session
raise ValueError("Session not found")
async def start(self, func_name):
await self.emit("start", {"name": func_name})
async def end(self, func_name):
await self.emit("end", {"name": func_name})
async def send_error(self, lineage_id: str, error: str):
await self.emit("error", {"lineage_id": lineage_id, "error": error})
async def send_interrupt(self, func_name: str):
await self.emit_call("interrupt", {"func_name": func_name})
async def send_stateful_funcs(self, stateful_funcs: dict[str, object]):
await self.emit("stateful_funcs", stateful_funcs)
async def send_output_state(self, func_name: str, lineage_id: str, state: State):
state.messages = ensure_values_serializable(state.messages)
await self.emit(
"output_state",
{
"func_name": func_name,
"lineage_id": lineage_id,
"state": ensure_values_serializable(state),
},
)
async def sync_tool_calls(
self,
funcs_to_tool_calls: dict[str, list[str]],
funcs_to_lineage_ids: dict[str, list[str]],
):
funcs = funcs_to_tool_calls.keys()
for func in funcs:
tool_calls = funcs_to_tool_calls.get(func, [])
lineage_ids = funcs_to_lineage_ids.get(func, [])
for tc, lid in zip(tool_calls, lineage_ids):
if tc and lid:
await self.emit("map_tc_to_lid", {"tc": tc, "lid": lid})
async def canvas_agent_start(self):
await self.emit("canvas_agent_start", {})
async def canvas_agent_end(self, response=None, error=None):
await self.emit("canvas_agent_end", {"response": response, "error": error})
async def send_state_edit(self, old_str: str, new_str: str):
await self.emit("state_edit", {"old_str": old_str, "new_str": new_str})
sessions_sid: Dict[str, Session] = {}
sessions_id: Dict[str, Session] = {}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/state/__init__.py | Python | from typing import Any, List, Optional, TypedDict
from uuid import uuid4
from pydantic import BaseModel, Field
class StateMetadata(TypedDict, total=False):
start_time: Optional[str]
end_time: Optional[str]
duration_ms: Optional[float]
session_id: Optional[str]
user_id: Optional[str]
func_name: Optional[str]
class State(BaseModel):
# This field is handled by Looplit
id: str = Field(default_factory=lambda: str(uuid4()))
metadata: Optional[StateMetadata] = None
# Messages HAVE to follow the OpenAI schema for now
messages: List[Any] = Field(default_factory=list)
tools: Optional[List[Any]] = None
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/state/typing.py | Python | from typing import Dict, List, Literal, Optional, TypedDict, Union
class ChatCompletionContentPartTextParam(TypedDict, total=False):
text: str
"""The text content."""
type: Literal["text"]
"""The type of the content part."""
class ImageURL(TypedDict, total=False):
url: str
"""Either a URL of the image or the base64 encoded image data."""
detail: Literal["auto", "low", "high"]
"""Specifies the detail level of the image.
Learn more in the
[Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).
"""
class ChatCompletionContentPartImageParam(TypedDict, total=False):
image_url: ImageURL
type: Literal["image_url"]
"""The type of the content part."""
class InputAudio(TypedDict, total=False):
data: str
"""Base64 encoded audio data."""
format: Literal["wav", "mp3"]
"""The format of the encoded audio data. Currently supports "wav" and "mp3"."""
class ChatCompletionContentPartInputAudioParam(TypedDict, total=False):
input_audio: InputAudio
type: Literal["input_audio"]
"""The type of the content part. Always `input_audio`."""
ChatCompletionContentPartParam = Union[
ChatCompletionContentPartTextParam,
ChatCompletionContentPartImageParam,
ChatCompletionContentPartInputAudioParam,
]
class ChatCompletionSystemMessageParam(TypedDict, total=False):
content: Union[str, List[ChatCompletionContentPartTextParam]]
"""The contents of the system message."""
role: Literal["system"]
"""The role of the messages author, in this case `system`."""
name: str
"""An optional name for the participant.
Provides the model information to differentiate between participants of the same
role.
"""
class ChatCompletionUserMessageParam(TypedDict, total=False):
content: Union[str, List[ChatCompletionContentPartParam]]
"""The contents of the user message."""
role: Literal["user"]
"""The role of the messages author, in this case `user`."""
name: str
"""An optional name for the participant.
Provides the model information to differentiate between participants of the same
role.
"""
class Audio(TypedDict, total=False):
id: str
"""Unique identifier for a previous audio response from the model."""
class ChatCompletionContentPartRefusalParam(TypedDict, total=False):
refusal: str
"""The refusal message generated by the model."""
type: Literal["refusal"]
"""The type of the content part."""
ContentArrayOfContentPart = Union[
ChatCompletionContentPartTextParam, ChatCompletionContentPartRefusalParam
]
class FunctionCall(TypedDict, total=False):
arguments: str
"""
The arguments to call the function with, as generated by the model in JSON
format. Note that the model does not always generate valid JSON, and may
hallucinate parameters not defined by your function schema. Validate the
arguments in your code before calling your function.
"""
name: str
"""The name of the function to call."""
class Function(TypedDict, total=False):
arguments: str
"""
The arguments to call the function with, as generated by the model in JSON
format. Note that the model does not always generate valid JSON, and may
hallucinate parameters not defined by your function schema. Validate the
arguments in your code before calling your function.
"""
name: str
"""The name of the function to call."""
class ChatCompletionMessageToolCallParam(TypedDict, total=False):
id: str
"""The ID of the tool call."""
function: Function
"""The function that the model called."""
type: Literal["function"]
"""The type of the tool. Currently, only `function` is supported."""
class ChatCompletionAssistantMessageParam(TypedDict, total=False):
role: Literal["assistant"]
"""The role of the messages author, in this case `assistant`."""
audio: Optional[Audio]
"""Data about a previous audio response from the model.
[Learn more](https://platform.openai.com/docs/guides/audio).
"""
content: Union[str, List[ContentArrayOfContentPart], None]
"""The contents of the assistant message.
Required unless `tool_calls` or `function_call` is specified.
"""
function_call: Optional[FunctionCall]
"""Deprecated and replaced by `tool_calls`.
The name and arguments of a function that should be called, as generated by the
model.
"""
name: str
"""An optional name for the participant.
Provides the model information to differentiate between participants of the same
role.
"""
refusal: Optional[str]
"""The refusal message by the assistant."""
tool_calls: List[ChatCompletionMessageToolCallParam]
"""The tool calls generated by the model, such as function calls."""
class ChatCompletionToolMessageParam(TypedDict, total=False):
content: Union[str, List[ChatCompletionContentPartTextParam]]
"""The contents of the tool message."""
role: Literal["tool"]
"""The role of the messages author, in this case `tool`."""
tool_call_id: str
"""Tool call that this message is responding to."""
ChatCompletionMessageParam = Union[
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
ChatCompletionAssistantMessageParam,
ChatCompletionToolMessageParam,
]
FunctionParameters = Dict[str, object]
class FunctionDefinition(TypedDict, total=False):
name: str
"""The name of the function to be called.
Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length
of 64.
"""
description: str
"""
A description of what the function does, used by the model to choose when and
how to call the function.
"""
parameters: FunctionParameters
"""The parameters the functions accepts, described as a JSON Schema object.
See the [guide](https://platform.openai.com/docs/guides/function-calling) for
examples, and the
[JSON Schema reference](https://json-schema.org/understanding-json-schema/) for
documentation about the format.
Omitting `parameters` defines a function with an empty parameter list.
"""
strict: Optional[bool]
"""Whether to enable strict schema adherence when generating the function call.
If set to true, the model will follow the exact schema defined in the
`parameters` field. Only a subset of JSON Schema is supported when `strict` is
`true`. Learn more about Structured Outputs in the
[function calling guide](docs/guides/function-calling).
"""
class ChatCompletionToolParam(TypedDict, total=False):
function: FunctionDefinition
type: Literal["function"]
"""The type of the tool. Currently, only `function` is supported."""
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
backend/looplit/utils.py | Python | import asyncio
import sys
from typing import Any, Coroutine, TypeVar
from pydantic import BaseModel
T_Retval = TypeVar("T_Retval")
def run_sync(co: Coroutine[Any, Any, T_Retval]) -> T_Retval:
"""Run the coroutine synchronously."""
loop = asyncio.get_event_loop()
result = loop.run_until_complete(co)
return result
FUNCS_TO_TOOL_CALLS: dict[str, list[str]] = {}
def map_tool_calls(messages, stateful_func_names):
messages = [m.model_dump() if isinstance(m, BaseModel) else m for m in messages]
with_tool_calls = [
m for m in messages if m["role"] == "assistant" and m["tool_calls"]
]
last = with_tool_calls[-1] if with_tool_calls else None
if last:
for tool_call in last["tool_calls"]:
func_name = tool_call["function"]["name"].removeprefix("call_")
if func_name in stateful_func_names:
if not func_name in FUNCS_TO_TOOL_CALLS:
FUNCS_TO_TOOL_CALLS[func_name] = []
elif tool_call["id"] in FUNCS_TO_TOOL_CALLS[func_name]:
continue
FUNCS_TO_TOOL_CALLS[func_name].append(tool_call["id"])
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/anthropic_multi_agent/customer_support_agent.py | Python | import json
import litellm
import looplit as ll
@ll.tool
async def get_order_status(order_id: str) -> str:
"""Get the status for a given order id"""
return "Everything is on track!"
async def handle_tool_calls(state: ll.State, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "get_order_status":
result = await get_order_status(**json.loads(tool_call.function.arguments))
else:
continue
state.messages.append(
{"role": "tool", "content": result, "tool_call_id": tool_call.id}
)
csa_initial_state = ll.State(
messages=[
{"role": "system", "content": "Customer Support Agent system prompt."},
],
tools=[
get_order_status.openai_schema,
],
)
@ll.stateful(init_state=csa_initial_state)
async def customer_support_agent(state: ll.State) -> ll.State:
response = await litellm.acompletion(
model="anthropic/claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
await handle_tool_calls(state, tool_calls)
return await customer_support_agent(state)
else:
return state
if __name__ == "__main__":
import asyncio
csa_initial_state.messages.append({"role": "user", "content": "Status of order 2"})
final_state = asyncio.run(customer_support_agent(csa_initial_state))
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/anthropic_multi_agent/router_agent.py | Python | import json
import litellm
from customer_support_agent import csa_initial_state, customer_support_agent
import looplit as ll
@ll.tool
async def get_weather(city: str) -> str:
"""Get the weather for a given city"""
return "10 degrees celsius"
@ll.tool
async def call_customer_support_agent(query: str) -> str:
"""Redirect to the Customer Support Agent"""
csa_state = csa_initial_state.copy(deep=True)
csa_state.messages.append({"role": "user", "content": query})
result = await customer_support_agent(csa_state)
return result.messages[-1].content
async def handle_tool_calls(state: ll.State, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "get_weather":
result = await get_weather(**json.loads(tool_call.function.arguments))
elif tool_call.function.name == "call_customer_support_agent":
result = await call_customer_support_agent(
**json.loads(tool_call.function.arguments)
)
else:
continue
state.messages.append(
{"role": "tool", "content": result, "tool_call_id": tool_call.id}
)
initial_state = ll.State(
messages=[
{"role": "system", "content": "Router Agent system prompt."},
],
tools=[get_weather.openai_schema, call_customer_support_agent.openai_schema],
)
@ll.stateful(init_state=initial_state)
async def router_agent(state: ll.State) -> ll.State:
response = await litellm.acompletion(
model="anthropic/claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
await handle_tool_calls(state, tool_calls)
return await router_agent(state)
else:
return state
if __name__ == "__main__":
import asyncio
final_state = asyncio.run(router_agent(initial_state))
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/hello/hello.py | Python | import json
import os
from openai import OpenAI
from openai.types.chat import ChatCompletionMessageToolCall
import looplit as ll
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
@ll.tool
def file_search(directory: str, pattern: str):
"""Searches for files matching pattern in given directory.Returns list of matching file paths"""
return ["sales_data.csv"]
@ll.tool
def analyze_csv(filepath: str):
"""Reads CSV file and performs statistical analysis"""
return {"revenue": {"mean": 0.5, "min": 0, "max": 1, "sum": 2}}
@ll.tool
def text_search(filepath: str, keyword: str):
"""Searches a file"""
return [1, 2]
tool_map = {
"file_search": file_search,
"analyze_csv": analyze_csv,
"text_search": text_search
}
def handle_tool_calls(state: ll.State, tool_calls: list[ChatCompletionMessageToolCall]):
for tool_call in tool_calls:
if tool_call.function.name in tool_map:
result = tool_map[tool_call.function.name](**json.loads(tool_call.function.arguments))
else:
continue
state.messages.append(
{"role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id}
)
initial_state = ll.State(
messages=[
{"role": "system", "content": "You are a helpful virtual assistant focused on data analysis and file management. Be direct and informative in your responses."},
],
tools=[t.openai_schema for t in tool_map.values()],
)
@ll.stateful(init_state=initial_state)
def file_agent(state: ll.State) -> ll.State:
response = client.chat.completions.create(
model="gpt-4o",
temperature=0,
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
handle_tool_calls(state, tool_calls)
return file_agent(state)
else:
return state
if __name__ == "__main__":
final_state = file_agent(initial_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/looplit_canvas/looplit_canvas.py | Python | import looplit as ll
import json
from looplit.canvas import canvas_agent, tool_defs, SYSTEM_PROMPT
flagged = {
"role": "assistant",
"content": None,
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "update_recurring_task",
"arguments": "{\"title\": \"Team Meeting\", \"recurrence\": \"weekly\", \"day\": \"monday\", \"time\": \"10:00\"}"
}
}]
}
reasoning = ll.State(
messages=[
{"role": "system", "content": "You are a task management assistant."},
{"role": "user", "content": "Schedule our weekly team meetings"},
{"role": "assistant", "content": "I'll help you set that up. Do you have a preferred time?"},
{"role": "user", "content": "Yes, every Monday at 10am"},
flagged
],
tools=[{
"name": "create_recurring_task",
"description": "Creates a new recurring task series",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"recurrence": {"type": "string", "enum": ["daily", "weekly", "monthly"]},
"day": {"type": "string"},
"time": {"type": "string"},
"notify_participants": {"type": "boolean"}
},
"required": ["title", "recurrence", "day", "time", "notify_participants"]
}
}, {
"name": "update_recurring_task",
"description": "Updates an existing recurring task series",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"recurrence": {"type": "string"},
"day": {"type": "string"},
"time": {"type": "string"}
}
}
}]
)
init_state = ll.State(
messages=[
{"role": "system", "content": SYSTEM_PROMPT.format(
flagged=json.dumps(flagged, indent=2),
reasoning=reasoning.model_dump_json(indent=2)
)},
{"role": "user", "content": "The agent should have call 'create_recurring_task'."}
],
tools=tool_defs,
)
_canvas_agent = ll.stateful(init_state)(canvas_agent)
if __name__ == "__main__":
final_state = _canvas_agent(init_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/mistral_multi_agent/customer_support_agent.py | Python | import json
import os
from mistralai import Mistral
import looplit as ll
client = Mistral(api_key=os.getenv("MISTRAL_API_KEY"))
@ll.tool
async def get_order_status(order_id: str) -> str:
"""Get the status for a given order id"""
return "in transit"
async def handle_tool_calls(state: ll.State, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "get_order_status":
result = await get_order_status(**json.loads(tool_call.function.arguments))
else:
continue
state.messages.append(
{
"role": "tool",
"content": f"{{'result': {result}}}",
"name": tool_call.function.name,
"tool_call_id": tool_call.id,
}
)
csa_initial_state = ll.State(
messages=[
{"role": "system", "content": "Customer Support Agent system prompt."},
],
tools=[
get_order_status.openai_schema,
],
)
@ll.stateful(init_state=csa_initial_state)
async def customer_support_agent(state: ll.State) -> ll.State:
response = await client.chat.complete_async(
model="mistral-large-latest",
temperature=0,
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
await handle_tool_calls(state, tool_calls)
return await customer_support_agent(state)
else:
return state
if __name__ == "__main__":
final_state = customer_support_agent(csa_initial_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/mistral_multi_agent/router_agent.py | Python | import json
import os
from customer_support_agent import csa_initial_state, customer_support_agent
from mistralai import Mistral
import looplit as ll
client = Mistral(api_key=os.getenv("MISTRAL_API_KEY"))
@ll.tool
async def get_weather(city: str) -> str:
"""Get the weather for a given city"""
return "10 degrees celsius"
@ll.tool
async def call_customer_support_agent(query: str) -> str:
"""Redirect to the Customer Support Agent"""
csa_state = csa_initial_state.copy(deep=True)
csa_state.messages.append({"role": "user", "content": query})
result = await customer_support_agent(csa_state)
return result.messages[-1].content
async def handle_tool_calls(state: ll.State, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "get_weather":
result = await get_weather(**json.loads(tool_call.function.arguments))
elif tool_call.function.name == "call_customer_support_agent":
result = await call_customer_support_agent(
**json.loads(tool_call.function.arguments)
)
else:
continue
state.messages.append(
{
"role": "tool",
"content": f"{{'result': {result}}}",
"name": tool_call.function.name,
"tool_call_id": tool_call.id,
}
)
initial_state = ll.State(
messages=[
{"role": "system", "content": "Router Agent system prompt."},
],
tools=[get_weather.openai_schema, call_customer_support_agent.openai_schema],
)
@ll.stateful(init_state=initial_state)
async def router_agent(state: ll.State) -> ll.State:
response = await client.chat.complete_async(
model="mistral-large-latest",
temperature=0,
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
await handle_tool_calls(state, tool_calls)
return await router_agent(state)
else:
return state
if __name__ == "__main__":
final_state = router_agent(initial_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/openai_multi_agent/customer_support_agent.py | Python | import json
import os
from openai import OpenAI
from openai.types.chat import ChatCompletionMessageToolCall
import looplit as ll
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
@ll.tool
def get_order_status(order_id: str) -> str:
"""Get the status for a given order id"""
return "Everything is on track!"
def handle_tool_calls(state: ll.State, tool_calls: list[ChatCompletionMessageToolCall]):
for tool_call in tool_calls:
if tool_call.function.name == "get_order_status":
result = get_order_status(**json.loads(tool_call.function.arguments))
else:
continue
state.messages.append(
{"role": "tool", "content": result, "tool_call_id": tool_call.id}
)
csa_initial_state = ll.State(
messages=[
{"role": "system", "content": "Customer Support Agent system prompt."},
],
tools=[
get_order_status.openai_schema,
],
)
@ll.stateful(init_state=csa_initial_state)
def customer_support_agent(state: ll.State) -> ll.State:
response = client.chat.completions.create(
model="gpt-4o",
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
handle_tool_calls(state, tool_calls)
return customer_support_agent(state)
else:
return state
if __name__ == "__main__":
final_state = customer_support_agent(csa_initial_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
examples/openai_multi_agent/router_agent.py | Python | import json
import os
from customer_support_agent import csa_initial_state, customer_support_agent
from openai import OpenAI
from openai.types.chat import ChatCompletionMessageToolCall
import looplit as ll
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
@ll.tool
def get_weather(city: str) -> str:
"""Get the weather for a given city"""
return "10 degrees celsius"
@ll.tool
def call_customer_support_agent(query: str) -> str:
"""Redirect to the Customer Support Agent"""
csa_state = csa_initial_state.copy(deep=True)
csa_state.messages.append({"role": "user", "content": query})
result = customer_support_agent(csa_state)
return result.messages[-1].content
def handle_tool_calls(state: ll.State, tool_calls: list[ChatCompletionMessageToolCall]):
for tool_call in tool_calls:
if tool_call.function.name == "get_weather":
result = get_weather(**json.loads(tool_call.function.arguments))
elif tool_call.function.name == "call_customer_support_agent":
result = call_customer_support_agent(
**json.loads(tool_call.function.arguments)
)
else:
continue
state.messages.append(
{"role": "tool", "content": result, "tool_call_id": tool_call.id}
)
initial_state = ll.State(
messages=[
{"role": "system", "content": "Router Agent system prompt."},
],
tools=[get_weather.openai_schema, call_customer_support_agent.openai_schema],
)
@ll.stateful(init_state=initial_state)
def router_agent(state: ll.State) -> ll.State:
response = client.chat.completions.create(
model="gpt-4o",
messages=state.messages,
tools=state.tools,
)
state.messages.append(response.choices[0].message)
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
handle_tool_calls(state, tool_calls)
return router_agent(state)
else:
return state
if __name__ == "__main__":
final_state = router_agent(initial_state)
print(final_state)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/eslint.config.js | JavaScript | import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
"@typescript-eslint/no-explicit-any": "off"
},
},
)
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/index.html | HTML | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/looplit.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Looplit Studio</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/postcss.config.js | JavaScript | export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/App.tsx | TypeScript (TSX) | import MonacoTheme from './MonacoTheme';
import { router } from './Router';
import SocketConnection from './SocketConnection';
import CodeCanvas from './components/Canvas';
import { ThemeProvider } from './components/ThemeProvider';
import { functionsState, sessionState } from './state';
import ConnectingView from './views/connecting';
import { Toaster } from '@/components/ui/sonner';
import { RouterProvider } from 'react-router-dom';
import { useRecoilValue } from 'recoil';
function App() {
const session = useRecoilValue(sessionState);
const functions = useRecoilValue(functionsState);
const ready = session && !session.error && functions !== undefined;
return (
<ThemeProvider storageKey="vite-ui-theme">
<MonacoTheme />
<SocketConnection />
<Toaster position="top-center" />
<ConnectingView />
<CodeCanvas />
{ready ? <RouterProvider router={router} /> : null}
</ThemeProvider>
);
}
export default App;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/MonacoTheme.tsx | TypeScript (TSX) | import { useMonaco } from '@monaco-editor/react';
import { useEffect } from 'react';
export default function MonacoTheme() {
const monaco = useMonaco();
useEffect(() => {
if (!monaco) return;
const white = '#ffffff';
const black = '#000000';
monaco.editor.defineTheme('looplit-light', {
base: 'vs',
inherit: true,
rules: [],
colors: {
'editor.foreground': black,
// This is matching the light theme bg color
'editor.background': '#F5F5F5',
'editorCursor.foreground': black
}
});
monaco.editor.defineTheme('looplit-dark', {
base: 'vs-dark',
inherit: true,
rules: [],
colors: {
'editor.foreground': white,
// This is matching the dark theme bg color
'editor.background': '#0A0A0A',
'editorCursor.foreground': white
}
});
}, [monaco]);
return null;
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/Router.tsx | TypeScript (TSX) | import HomeView from './views/home';
import RootFunctionView from './views/rootFunction';
import { createBrowserRouter } from 'react-router-dom';
export const router = createBrowserRouter(
[
{
path: '/',
element: <HomeView />
},
{
path: '/fn/:name',
element: <RootFunctionView />
}
],
{}
);
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/SocketConnection.tsx | TypeScript (TSX) | import { createYamlConflict } from './components/StateMergeEditor';
import {
IError,
IInterrupt,
ILooplitState,
canvasState,
errorState,
functionsState,
interruptState,
runningState,
sessionState,
stateHistoryByLineageState,
toolCallsToLineageIdsState
} from './state';
import { useCallback, useEffect } from 'react';
import { useSetRecoilState } from 'recoil';
import io from 'socket.io-client';
import { toast } from 'sonner';
export default function SocketConnection() {
const setSession = useSetRecoilState(sessionState);
const setError = useSetRecoilState(errorState);
const setCanvas = useSetRecoilState(canvasState);
const setFunctions = useSetRecoilState(functionsState);
const setInterrupt = useSetRecoilState(interruptState);
const setRunning = useSetRecoilState(runningState);
const setStateHistoryByLineage = useSetRecoilState(
stateHistoryByLineageState
);
const setToolCallsToLineageIds = useSetRecoilState(
toolCallsToLineageIdsState
);
const connect = useCallback(() => {
const devServer = 'http://127.0.0.1:8000';
const { protocol, host } = window.location;
const uri = `${protocol}//${host}`;
const url = import.meta.env.DEV ? devServer : uri;
const socket = io(url, {
path: '/ws/socket.io',
extraHeaders: {}
});
setSession((old) => {
old?.socket?.removeAllListeners();
old?.socket?.close();
return {
socket
};
});
socket.on('connect', () => {
socket.emit('connection_successful');
setSession((s) => ({ ...s!, error: false }));
});
socket.on('connect_error', () => {
setSession((s) => ({ ...s!, error: true }));
});
socket.on('stateful_funcs', (funcs: Record<string, ILooplitState>) => {
setFunctions(funcs);
});
socket.on('start', () => {
setRunning(true);
});
socket.on('end', () => {
setRunning(false);
});
socket.on('error', (error: IError) => {
setError(error);
});
socket.on('interrupt', ({ func_name }: IInterrupt, callback) => {
setInterrupt({
func_name,
callback
});
});
socket.on(
'output_state',
({
lineage_id,
state
}: {
func_name: string;
lineage_id: string;
state: ILooplitState;
}) => {
setStateHistoryByLineage((prev) => {
return {
...prev,
[lineage_id]: prev[lineage_id]
? [...prev[lineage_id], state]
: [state]
};
});
}
);
socket.on('map_tc_to_lid', ({ tc, lid }: { tc: string; lid: string }) => {
setToolCallsToLineageIds((prev) => ({
...prev,
[tc]: lid
}));
});
socket.on('code_change', (target: string) => {
toast.info(`${target} updated!`);
});
socket.on('canvas_agent_start', () => {
setCanvas((prev) => {
if (!prev) return prev;
return {
...prev,
error: undefined,
running: true
};
});
});
socket.on(
'canvas_agent_end',
({
error,
response
}: {
error?: string;
response?: { role: string; content: string };
}) => {
setCanvas((prev) => {
if (!prev) return prev;
return {
...prev,
error,
messages: response ? [...prev.messages, response] : prev.messages,
running: false
};
});
}
);
socket.on(
'state_edit',
({ old_str, new_str }: { old_str: string; new_str: string }) => {
setCanvas((prev) => {
if (!prev) return prev;
return {
...prev,
aiState: createYamlConflict(prev.aiState, old_str, new_str)
};
});
}
);
}, [setSession]);
useEffect(() => {
connect();
}, [connect]);
return null;
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/AutoResizeTextarea.tsx | TypeScript (TSX) | import { Textarea } from '@/components/ui/textarea';
import { cn } from '@/lib/utils';
import { useCallback, useEffect, useRef } from 'react';
interface Props extends React.ComponentProps<'textarea'> {
maxHeight?: number;
onPasteImage?: (base64Url: string) => void;
}
const AutoResizeTextarea = ({
maxHeight,
onPasteImage,
className,
...props
}: Props) => {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handlePaste = useCallback(
(event: ClipboardEvent) => {
const items = event.clipboardData?.items;
if (items) {
for (let i = 0; i < items.length; i++) {
if (items[i]?.type.indexOf('image') !== -1) {
const file = items[i]?.getAsFile();
if (file) {
const reader = new FileReader();
reader.onload = () => {
const base64Url = reader.result;
onPasteImage?.(base64Url as string);
};
reader.readAsDataURL(file);
}
}
}
}
},
[onPasteImage]
);
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
// Add paste event listener
textarea.addEventListener('paste', handlePaste);
return () => {
// Remove paste event listener
textarea.removeEventListener('paste', handlePaste);
};
}, [handlePaste]);
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea || !maxHeight) return;
textarea.style.height = 'auto';
const newHeight = Math.min(textarea.scrollHeight, maxHeight);
textarea.style.height = `${newHeight}px`;
}, [props.value]);
return (
<Textarea
ref={textareaRef}
{...props}
className={cn(
'p-0 min-h-6 resize-none border-none overflow-y-auto shadow-none focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0',
className
)}
style={{ maxHeight }}
/>
);
};
export default AutoResizeTextarea;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/CanvasFloatingInput.tsx | TypeScript (TSX) | import AutoResizeTextarea from '../AutoResizeTextarea';
import { Kbd } from '../Kbd';
import { Button } from '../ui/button';
import useCurrentState from '@/hooks/useCurrentState';
import useInteraction from '@/hooks/useInteraction';
import { canvasState } from '@/state';
import FunctionViewContext from '@/views/function/context';
import { dump as yamlStringify } from 'js-yaml';
import { omit } from 'lodash';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useSetRecoilState } from 'recoil';
import { v4 as uuidv4 } from 'uuid';
export interface ICanvasInputProps {
selectedText: string;
setOpen?: (open: boolean) => void;
}
export default function CanvasFloatingInput({
selectedText,
setOpen
}: ICanvasInputProps) {
const ref = useRef<HTMLDivElement>(null);
const setCanvas = useSetRecoilState(canvasState);
const { callCanvasAgent } = useInteraction();
const currentState = useCurrentState();
const { currentLineageId } = useContext(FunctionViewContext);
const [value, setValue] = useState('');
const handleSubmit = useCallback(() => {
if (!value || !ref.current) return;
const rect = ref.current.getBoundingClientRect();
const state = yamlStringify(omit(currentState, 'id', 'metadata'), {
indent: 2,
lineWidth: -1,
noRefs: true,
flowLevel: -1,
skipInvalid: true,
noCompatMode: true,
styles: {
'!!str': 'literal' // Use literal style (|) for multiline strings
}
});
const canvasState = {
context: selectedText,
chatId: uuidv4(),
running: false,
messages: [{ role: 'user', content: value }],
aiState: state,
origState: state,
lineageId: currentLineageId,
openCoords: {
x: rect.x,
y: rect.y
}
};
setCanvas(canvasState);
callCanvasAgent({
chat_id: canvasState.chatId,
context: selectedText,
message: value,
state: canvasState.aiState
});
setOpen?.(false);
setValue('');
}, [value, currentState, currentLineageId]);
// Keyboard shortcut handler
useEffect(() => {
if (!ref.current) return;
const handleKeyDown = (event: KeyboardEvent) => {
// Check for Cmd+Enter (Mac) or Ctrl+Enter (Windows/Linux)
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
handleSubmit();
}
};
ref.current.addEventListener('keydown', handleKeyDown);
// Cleanup
return () => {
ref.current?.removeEventListener('keydown', handleKeyDown);
};
}, [handleSubmit]);
if (!selectedText) return null;
return (
<div
ref={ref}
className="p-3 rounded-md border bg-background flex flex-col gap-2"
>
<AutoResizeTextarea
maxHeight={200}
autoFocus
placeholder="Describe the issue..."
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button
disabled={!value}
size="sm"
onClick={handleSubmit}
className="ml-auto p-1 h-6"
>
Submit <Kbd>Cmd+Enter</Kbd>
</Button>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/AssistantMessage.tsx | TypeScript (TSX) | import { Logo } from '@/components/Logo';
import Markdown from '@/components/Markdown';
interface Props {
content: string;
}
export default function CanvasChatAssistantMessage({ content }: Props) {
return (
<div className="flex gap-4 items-start">
<Logo className="w-5 mt-1.5" />
<div>
<Markdown>{content}</Markdown>
</div>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/Body.tsx | TypeScript (TSX) | import CanvasChatAssistantMessage from './AssistantMessage';
import CanvasChatUserMessage from './UserMessage';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { canvasState } from '@/state';
import { AlertCircle } from 'lucide-react';
import { useRecoilValue } from 'recoil';
export default function CanvasChatBody() {
const canvas = useRecoilValue(canvasState);
if (!canvas) return null;
return (
<div className="flex flex-col gap-4 flex-grow px-6 overflow-y-auto">
{canvas?.messages.map((m, i) => {
if (m.role === 'user') {
return (
<CanvasChatUserMessage
key={canvas.chatId + i}
content={m.content}
/>
);
} else if (m.role === 'assistant') {
return (
<CanvasChatAssistantMessage
key={canvas.chatId + i}
content={m.content}
/>
);
} else {
return null;
}
})}
{canvas.error ? (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{canvas.error}</AlertDescription>
</Alert>
) : null}
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/Header.tsx | TypeScript (TSX) | import { Loader } from '@/components/Loader';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { canvasState } from '@/state';
import { SquarePen } from 'lucide-react';
import { useRecoilState } from 'recoil';
import { v4 } from 'uuid';
export default function CanvasChatHeader() {
const [canvas, setCanvas] = useRecoilState(canvasState);
const reset = () => {
setCanvas((prev) => ({
chatId: v4(),
messages: [],
origState: prev!.origState,
aiState: prev!.origState,
lineageId: prev!.lineageId,
running: false,
context: prev!.context,
openCoords: prev!.openCoords
}));
};
if (!canvas) return null;
return (
<div className="h-[60px] flex justify-between items-center px-6">
<Button
onClick={reset}
disabled={canvas.running}
variant="ghost"
size="icon"
className="-ml-2"
>
<SquarePen className="!size-5" />
</Button>
<div>
{canvas.running ? (
<Badge>
<Loader className="text-primary-foreground w-4 mr-1.5" /> Running
</Badge>
) : null}
</div>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/Input.tsx | TypeScript (TSX) | import AutoResizeTextarea from '@/components/AutoResizeTextarea';
import { Kbd } from '@/components/Kbd';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { canvasState } from '@/state';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRecoilValue } from 'recoil';
interface Props {
className?: string;
onSubmit: (message: string) => void;
}
export default function CanvasChatInput({ onSubmit, className }: Props) {
const ref = useRef<HTMLDivElement>(null);
const canvas = useRecoilValue(canvasState);
const [value, setValue] = useState('');
const disabled = canvas?.running || !value;
const submit = useCallback(() => {
if (!value) return;
onSubmit(value);
setValue('');
}, [value, disabled]);
// Keyboard shortcut handler
useEffect(() => {
if (!ref.current) return;
const handleKeyDown = (event: KeyboardEvent) => {
// Check for Cmd+Enter (Mac) or Ctrl+Enter (Windows/Linux)
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
submit();
}
};
ref.current.addEventListener('keydown', handleKeyDown);
// Cleanup
return () => {
ref.current?.removeEventListener('keydown', handleKeyDown);
};
}, [submit]);
const submitButton = useMemo(() => {
return (
<Button size="sm" disabled={disabled} onClick={submit}>
Submit <Kbd>Cmd+Enter</Kbd>
</Button>
);
}, [submit]);
if (!canvas) return null;
return (
<div
ref={ref}
className={cn(
'w-full flex flex-col gap-1 border-t border-b px-6 py-4',
className
)}
>
<AutoResizeTextarea
autoFocus
value={value}
onChange={(e) => setValue(e.target.value)}
maxHeight={200}
placeholder="Ask AI..."
/>
<div className="flex justify-end">
<div className="flex items-center gap-2">{submitButton}</div>
</div>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/UserMessage.tsx | TypeScript (TSX) | import Markdown from '@/components/Markdown';
interface Props {
content: string;
}
export default function CanvasChatUserMessage({ content }: Props) {
return (
<div className="bg-accent px-4 py-1 ml-auto max-w-[80%] rounded-lg">
<Markdown>{content}</Markdown>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Chat/index.tsx | TypeScript (TSX) | import CanvasChatBody from './Body';
import CanvasChatHeader from './Header';
import CanvasChatInput from './Input';
import useInteraction from '@/hooks/useInteraction';
import { canvasState } from '@/state';
import { useRecoilState } from 'recoil';
export default function CanvasChat() {
const { callCanvasAgent } = useInteraction();
const [canvas, setCanvas] = useRecoilState(canvasState);
const submit = (message: string) => {
if (!canvas) return;
setCanvas((prev) => {
if (!prev) return undefined;
return {
...prev,
messages: [...prev.messages, { role: 'user', content: message }]
};
});
callCanvasAgent({
chat_id: canvas.chatId,
context: canvas.context,
state: canvas.aiState,
message
});
};
return (
<div className="flex flex-col h-full">
<CanvasChatHeader />
<CanvasChatBody />
<CanvasChatInput onSubmit={submit} className="mt-auto" />
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/Header.tsx | TypeScript (TSX) | import { Button } from '../ui/button';
import { ILooplitState, canvasState, editStateState } from '@/state';
import { load as yamlParse } from 'js-yaml';
import { ArrowRight, Check, X } from 'lucide-react';
import { useCallback } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { toast } from 'sonner';
export default function CanvasHeader() {
const [canvas, setCanvas] = useRecoilState(canvasState);
const setEditState = useSetRecoilState(editStateState);
const onContinue = useCallback(() => {
if (!canvas) return;
try {
const state = yamlParse(canvas.aiState, {}) as ILooplitState;
setEditState((prev) => {
const next = { ...prev };
const prevState = next[canvas.lineageId] || {};
next[canvas.lineageId] = { ...prevState, ...state };
return next;
});
setCanvas(undefined);
toast.info('Entering edit mode.');
} catch (err) {
toast.error('Failed to parse canvas state: ' + String(err));
}
}, [canvas, setEditState]);
if (!canvas) return null;
return (
<div className="flex h-[60px] items-center justify-between">
<div className="text-xl font-medium flex items-center gap-4">
<Button
variant="ghost"
size="icon"
className="-ml-2.5"
disabled={canvas.running}
onClick={() => setCanvas(undefined)}
>
<X className="!size-6" />
</Button>
State Canvas
</div>
<div className="flex items-center gap-4">
{canvas.rejectAll && canvas.acceptAll ? (
<>
<Button
onClick={canvas.rejectAll}
disabled={canvas.running}
variant="destructive"
>
<X /> Reject All
</Button>
<Button onClick={canvas.acceptAll} disabled={canvas.running}>
<Check /> Accept All
</Button>
</>
) : (
<Button disabled={canvas.running} onClick={onContinue}>
Continue <ArrowRight />
</Button>
)}
</div>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Canvas/index.tsx | TypeScript (TSX) | import StateMergeEditor from '../StateMergeEditor';
import CanvasChat from './Chat';
import CanvasHeader from './Header';
import { canvasState } from '@/state';
import { AnimatePresence, motion } from 'motion/react';
import { useEffect } from 'react';
import { useRecoilValue } from 'recoil';
let [x, y] = [0, 0];
const CodeCanvas = () => {
const canvas = useRecoilValue(canvasState);
useEffect(() => {
if (canvas) {
x = canvas.openCoords.x;
y = canvas.openCoords.y;
}
}, [canvas]);
const isOpen = !!canvas;
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{
clipPath: `circle(0px at ${canvas.openCoords.x}px ${canvas.openCoords.y}px)`,
opacity: 0
}}
animate={{
clipPath: `circle(150% at ${canvas.openCoords.x}px ${canvas.openCoords.y}px)`,
opacity: 1
}}
exit={{
clipPath: `circle(0px at ${x}px ${y}px)`,
opacity: 0
}}
transition={{
duration: 0.5,
ease: [0.4, 0, 0.2, 1]
}}
className="h-screen w-screen bg-card fixed z-[100] flex"
>
{/* Chat Sidebar */}
<motion.div
initial={{ x: '30%', opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: '30%', opacity: 0 }}
transition={{
ease: [0.4, 0, 0.2, 1],
duration: 0.5,
delay: 0.2
}}
className="w-[20%] h-full bg-background relative z-1 flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<CanvasChat />
</motion.div>
{/* Main Code Sheet */}
<motion.div
style={{ boxShadow: '-25px 0px 41px -43px rgba(0,0,0,0.45)' }}
className="w-[80%] flex flex-col h-full bg-card border-l px-6 relative z-2"
>
<motion.div
initial={{ y: '20%', opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: '20%', opacity: 0 }}
transition={{
type: 'spring',
stiffness: 200,
damping: 30
}}
className="flex-grow flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<CanvasHeader />
<StateMergeEditor
value={canvas.aiState}
readOnly={canvas.running}
/>
</motion.div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
};
export default CodeCanvas;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/CopyButton.tsx | TypeScript (TSX) | import { Button } from '@/components/ui/button';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from '@/components/ui/tooltip';
import { Check, Copy } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
interface Props {
content: unknown;
className?: string;
}
const CopyButton = ({ content, className }: Props) => {
const [copied, setCopied] = useState(false);
const copyToClipboard = async () => {
try {
const textToCopy =
typeof content === 'object'
? JSON.stringify(content, null, 2)
: String(content);
await navigator.clipboard.writeText(textToCopy);
setCopied(true);
// Reset copied state after 2 seconds
setTimeout(() => {
setCopied(false);
}, 2000);
} catch (err) {
toast.error('Failed to copy: ' + String(err));
}
};
return (
<TooltipProvider delayDuration={100}>
<Tooltip>
<TooltipTrigger asChild>
<Button
onClick={copyToClipboard}
variant="ghost"
size="icon"
className={`text-muted-foreground ${className}`}
>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{copied ? 'Copied!' : 'Copy to clipboard'}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
};
export default CopyButton;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/EditorFormat.tsx | TypeScript (TSX) | import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import useCurrentEditState from '@/hooks/useCurrentEditState';
import { editorFormatState } from '@/state';
import { useEffect } from 'react';
import { useRecoilState } from 'recoil';
const STORAGE_KEY = 'editor-format-preference';
export function useEditorFormat() {
const [format, setFormat] = useRecoilState(editorFormatState);
// Sync to localStorage whenever format changes
useEffect(() => {
try {
localStorage.setItem(STORAGE_KEY, format);
} catch (error) {
console.error('Error writing to localStorage:', error);
}
}, [format]);
return [format, setFormat] as const;
}
export function EditorFormatSelect() {
const [format, setFormat] = useEditorFormat();
const editMode = useCurrentEditState();
return (
<Select
disabled={!!editMode}
value={format}
onValueChange={setFormat as any}
>
<SelectTrigger className="w-fit gap-1.5 h-7 px-2 border-none">
<SelectValue placeholder="Select format">{format}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="json">JSON</SelectItem>
<SelectItem value="yaml">YAML</SelectItem>
</SelectContent>
</Select>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ImageDialog.tsx | TypeScript (TSX) | import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger
} from '@/components/ui/dialog';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
Tooltip,
TooltipContent,
TooltipTrigger
} from '@/components/ui/tooltip';
import { zodResolver } from '@hookform/resolvers/zod';
import { ImagePlusIcon } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
interface Props {
onAddImage: (url: string) => void;
}
export default function ImageDialog({ onAddImage }: Props) {
const [open, setOpen] = useState(false);
const formSchema = z.object({
url: z.string().url()
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
url: ''
}
});
const onDrop = useCallback(
(acceptedFiles: File[]) => {
const file = acceptedFiles[0];
if (file) {
const reader = new FileReader();
reader.onload = () => {
const base64Url = reader.result;
onAddImage(base64Url as string);
setOpen(false);
};
reader.readAsDataURL(file);
} else {
// Handle the error case where the file is too large or not an image
toast.error(
'File is too large or not an image. Please select an image file under 10 MB.'
);
}
},
[onAddImage]
);
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: { 'image/*': [] }
});
const handlePaste = useCallback(
(event: ClipboardEvent) => {
if (!open) return;
const items = event.clipboardData?.items;
if (items) {
for (let i = 0; i < items.length; i++) {
if (items[i]?.type.indexOf('image') !== -1) {
const file = items[i]?.getAsFile();
if (file) {
const reader = new FileReader();
reader.onload = () => {
const base64Url = reader.result;
onAddImage(base64Url as string);
setOpen(false);
};
reader.readAsDataURL(file);
}
}
}
}
},
[onAddImage, open]
);
useEffect(() => {
// Add paste event listener
document.addEventListener('paste', handlePaste);
return () => {
// Remove paste event listener
document.removeEventListener('paste', handlePaste);
};
}, [handlePaste]);
function onSubmit(values: z.infer<typeof formSchema>) {
onAddImage(values.url);
setOpen(false);
}
return (
<Dialog open={open} onOpenChange={(open) => setOpen(open)}>
<DialogTrigger asChild>
<Tooltip>
<TooltipTrigger asChild>
<Button
className="text-muted-foreground"
onClick={() => setOpen(true)}
variant="ghost"
size="icon"
>
<ImagePlusIcon size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Add Image</p>
</TooltipContent>
</Tooltip>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Image</DialogTitle>
<DialogDescription>
Add an image to the message by uploading a file or providing a URL.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div
{...getRootProps()}
className="dropzonerelative flex h-40 w-full items-center justify-center rounded-lg border-2 border-dashed border-gray-200 p-6 dark:border-gray-800"
>
<input {...getInputProps()} />
<div className="flex flex-col items-center gap-1 text-center">
<span className="text-sm font-medium">
Drop files here to upload
</span>
<span className="text-xs text-gray-500 dark:text-gray-400">
or click to browse
</span>
</div>
</div>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-slate-500">
Or add image URL
</span>
</div>
</div>
<Form {...form}>
<form
id="imageForm"
onSubmit={form.handleSubmit(onSubmit)}
className="grid gap-2"
>
<FormField
control={form.control}
name="url"
render={(field) => (
<FormItem>
<FormLabel />
<FormControl>
<Input
placeholder="https://example.com/image.jpg"
{...field}
{...form.register('url')}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</div>
<DialogFooter>
<Button type="submit" form="imageForm">
Import Image
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ImageEditor.tsx | TypeScript (TSX) | import { ZoomableImage } from './ZoomableImage';
import { Button } from '@/components/ui/button';
import { Trash } from 'lucide-react';
interface Props {
url: string;
disabled?: boolean;
onDelete?: () => void;
readOnly?: boolean;
}
export default function ImageEditor({
url,
disabled,
onDelete,
readOnly = false
}: Props) {
return (
<div
className={`group relative flex h-[168px] w-[300px] overflow-hidden rounded-md border`}
>
{!readOnly && (
<Button
disabled={disabled}
onClick={onDelete}
variant="outline"
size="icon"
className="z-1 invisible absolute right-2 top-2 h-6 w-6 group-hover:visible"
>
<Trash size={14} />
</Button>
)}
<ZoomableImage alt="Image" className="w-full object-cover" src={url} />
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/InlineText.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
interface Props {
children: React.ReactNode;
className?: string;
}
export default function InlineText({ children, className }: Props) {
return (
<code
className={cn(
'relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold',
className
)}
>
{children}
</code>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/JsonEditor.tsx | TypeScript (TSX) | import { useMonacoTheme } from './ThemeProvider';
import Editor from '@monaco-editor/react';
import type { editor } from 'monaco-editor';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
interface Props {
value: Record<string, unknown>;
height?: string;
fitContent?: boolean;
className?: string;
onChange?: (value: Record<string, unknown>) => void;
}
export const defaultOptions = {
fontFamily: 'inter, monospace, sans-serif',
fontSize: 14,
lineHeight: 24,
renderWhitespace: 'boundary' as const,
unicodeHighlight: {
ambiguousCharacters: false,
invisibleCharacters: false
},
wordWrap: 'on' as const,
minimap: { enabled: false },
quickSuggestions: false,
suggestOnTriggerCharacters: false,
contextmenu: false,
renderLineHighlight: 'none' as const,
scrollBeyondLastLine: false,
overviewRulerLanes: 0,
lineNumbersMinChars: 0,
glyphMargin: false,
lineNumbers: 'off' as const,
folding: true,
scrollbar: {
useShadows: false,
alwaysConsumeMouseWheel: false
}
};
export default function JsonEditor({
value,
className,
height,
fitContent,
onChange
}: Props) {
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const preventNextOnChange = useRef(false);
const theme = useMonacoTheme();
const [error, setError] = useState<string>();
useEffect(() => {
if (error) {
const id = toast.error(error);
return () => {
toast.dismiss(id);
};
}
}, [error]);
function adjustEditorHeightToContent() {
const editor = editorRef.current;
if (!editor) {
return;
}
const editorElement = editor.getDomNode(); // Get the editor DOM node
if (!editorElement) {
return;
}
// Use the scrollHeight to get the total content height including word-wrapped lines
const contentHeight = editor.getContentHeight();
const editorHeight = contentHeight + 6;
const maxHeight = 500;
editorElement.style.height = `${Math.min(maxHeight, editorHeight)}px`; // Adjust editor container height
editor.layout(); // Update editor layout
}
const jsonString = JSON.stringify(value, undefined, 2);
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
const forceRender = editor.getValue() !== jsonString;
if (forceRender) {
const position = editor.getPosition();
preventNextOnChange.current = true;
editor.setValue(jsonString);
if (position) editor.setPosition(position);
}
}, [jsonString]);
return (
<div className={className}>
<Editor
loading={null}
width="100%"
height={height}
theme={theme}
options={{
...defaultOptions,
readOnly: !onChange
}}
defaultValue={jsonString}
onChange={(value) => {
if (preventNextOnChange.current) {
preventNextOnChange.current = false;
return;
}
try {
setError(undefined);
const jsonValue = JSON.parse(value || '');
onChange?.(jsonValue);
} catch (err) {
setError(String(err));
}
}}
language="json"
onMount={(editor) => {
editorRef.current = editor;
if (!fitContent) return;
editor.onDidContentSizeChange(() => {
adjustEditorHeightToContent();
});
editor.layout();
adjustEditorHeightToContent();
}}
/>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Kbd.tsx | TypeScript (TSX) | import { usePlatform } from '@/hooks/usePlatform';
import { cn } from '@/lib/utils';
import { Slot } from '@radix-ui/react-slot';
import { Command, CornerDownLeft } from 'lucide-react';
import { ForwardedRef, forwardRef } from 'react';
export type KbdProps = React.HTMLAttributes<HTMLElement> & {
asChild?: boolean;
};
const Kbd = forwardRef(
(
{ asChild, children, className, ...kbdProps }: KbdProps,
forwardedRef: ForwardedRef<HTMLElement>
) => {
const { isMac } = usePlatform();
const Comp = asChild ? Slot : 'kbd';
const formatChildren = (child: React.ReactNode): React.ReactNode => {
if (typeof child === 'string') {
const lowerChild = child.toLowerCase();
if (lowerChild === 'enter') {
return <CornerDownLeft className="!size-3" />;
}
if (lowerChild === 'cmd+enter' || lowerChild === 'ctrl+enter') {
const cmdKey = isMac ? <Command className="!size-3" /> : 'Ctrl';
return (
<>
{cmdKey}
<CornerDownLeft className="!size-3 ml-0.5" />
</>
);
}
return isMac
? child.replace(/cmd/i, '⌘')
: child.replace(/cmd/i, 'Ctrl');
}
return child;
};
const formattedChildren = Array.isArray(children)
? children.map(formatChildren)
: formatChildren(children);
return (
<Comp
{...kbdProps}
className={cn(
'inline-flex select-none items-center justify-center whitespace-nowrap rounded-[4px] bg-muted px-1 py-[1px] font-mono text-xs tracking-tight text-muted-foreground shadow',
className
)}
ref={forwardedRef}
>
{formattedChildren}
</Comp>
);
}
);
Kbd.displayName = 'Kbd';
export { Kbd };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Loader.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import { LoaderIcon } from 'lucide-react';
interface LoaderProps {
className?: string;
}
const Loader = ({ className }: LoaderProps): JSX.Element => {
return (
<LoaderIcon
className={cn('h-4 w-4 animate-spin text-primary', className)}
/>
);
};
export { Loader };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Logo.tsx | TypeScript (TSX) | import { useTheme } from './ThemeProvider';
import LogoDark from '@/assets/logo_dark.svg';
import LogoLight from '@/assets/logo_light.svg';
interface Props {
className: string;
}
export const Logo = ({ className }: Props) => {
const { theme } = useTheme();
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
const currentTheme = theme === 'system' ? systemTheme : theme;
return (
<img
src={currentTheme === 'dark' ? LogoDark : LogoLight}
alt="logo"
className={className}
/>
);
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Markdown.tsx | TypeScript (TSX) | import { useMonacoTheme } from './ThemeProvider';
import { AspectRatio } from './ui/aspect-ratio';
import { Card } from './ui/card';
import { Separator } from './ui/separator';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
} from './ui/table';
import Editor from '@monaco-editor/react';
import { omit } from 'lodash';
import type { editor } from 'monaco-editor';
import { useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
const MarkdownCodeEditor = ({
language,
code
}: {
language: string;
code: string;
}) => {
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const [height, setHeight] = useState<number>();
const theme = useMonacoTheme();
function adjustEditorHeightToContent() {
const editor = editorRef.current;
if (!editor) {
return;
}
const editorElement = editor.getDomNode(); // Get the editor DOM node
if (!editorElement) {
return;
}
// Use the scrollHeight to get the total content height including word-wrapped lines
const contentHeight = editor.getContentHeight();
const editorHeight = contentHeight;
setHeight(editorHeight);
}
return (
<Editor
height={height}
defaultValue={code}
language={language}
theme={theme}
options={{
fontFamily: 'inter, monospace, sans-serif',
renderLineHighlight: 'none',
fontSize: 12,
lineNumbers: 'off',
minimap: { enabled: false },
readOnly: true,
lineNumbersMinChars: 0,
folding: false,
lineDecorationsWidth: 0,
overviewRulerLanes: 0,
scrollbar: {
useShadows: false,
alwaysConsumeMouseWheel: false
}
}}
onMount={(editor) => {
editorRef.current = editor;
adjustEditorHeightToContent();
}}
/>
);
};
const Markdown = ({ children }: { children: string }) => {
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code(props) {
return (
<code
{...omit(props, ['node'])}
className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold"
/>
);
},
pre({ children, ...props }: any) {
const codeChildren = props.node?.children?.[0];
const className = codeChildren?.properties?.className?.[0];
const match = /language-(\w+)/.exec(className || '');
const code = codeChildren?.children?.[0]?.value;
const showSyntaxHighlighter = match && code;
if (showSyntaxHighlighter) {
return <MarkdownCodeEditor code={code} language={match[1] || ''} />;
}
return (
<div className="min-h-10 overflow-x-auto rounded-md bg-accent p-1">
<code
{...props}
style={{
whiteSpace: 'pre-wrap'
}}
>
{children}
</code>
</div>
);
},
a({ children, ...props }) {
return (
<a {...props} className="text-primary" target="_blank">
{children}
</a>
);
},
img: (image: any) => {
return (
<AspectRatio
ratio={16 / 9}
className="max-h-[200px] max-w-[355px] bg-muted"
>
<img
src={image.src}
alt={image.alt}
className="h-full w-full rounded-md object-cover"
/>
</AspectRatio>
);
},
blockquote(props) {
return (
<blockquote
{...omit(props, ['node'])}
className="mt-6 border-l-2 pl-6 italic"
/>
);
},
em(props) {
return <span {...omit(props, ['node'])} className="italic" />;
},
strong(props) {
return <span {...omit(props, ['node'])} className="font-bold" />;
},
hr() {
return <Separator />;
},
ul(props) {
return (
<ul
{...omit(props, ['node'])}
className="my-3 ml-3 list-disc pl-2 [&>li]:mt-1"
/>
);
},
ol(props) {
return (
<ol
{...omit(props, ['node'])}
className="my-3 ml-3 list-decimal [&>li]:mt-1"
/>
);
},
h1(props) {
return (
<h1
{...omit(props, ['node'])}
className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl"
/>
);
},
h2(props) {
return (
<h2
{...omit(props, ['node'])}
className="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0"
/>
);
},
h3(props) {
return (
<h3
{...omit(props, ['node'])}
className="scroll-m-20 text-2xl font-semibold tracking-tight"
/>
);
},
h4(props) {
return (
<h4
{...omit(props, ['node'])}
className="scroll-m-20 text-xl font-semibold tracking-tight"
/>
);
},
p(props) {
return (
<p
{...omit(props, ['node'])}
className="leading-7 [&:not(:first-child)]:mt-6"
/>
);
},
table({ children, ...props }) {
return (
<Card className="[&:not(:first-child)]:mt-2 [&:not(:last-child)]:mb-2">
<Table {...props}>{children}</Table>
</Card>
);
},
thead({ children, ...props }) {
return <TableHeader {...props}>{children}</TableHeader>;
},
tr({ children, ...props }) {
return <TableRow {...props}>{children}</TableRow>;
},
th({ children, ...props }) {
return <TableHead {...props}>{children}</TableHead>;
},
td({ children, ...props }) {
return <TableCell {...props}>{children}</TableCell>;
},
tbody({ children, ...props }) {
return <TableBody {...props}>{children}</TableBody>;
}
}}
>
{children}
</ReactMarkdown>
);
};
export default Markdown;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Message/Content.tsx | TypeScript (TSX) | import type { IMessageContent } from '.';
import AutoResizeTextarea from '../AutoResizeTextarea';
import ImageEditor from '../ImageEditor';
import { Button } from '../ui/button';
import { Trash2 } from 'lucide-react';
import { useCallback } from 'react';
interface Props {
content: IMessageContent;
onChange?: (content: IMessageContent) => void;
autoFocus?: boolean;
maxHeight?: number;
}
export function MessageContent({
content,
onChange,
autoFocus,
maxHeight
}: Props) {
const placeholder = autoFocus ? 'Type your message here.' : 'Empty';
const addImage = useCallback(
(url: string) => {
const toAdd = { type: 'image_url' as const, image_url: { url } };
if (typeof content === 'string') {
onChange?.([
{
type: 'text',
text: content as string
},
toAdd
]);
} else {
onChange?.([...content, toAdd]);
}
},
[content, onChange]
);
if (typeof content === 'string') {
return (
<AutoResizeTextarea
maxHeight={maxHeight}
value={content}
autoFocus={autoFocus}
onPasteImage={addImage}
disabled={!onChange}
onChange={(e) => onChange?.(e.target.value)}
placeholder={placeholder}
/>
);
} else {
return (
<div className="flex flex-col gap-2">
{content.map((c, i) => {
if (c.type === 'text') {
return (
<div className="flex" key={i}>
<AutoResizeTextarea
key={i}
maxHeight={maxHeight}
disabled={!onChange}
value={c.text}
onPasteImage={addImage}
onChange={(e) =>
onChange?.(
content.map((c, changedIndex) => {
if (i !== changedIndex) {
return c;
} else {
return { ...c, text: e.target.value };
}
})
)
}
placeholder={placeholder}
/>
{i !== 0 ? (
<Button
onClick={() =>
onChange?.(
content.filter((_, deletedIndex) => i !== deletedIndex)
)
}
className="-mt-2"
variant="ghost"
size="icon"
>
<Trash2 />
</Button>
) : null}
</div>
);
} else if (c.type === 'image_url') {
const url =
typeof c.image_url === 'string' ? c.image_url : c.image_url.url;
return (
<ImageEditor
key={i}
url={url}
onDelete={() =>
onChange?.(
content.filter((_, deletedIndex) => i !== deletedIndex)
)
}
/>
);
}
})}
</div>
);
}
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Message/RoleSelect.tsx | TypeScript (TSX) | import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
const generationMessageRoleValues = ['system', 'assistant', 'user', 'tool'];
interface Props {
value: string;
disabled?: boolean;
onValueChange: (v: string) => void;
}
export default function RoleSelect({ value, disabled, onValueChange }: Props) {
const items = generationMessageRoleValues.map((r) => (
<SelectItem key={r} value={r}>
{r}
</SelectItem>
));
return (
<Select onValueChange={onValueChange} value={value} disabled={disabled}>
<SelectTrigger className="gap-1 w-fit shadow-none border-none bg-transparent px-0 font-medium focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0">
<SelectValue placeholder="Role" />
</SelectTrigger>
<SelectContent>{items}</SelectContent>
</Select>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/Message/index.tsx | TypeScript (TSX) | import ImageDialog from '../ImageDialog';
import { Button } from '../ui/button';
import { MessageContent } from './Content';
import RoleSelect from './RoleSelect';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from '@/components/ui/tooltip';
import { ListPlusIcon, Trash2 } from 'lucide-react';
import { useCallback } from 'react';
export interface ITextContent {
type: 'text';
text: string;
}
export interface IImageUrlContent {
type: 'image_url';
image_url: string | { url: string };
}
export interface IToolCall {
id: string;
index?: number;
type: 'function';
function: {
name: string;
arguments: Record<string, any> | string;
};
}
export type IMessageContent = string | (ITextContent | IImageUrlContent)[];
export interface IMessage {
content?: IMessageContent;
role: string;
name?: string;
tool_calls?: IToolCall[];
tool_call_id?: string;
}
interface Props {
message: IMessage;
autoFocus?: boolean;
onChange?: (message: IMessage) => void;
onDelete?: () => void;
maxHeight?: number;
children?: React.ReactNode;
}
export default function Message({
message,
onChange,
onDelete,
autoFocus,
maxHeight,
children
}: Props) {
const addText = useCallback(() => {
const toAdd = { type: 'text' as const, text: '' };
if (typeof message.content === 'string') {
onChange?.({
...message,
content: [
{
type: 'text',
text: message.content as string
},
toAdd
]
});
} else {
onChange?.({
...message,
content: [...(message.content || []), toAdd]
});
}
}, [message.content, onChange]);
const addImage = useCallback(
(url: string) => {
const toAdd = { type: 'image_url' as const, image_url: { url } };
if (typeof message.content === 'string') {
onChange?.({
...message,
content: [
{
type: 'text',
text: message.content as string
},
toAdd
]
});
} else {
onChange?.({
...message,
content: [...(message.content || []), toAdd]
});
}
},
[message, onChange]
);
return (
<div className="flex flex-col gap-1">
<div className="flex justify-between items-center">
<div className="flex items-center gap-1">
<RoleSelect
disabled={!onChange}
value={message.role}
onValueChange={(v) => {
onChange?.({
...message,
role: v
});
}}
/>
{message.tool_call_id ? (
<span className="italic font-normal text-muted-foreground">
{message.tool_call_id}
</span>
) : null}
</div>
{onChange ? (
<TooltipProvider delayDuration={100}>
<div className="flex -mr-2">
<Tooltip>
<TooltipTrigger asChild>
<Button
className="text-muted-foreground"
onClick={addText}
variant="ghost"
size="icon"
>
<ListPlusIcon size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Add Text Block</p>
</TooltipContent>
</Tooltip>
<ImageDialog onAddImage={addImage} />
{onDelete ? (
<Button
className="text-muted-foreground"
onClick={onDelete}
variant="ghost"
size="icon"
>
<Trash2 size={14} />
</Button>
) : null}
</div>
</TooltipProvider>
) : null}
</div>
<MessageContent
autoFocus={autoFocus}
maxHeight={maxHeight}
content={message.content || ''}
onChange={
onChange ? (content) => onChange({ ...message, content }) : undefined
}
/>
{children}
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/MessageComposer/index.tsx | TypeScript (TSX) | import type { IMessage } from '../Message';
import Message from '../Message';
import { Kbd } from '@/components/Kbd';
import { Button } from '@/components/ui/button';
import useCurrentEditState from '@/hooks/useCurrentEditState';
import useCurrentState from '@/hooks/useCurrentState';
import useInteraction from '@/hooks/useInteraction';
import {
ILooplitState,
runningState,
stateHistoryByLineageState
} from '@/state';
import FunctionViewContext from '@/views/function/context';
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState
} from 'react';
import { useRecoilValue, useSetRecoilState } from 'recoil';
import { v4 as uuidv4 } from 'uuid';
export default function MessageComposer() {
const ref = useRef<HTMLDivElement>(null);
const editState = useCurrentEditState();
const running = useRecoilValue(runningState);
const [composer, setComposer] = useState<IMessage>({
role: 'user',
content: ''
});
const currentState = useCurrentState();
const { name, currentLineageId, currentStateIndex, setCurrentStateIndex } =
useContext(FunctionViewContext);
const setStateHistoryByLineage = useSetRecoilState(
stateHistoryByLineageState
);
const { callStatefulFunction } = useInteraction();
const disabled = running || !composer.content || !!editState;
const addMessage = useCallback(
(send?: boolean) => {
if (disabled) return;
const newState: ILooplitState = {
...currentState,
id: uuidv4(),
tools: currentState?.tools ? [...currentState.tools] : [],
messages: currentState?.messages
? [...currentState.messages, composer]
: [composer]
};
// Update state history
setStateHistoryByLineage((prev) => {
const currentLineage = [...(prev[currentLineageId] || [])];
// Remove any states after the current index
currentLineage.splice(currentStateIndex + 1);
// Add the new state
currentLineage.push(newState);
return {
...prev,
[currentLineageId]: currentLineage
};
});
// Update current state index to point to the new state
setCurrentStateIndex?.((prev) => prev.currentStateIndex + 1);
setComposer((prev) => ({
role: prev.role,
content: ''
}));
if (send) {
callStatefulFunction({
func_name: name,
lineage_id: currentLineageId,
state: newState
});
}
},
[
disabled,
composer,
currentLineageId,
currentState,
currentStateIndex,
name,
setStateHistoryByLineage,
setCurrentStateIndex,
callStatefulFunction
]
);
// Keyboard shortcut handler
useEffect(() => {
if (!ref.current) return;
const handleKeyDown = (event: KeyboardEvent) => {
// Check for Cmd+Enter (Mac) or Ctrl+Enter (Windows/Linux)
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
addMessage(true);
}
};
ref.current.addEventListener('keydown', handleKeyDown);
// Cleanup
return () => {
ref.current?.removeEventListener('keydown', handleKeyDown);
};
}, [addMessage]);
const addMessageButton = (
<Button
data-testid="add-message-tabs"
onClick={() => addMessage()}
size="sm"
variant="outline"
disabled={disabled}
>
Add
</Button>
);
const submitButton = useMemo(() => {
return (
<Button size="sm" disabled={disabled} onClick={() => addMessage(true)}>
Submit <Kbd>Cmd+Enter</Kbd>
</Button>
);
}, [addMessage]);
return (
<div ref={ref} className="flex flex-col gap-1 border-t border-b px-4 py-2">
<Message
autoFocus
message={composer}
onChange={setComposer}
maxHeight={200}
>
<div className="flex justify-end">
<div className="flex items-center gap-2">
{addMessageButton}
{submitButton}
</div>
</div>
</Message>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/StateMergeEditor.tsx | TypeScript (TSX) | import { useMonacoTheme } from './ThemeProvider';
import { cn } from '@/lib/utils';
import { canvasState } from '@/state';
import Editor from '@monaco-editor/react';
import { Position, Range, editor } from 'monaco-editor';
import { useEffect, useMemo, useRef } from 'react';
import { useSetRecoilState } from 'recoil';
const ABOVE = editor.ContentWidgetPositionPreference.ABOVE;
export const START = '<<<<<<<';
export const MIDDLE = '=======';
export const END = '>>>>>>>';
interface Props {
value: string;
readOnly?: boolean;
}
export function createYamlConflict(
yaml: string,
oldStr: string,
newStr: string
) {
const startIndex = yaml.indexOf(oldStr);
if (startIndex === -1) return yaml;
// Find start of the line containing oldStr
let lineStart = startIndex;
while (lineStart > 0 && yaml[lineStart - 1] !== '\n') {
lineStart--;
}
const endIndex = startIndex + oldStr.length;
const before = yaml.substring(0, lineStart);
const after = yaml.substring(endIndex);
const indentation = yaml.substring(lineStart, startIndex);
const conflict = `${before}<<<<<<< Current
${indentation}${oldStr}
=======
${indentation}${newStr}
>>>>>>> AI suggestion${after}`;
return conflict;
}
// Add blank lines before conflicts
const addBlankLines = (text: string) => {
const lines = text.split('\n');
const newLines = [];
for (let i = 0; i < lines.length; i++) {
// If this line starts a conflict and it's not the first line
// and the previous line isn't already blank
if (lines[i].startsWith(START) && i > 0 && lines[i - 1].trim() !== '') {
newLines.push(''); // Add blank line
}
newLines.push(lines[i]);
}
return newLines.join('\n');
};
interface IConflict {
marker: 'start' | 'middle';
current: string[];
incoming: string[];
startLine: number;
headerLine: number;
separatorLine: number;
footerLine: number;
endLine: number;
hasBlankLineBefore: boolean;
}
export const parseConflicts = (text: string): IConflict[] => {
const lines = text.split('\n');
const conflicts: IConflict[] = [];
let currentConflict: IConflict | null = null;
lines.forEach((line, index) => {
if (line.startsWith(START)) {
// @ts-expect-error partial
currentConflict = {
marker: 'start',
current: [],
incoming: [],
startLine: index,
headerLine: index,
hasBlankLineBefore: index > 0 && lines[index - 1].trim() === ''
};
} else if (line.startsWith(MIDDLE) && currentConflict) {
currentConflict.marker = 'middle';
currentConflict.separatorLine = index;
} else if (line.startsWith(END) && currentConflict) {
currentConflict.footerLine = index;
currentConflict.endLine = index;
conflicts.push({ ...currentConflict });
currentConflict = null;
} else if (currentConflict) {
if (currentConflict.marker === 'start') {
currentConflict.current.push(line);
} else if (currentConflict.marker === 'middle') {
currentConflict.incoming.push(line);
}
}
});
return conflicts;
};
const StateMergeEditor = ({ value, readOnly }: Props) => {
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const decorationsRef = useRef<editor.IModelDeltaDecoration[]>(null);
const widgetsRef = useRef<editor.IContentWidget[]>([]);
const setCanvas = useSetRecoilState(canvasState);
const theme = useMonacoTheme();
const headerBg = theme === 'looplit-dark' ? 'bg-sky-800' : 'bg-sky-200';
const currentBg = theme === 'looplit-dark' ? 'bg-sky-950' : 'bg-sky-300';
const incomingBg = theme === 'looplit-dark' ? 'bg-teal-950' : 'bg-teal-300';
const footerBg = theme === 'looplit-dark' ? 'bg-teal-800' : 'bg-teal-200';
const buttonHover = 'hover:text-blue-400';
const conflictedText = useMemo(() => addBlankLines(value), [value]);
const clearAllWidgets = (editor: editor.IStandaloneCodeEditor) => {
// Remove all existing content widgets
if (widgetsRef.current.length > 0) {
widgetsRef.current.forEach((widget) => {
editor.removeContentWidget(widget);
});
widgetsRef.current = [];
}
};
const addConflictDecorations = (
editor: editor.IStandaloneCodeEditor,
conflicts: IConflict[]
) => {
// Clear existing decorations and widgets
if (decorationsRef.current) {
// @ts-expect-error monaco
decorationsRef.current.clear();
}
clearAllWidgets(editor);
const decorations: editor.IModelDeltaDecoration[] = [];
conflicts.forEach((conflict, idx) => {
decorations.push({
range: new Range(
conflict.headerLine + 1,
1,
conflict.headerLine + 1,
1
),
options: {
isWholeLine: true,
className: `conflict-header ${headerBg}`,
linesDecorationsClassName: 'conflict-header-margin'
}
});
decorations.push({
range: new Range(conflict.headerLine + 2, 1, conflict.separatorLine, 1),
options: {
isWholeLine: true,
className: `current-change ${currentBg}`,
linesDecorationsClassName: 'current-change-margin'
}
});
decorations.push({
range: new Range(conflict.separatorLine + 2, 1, conflict.footerLine, 1),
options: {
isWholeLine: true,
className: `incoming-change ${incomingBg}`,
linesDecorationsClassName: 'incoming-change-margin'
}
});
decorations.push({
range: new Range(
conflict.footerLine + 1,
1,
conflict.footerLine + 1,
1
),
options: {
isWholeLine: true,
className: `conflict-footer ${footerBg}`,
linesDecorationsClassName: 'conflict-footer-margin'
}
});
// Add action buttons with proper cleanup
const widgetId = `conflict-actions-${idx}`;
const actionsContainer = document.createElement('div');
actionsContainer.className =
'conflict-actions absolute left-0 z-10 !flex gap-4 text-muted-foreground h-5 w-fit';
const acceptCurrentBtn = document.createElement('div');
acceptCurrentBtn.className = `action-button h-5 accept-current text-sm cursor-pointer whitespace-nowrap ${buttonHover}`;
acceptCurrentBtn.textContent = 'Accept Current';
acceptCurrentBtn.onclick = () => handleAcceptCurrent(conflict, editor);
const acceptIncomingBtn = document.createElement('div');
acceptIncomingBtn.className = `action-button h-5 accept-incoming text-sm cursor-pointer whitespace-nowrap ${buttonHover}`;
acceptIncomingBtn.textContent = 'Accept AI';
acceptIncomingBtn.onclick = () => handleAcceptIncoming(conflict, editor);
actionsContainer.appendChild(acceptCurrentBtn);
actionsContainer.appendChild(acceptIncomingBtn);
const contentWidget = {
domNode: actionsContainer,
getId: () => widgetId,
getDomNode: () => actionsContainer,
getPosition: () => ({
position: {
lineNumber: conflict.headerLine + 1,
column: 1
},
preference: [ABOVE]
})
};
widgetsRef.current.push(contentWidget);
editor.addContentWidget(contentWidget);
});
// @ts-expect-error monaco
decorationsRef.current = editor.createDecorationsCollection(decorations);
// Scroll to the last decoration if there are any decorations
if (decorations.length > 0) {
const lastDecoration = decorations[decorations.length - 1];
editor.revealLineInCenter(lastDecoration.range.startLineNumber);
}
};
const makeEdit = (
editor: editor.IStandaloneCodeEditor,
conflict: IConflict,
newLines: string[]
) => {
const model = editor.getModel();
if (!model) return;
// Determine if we need to remove a blank line before the conflict
const startLineNumber = conflict.hasBlankLineBefore
? conflict.headerLine
: conflict.headerLine + 1;
const endLineNumber = conflict.footerLine + 2;
const range = new Range(startLineNumber, 1, endLineNumber, 1);
// Add newline at the end of the resolved content
const newTextLines = newLines.join('\n') + '\n';
const newPosition = new Position(
startLineNumber + newLines.length - 1,
newLines[newLines.length - 1].length + 1
);
editor.pushUndoStop();
editor.executeEdits('conflict-resolution', [
{
range: range,
text: newTextLines,
forceMoveMarkers: true
}
]);
editor.pushUndoStop();
editor.setPosition(newPosition);
editor.focus();
};
const handleAcceptCurrent = (
conflict: IConflict,
editor: editor.IStandaloneCodeEditor
) => {
if (!editor) return;
makeEdit(editor, conflict, conflict.current);
};
const handleAcceptIncoming = (
conflict: IConflict,
editor: editor.IStandaloneCodeEditor
) => {
if (!editor) return;
makeEdit(editor, conflict, conflict.incoming);
};
const handleAcceptAllConflicts = (
editor: editor.IStandaloneCodeEditor,
conflicts: IConflict[],
useIncoming: boolean
) => {
if (!editor) return;
// Sort conflicts in reverse order (bottom to top)
// This prevents position shifts from affecting subsequent resolutions
const sortedConflicts = [...conflicts].sort(
(a, b) => b.headerLine - a.headerLine
);
editor.pushUndoStop();
sortedConflicts.forEach((conflict) => {
const lines = useIncoming ? conflict.incoming : conflict.current;
const startLineNumber = conflict.hasBlankLineBefore
? conflict.headerLine
: conflict.headerLine + 1;
const endLineNumber = conflict.footerLine + 2;
const range = new Range(startLineNumber, 1, endLineNumber, 1);
const newTextLines = lines.join('\n') + '\n';
editor.executeEdits('conflict-resolution', [
{
range: range,
text: newTextLines,
forceMoveMarkers: true
}
]);
});
editor.pushUndoStop();
editor.focus();
};
// Clean up widgets when component unmounts
useEffect(() => {
return () => {
if (editorRef.current) {
clearAllWidgets(editorRef.current);
}
};
}, []);
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
const conflicedText = addBlankLines(value);
const forceRender = editor.getValue() !== conflicedText;
if (!forceRender) return;
const conflicts = parseConflicts(conflictedText);
if (conflicts) {
editor.setValue(conflictedText);
} else {
const position = editor.getPosition();
editor.setValue(conflictedText);
if (position) editor.setPosition(position);
}
}, [value]);
return (
<div
className={cn(
'flex-grow',
theme === 'looplit-dark' ? 'monaco-dark-card' : 'monaco-light-card'
)}
>
<Editor
height="100%"
width="100%"
loading={null}
language="yaml"
defaultValue={conflictedText}
onMount={(editor) => {
editorRef.current = editor;
}}
onChange={(newText) => {
if (!editorRef.current) return;
const remainingConflicts = parseConflicts(newText || '');
addConflictDecorations(editorRef.current, remainingConflicts);
setCanvas((prev) => {
if (!prev) return prev;
const nextAiState = editorRef.current?.getValue() || '';
if (!remainingConflicts.length) {
return {
...prev,
aiState: nextAiState,
acceptAll: undefined,
rejectAll: undefined
};
}
return {
...prev,
aiState: nextAiState,
acceptAll: () =>
handleAcceptAllConflicts(
editorRef.current!,
remainingConflicts,
true
),
rejectAll: () =>
handleAcceptAllConflicts(
editorRef.current!,
remainingConflicts,
false
)
};
});
}}
theme={theme}
options={{
readOnly,
fontFamily: 'inter, monospace, sans-serif',
fontSize: 15,
lineHeight: 24,
wordWrap: 'on',
unicodeHighlight: {
ambiguousCharacters: false,
invisibleCharacters: false
},
minimap: { enabled: false },
quickSuggestions: false,
suggestOnTriggerCharacters: false,
contextmenu: false,
renderLineHighlight: 'none' as const,
scrollBeyondLastLine: false,
overviewRulerLanes: 0,
lineNumbersMinChars: 1,
lineDecorationsWidth: 30,
glyphMargin: false,
folding: false,
scrollbar: {
useShadows: false,
alwaysConsumeMouseWheel: false
},
renderWhitespace: 'boundary'
}}
/>
</div>
);
};
export default StateMergeEditor;
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ThemeProvider.tsx | TypeScript (TSX) | import { createContext, useContext, useEffect, useState } from 'react';
type Theme = 'dark' | 'light' | 'system';
type ThemeProviderProps = {
children: React.ReactNode;
defaultTheme?: Theme;
storageKey?: string;
};
type ThemeProviderState = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const initialState: ThemeProviderState = {
theme: 'system',
setTheme: () => null
};
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
export function ThemeProvider({
children,
defaultTheme = 'system',
storageKey = 'vite-ui-theme',
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
);
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
}
};
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
);
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (context === undefined)
throw new Error('useTheme must be used within a ThemeProvider');
return context;
};
export const useMonacoTheme = () => {
const { theme } = useTheme();
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
const currentTheme = theme === 'system' ? systemTheme : theme;
return currentTheme === 'dark' ? 'looplit-dark' : 'looplit-light';
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ThemeToggle.tsx | TypeScript (TSX) | import { useTheme } from './ThemeProvider';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { Moon, Sun } from 'lucide-react';
interface Props {
className?: string;
}
export function ThemeToggle({ className }: Props) {
const { setTheme } = useTheme();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon" className={className}>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme('light')}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('dark')}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('system')}>
System
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/YamlEditor.tsx | TypeScript (TSX) | import { useMonacoTheme } from './ThemeProvider';
import { cn } from '@/lib/utils';
import Editor from '@monaco-editor/react';
import { load as yamlParse, dump as yamlStringify } from 'js-yaml';
import { type editor } from 'monaco-editor';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
interface Props {
value: Record<string, unknown>;
height?: string;
fitContent?: boolean;
className?: string;
onChange?: (value: Record<string, unknown>) => void;
}
// This is a hack to make all strings multi-line strings.
function convertToMultiline(obj: any): any {
if (typeof obj === 'string' && !obj.includes('\n')) {
return `${obj}\n`;
}
if (Array.isArray(obj)) {
return obj.map(convertToMultiline);
}
if (obj && typeof obj === 'object') {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, convertToMultiline(v)])
);
}
return obj;
}
function cleanupMultiline(obj: any): any {
if (typeof obj === 'string') {
return obj.replace(/\n$/, '');
}
if (Array.isArray(obj)) {
return obj.map(cleanupMultiline);
}
if (obj && typeof obj === 'object') {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, cleanupMultiline(v)])
);
}
return obj;
}
export const defaultOptions = {
fontFamily: 'inter, monospace, sans-serif',
fontSize: 14,
lineHeight: 24,
renderWhitespace: 'boundary' as const,
unicodeHighlight: {
ambiguousCharacters: false,
invisibleCharacters: false
},
wordWrap: 'on' as const,
minimap: { enabled: false },
quickSuggestions: false,
suggestOnTriggerCharacters: false,
contextmenu: false,
renderLineHighlight: 'none' as const,
scrollBeyondLastLine: false,
overviewRulerLanes: 0,
lineNumbersMinChars: 0,
glyphMargin: false,
lineNumbers: 'off' as const,
folding: true,
scrollbar: {
useShadows: false,
alwaysConsumeMouseWheel: false
}
};
export default function YamlEditor({
value,
className,
height,
fitContent,
onChange
}: Props) {
const preventNextOnChange = useRef(false);
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const theme = useMonacoTheme();
const [error, setError] = useState<string>();
useEffect(() => {
if (error) {
const id = toast.error(error);
return () => {
toast.dismiss(id);
};
}
}, [error]);
function adjustEditorHeightToContent() {
const editor = editorRef.current;
if (!editor) return;
const editorElement = editor.getDomNode();
if (!editorElement) return;
const contentHeight = editor.getContentHeight();
const editorHeight = contentHeight + 6;
const maxHeight = 500;
editorElement.style.height = `${Math.min(maxHeight, editorHeight)}px`;
editor.layout();
}
// Convert JSON to YAML string for initial display with proper multiline handling
const yamlString = yamlStringify(convertToMultiline(value), {
indent: 2,
lineWidth: -1,
noRefs: true,
flowLevel: -1,
skipInvalid: true,
noCompatMode: true,
styles: {
'!!str': 'literal' // Use literal style (|) for multiline strings
}
});
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
const forceRender = editor.getValue() !== yamlString;
if (forceRender) {
const position = editor.getPosition();
preventNextOnChange.current = true;
editor.setValue(yamlString);
if (position) editor.setPosition(position);
}
}, [yamlString]);
return (
<div className={cn(className, 'relative')}>
<Editor
loading={null}
width="100%"
height={height}
theme={theme}
options={{
...defaultOptions,
readOnly: !onChange
}}
defaultValue={yamlString}
onChange={(value) => {
if (preventNextOnChange.current) {
preventNextOnChange.current = false;
return;
}
if (!value) return;
try {
setError(undefined);
// Parse YAML with more lenient options
const jsonValue = yamlParse(value, {}) as Record<string, unknown>;
const cleanedValue = cleanupMultiline(jsonValue);
onChange?.(cleanedValue);
} catch (err) {
setError(String(err));
}
}}
language="yaml"
onMount={(editor) => {
editorRef.current = editor;
if (!fitContent) return;
editor.onDidContentSizeChange(() => {
adjustEditorHeightToContent();
});
editor.layout();
adjustEditorHeightToContent();
}}
/>
</div>
);
}
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ZoomableImage.tsx | TypeScript (TSX) | import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
import { DetailedHTMLProps, ImgHTMLAttributes } from 'react';
export const ZoomableImage = ({
alt = '',
className,
src,
...other
}: DetailedHTMLProps<
ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement
>) => {
return (
<Dialog>
<DialogTrigger asChild>
<img
alt={alt}
className={cn('cursor-zoom-in', className)}
src={src}
{...other}
/>
</DialogTrigger>
<DialogContent className="max-w-7xl border-0 bg-transparent p-0">
<div className="relative h-[calc(100vh-220px)] w-full overflow-clip rounded-md bg-transparent">
<img alt={alt} className="h-full w-full object-contain" src={src} />
</div>
</DialogContent>
</Dialog>
);
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/alert-dialog.tsx | TypeScript (TSX) | import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
import * as React from 'react';
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-2 text-center sm:text-left',
className
)}
{...props}
/>
);
AlertDialogHeader.displayName = 'AlertDialogHeader';
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
AlertDialogFooter.displayName = 'AlertDialogFooter';
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold', className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: 'outline' }),
'mt-2 sm:mt-0',
className
)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/alert.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';
const alertVariants = cva(
'relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive:
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive'
}
},
defaultVariants: {
variant: 'default'
}
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
{...props}
/>
));
AlertTitle.displayName = 'AlertTitle';
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm [&_p]:leading-relaxed', className)}
{...props}
/>
));
AlertDescription.displayName = 'AlertDescription';
export { Alert, AlertTitle, AlertDescription };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/aspect-ratio.tsx | TypeScript (TSX) | import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio';
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/badge.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';
const badgeVariants = cva(
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default:
'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
secondary:
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive:
'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
outline: 'text-foreground'
}
},
defaultVariants: {
variant: 'default'
}
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/button.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import { Slot } from '@radix-ui/react-slot';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default:
'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline:
'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline'
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-6 w-6 m-1'
}
},
defaultVariants: {
variant: 'default',
size: 'default'
}
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/card.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as React from 'react';
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-xl border bg-card text-card-foreground shadow',
className
)}
{...props}
/>
));
Card.displayName = 'Card';
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex flex-col space-y-1.5 p-6', className)}
{...props}
/>
));
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('font-semibold leading-none tracking-tight', className)}
{...props}
/>
));
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
));
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex items-center p-6 pt-0', className)}
{...props}
/>
));
CardFooter.displayName = 'CardFooter';
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/dialog.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import * as React from 'react';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-1.5 text-center sm:text-left',
className
)}
{...props}
/>
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
'text-lg font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/dropdown-menu.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { Check, ChevronRight, Circle } from 'lucide-react';
import * as React from 'react';
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
inset && 'pl-8',
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn('ml-auto text-xs tracking-widest opacity-60', className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut';
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/form.tsx | TypeScript (TSX) | import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import * as LabelPrimitive from '@radix-ui/react-label';
import { Slot } from '@radix-ui/react-slot';
import * as React from 'react';
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext
} from 'react-hook-form';
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error('useFormField should be used within <FormField>');
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
);
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn('space-y-2', className)} {...props} />
</FormItemContext.Provider>
);
});
FormItem.displayName = 'FormItem';
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (
<Label
ref={ref}
className={cn(error && 'text-destructive', className)}
htmlFor={formItemId}
{...props}
/>
);
});
FormLabel.displayName = 'FormLabel';
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
});
FormControl.displayName = 'FormControl';
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return (
<p
ref={ref}
id={formDescriptionId}
className={cn('text-[0.8rem] text-muted-foreground', className)}
{...props}
/>
);
});
FormDescription.displayName = 'FormDescription';
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p
ref={ref}
id={formMessageId}
className={cn('text-[0.8rem] font-medium text-destructive', className)}
{...props}
>
{body}
</p>
);
});
FormMessage.displayName = 'FormMessage';
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/input.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as React from 'react';
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = 'Input';
export { Input };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/label.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as LabelPrimitive from '@radix-ui/react-label';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/popover.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import * as React from 'react';
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/resizable.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import { GripVertical } from 'lucide-react';
import * as ResizablePrimitive from 'react-resizable-panels';
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
'flex h-full w-full data-[panel-group-direction=vertical]:flex-col',
className
)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
'relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90',
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/select.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp, ChevronsUpDown } from 'lucide-react';
import * as React from 'react';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronsUpDown className="h-3 w-3 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('px-2 py-1.5 text-sm font-semibold', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton
};
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit | |
frontend/src/components/ui/separator.tsx | TypeScript (TSX) | import { cn } from '@/lib/utils';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import * as React from 'react';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = 'horizontal', decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
className
)}
{...props}
/>
)
);
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
| willydouhard/looplit | 13 | TypeScript | willydouhard | Willy Douhard | Chainlit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.