task stringclasses 3
values | language stringclasses 1
value | instruction stringlengths 151 4.14k | response stringlengths 33 4.08k | source_file stringclasses 31
values | function_name stringlengths 3 35 | class_name stringclasses 14
values | line_start int64 23 941 | line_end int64 32 953 | license stringclasses 1
value | source stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _eval_node(node: ast.AST) -> float:
if isinstance(node, ast.Expression):
return _eval_node(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.v... | if isinstance(node, ast.UnaryOp):
value = _eval_node(node.operand)
if isinstance(node.op, ast.UAdd):
return value
if isinstance(node.op, ast.USub):
return -value
raise ValueError("not an arithmetic expression") | calculator.py | _eval_node | null | 51 | 68 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _normalise(text: str) -> str:
out = text.lower()
out = (out.replace("×", "*").replace("÷", "/").replace("−", "-")
.replace("–", "-").replace("—", "-").replace("^", "**"))
# "12 x 13" / "12x... | out = re.sub(r"(?<=\d)\s*[x×]\s*(?=\d)", "*", out)
return out | calculator.py | _normalise | null | 79 | 85 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _safe_result(expression: str) -> str | None:
try:
value = evaluate(expression)
except (SyntaxError, ValueError, ZeroDivisionError, OverflowError):
return None
``` | if isinstance(value, complex) or not math.isfinite(value):
return None
return _fmt(value) | calculator.py | _safe_result | null | 95 | 102 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def solve_math(text: str) -> str | None:
"""Return a short answer line, or None if this is not an arithmetic ask."""
low = _normalise(text)
if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):
... | expression = _strip_cues(low).replace(" ", "")
cue = _has_cue(low)
if _PURE.match(expression) and any(op in expression for op in "+-*/%") \
and any(ch.isdigit() for ch in expression):
pass
elif cue:
found = _EXPR.findall(low)
if not found:
return None
... | calculator.py | solve_math | null | 105 | 152 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def solve_math(text: str) -> str | None:
"""Return a short answer line, or None if this is not an arithmetic ask."""
low = _normalise(text)
if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):
return None
# square roots
m = re.searc... | Return a short answer line, or None if this is not an arithmetic ask. | calculator.py | solve_math | null | 105 | 152 | mit | SadikAI project |
code_generation | python | Write a Python function `solve_math(text: str)` that does the following:
Return a short answer line, or None if this is not an arithmetic ask.
Return only the Python code. | def solve_math(text: str) -> str | None:
"""Return a short answer line, or None if this is not an arithmetic ask."""
low = _normalise(text)
if _DATE.search(low) or any(w in low for w in _PHONE_WORDS):
return None
# square roots
m = re.search(r"(?:square root(?:\s+of)?|sqrt|√)\s*\(?\s*(\d+(?... | calculator.py | solve_math | null | 105 | 152 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def show(reply) -> None:
emo = reply.emotion
mood = reply.mood.get("label", "?")
print(f"\n{BOLD}{MODEL_NAME}{RESET} {DIM}[{reply.mode} · mood {mood} · "
f"{emo.get('label', '?')} {emo.get('valence... | for artifact in reply.artifacts:
print(f" {BOLD}saved{RESET} {artifact['name']}"
f" {DIM}({artifact['path']}){RESET}")
if reply.sources:
for src in reply.sources:
print(f" {DIM}source: {src['title']} — {src['url']}{RESET}")
if reply.memories:
print(f" {DI... | chat.py | show | null | 27 | 40 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--checkpoint", default="runs/medium/b... | while True:
try:
line = input("\nyou › ").strip()
except (EOFError, KeyboardInterrupt):
print("\nbye.")
break
if not line:
continue
if line in {"/quit", "/exit", "/q"}:
print("bye.")
break
if line == "/he... | chat.py | main | null | 43 | 144 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def __init__(
self,
checkpoint: str | Path = "runs/medium/best.pt",
tokenizer: str | Path = "tokenizer/tokenizer.json",
memory_path: str | Path = "data/chat/memory.json",
stat... | self.device = torch.device(device)
self.memory = MemoryStore(memory_path)
self.state_path = Path(state_path)
self.mood = self._load_mood()
self.web = web
self.use_model = use_model
self.rng = random.Random(seed)
self.tok: Tokenizer | None = None
se... | chat_engine.py | __init__ | ChatEngine | 146 | 171 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _load_model(self, checkpoint: str | Path, tokenizer: str | Path) -> None:
checkpoint = ensure_weights(checkpoint)
ckpt = torch.load(checkpoint, map_location=self.device, weights_only=False)
... | if any(k.startswith("_orig_mod.") for k in state):
state = {k.replace("_orig_mod.", "", 1): v for k, v in state.items()}
self.model.load_state_dict(state)
self.model.to(self.device).eval()
self.model_step = str(ckpt.get("step", "?"))
self.tok = Tokenizer(tokenizer) | chat_engine.py | _load_model | ChatEngine | 174 | 184 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _save(self) -> None:
self.memory.save()
self.state_path.parent.mkdir(parents=True, exist_ok=True)
``` | payload = {"mood": self.mood.to_dict(), "saved": time.time()}
self.state_path.write_text(json.dumps(payload, ensure_ascii=False, indent=1),
encoding="utf-8") | chat_engine.py | _save | ChatEngine | 195 | 200 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def respond(self, text: str) -> Reply:
text = " ".join(text.split()).strip()
if not text:
raise ValueError("empty message")
emotion = detect(text)
self.mood.update(emotio... | if low.startswith("/learn"):
reply = self._learn_reply(text)
elif low in {"/topics", "topics", "/learn topics"}:
reply = Reply(text=list_topics(), mode="learn")
elif low in {"/about", "/creator", "/about me"}:
reply = self._creator_reply(emotion)
elif ... | chat_engine.py | respond | ChatEngine | 203 | 260 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _recall(self, text: str, before: list[str]) -> list:
hits = self.memory.recall(text, k=4)
out = []
``` | for entry, score in hits:
if entry.text == text or entry.kind == "fact":
continue
if entry.text in before:
out.append((entry, score))
return out[:2] | chat_engine.py | _recall | ChatEngine | 263 | 271 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _memory_reply(self, emotion: Emotion, recalled: list) -> Reply:
profile = self.memory.profile()
stats = self.memory.stats()
if not profile and not recalled:
return Reply(
... | sentences: list[str] = []
if profile:
sentences.append("Here's what I remember: " + _profile_sentence(profile) + ".")
if recalled:
lines = "; ".join(f"“{_clip(e.text, 90)}”" for e, _ in recalled)
sentences.append(f"I also remember you saying {lines}.")
... | chat_engine.py | _memory_reply | ChatEngine | 277 | 296 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _web_reply(self, text: str, emotion: Emotion) -> Reply:
results = search(text)
if not results:
return Reply(
text="I looked, but couldn't find a clear answer. Try nami... | snippet = _two_sentences(top.snippet)
lead = WEB_LEAD.get(emotion.label, WEB_LEAD["neutral"])
text_out = f"{lead}{snippet}"
if len(results) > 1 and results[1].title.lower() != top.title.lower():
text_out += f" I also saw something about {results[1].title}."
return Rep... | chat_engine.py | _web_reply | ChatEngine | 384 | 406 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _weather_reply(self, text: str, emotion: Emotion) -> Reply:
city = _extract_city(text)
if not city:
return Reply(text="Which city? Say something like 'weather in Delhi' "
... | if result is None:
return Reply(text=f"I couldn't reach the weather service for {city}. "
"Check the spelling, or try again in a minute.",
mode="weather-miss")
return Reply(text=result.snippet, mode="weather",
source... | chat_engine.py | _weather_reply | ChatEngine | 408 | 422 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _identity_reply(self, emotion: Emotion) -> Reply:
who = self.memory.profile().get("name")
hello = f"Hi {who}. " if who else ""
``` | return Reply(
text=f"{hello}I'm {MODEL_NAME} — a {PARAMS}-parameter local language "
f"model made by {CREATOR_NAME} ({CREATOR_AGE}, {CREATOR_GRADE}). I was "
f"trained here on English, Hindi, Hinglish and code. I have persistent "
f"memory, a web lo... | chat_engine.py | _identity_reply | ChatEngine | 432 | 443 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _learn_reply(self, text: str) -> Reply:
topic = text[len("/learn"):].strip(" :—-")
if not topic:
return Reply(text=list_topics(), mode="learn")
lesson = answer_knowledge(topic... | if lesson is None:
return Reply(
text=f"I don't have a lesson on '{topic}' yet. Try one of these:\n\n"
+ list_topics(),
mode="learn",
)
return Reply(text=lesson, mode="learn") | chat_engine.py | _learn_reply | ChatEngine | 473 | 486 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _run_reply(self, text: str) -> Reply:
language, code = extract_code(text)
if not code.strip():
return Reply(
text="Paste the code after /run, or send it in a ``` block... | result = run_code(code, language)
return Reply(text=format_result(result), mode="run",
note="executed locally with an 8s timeout") | chat_engine.py | _run_reply | ChatEngine | 496 | 506 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _greeting_reply(self, emotion: Emotion) -> Reply:
name = self.memory.profile().get("name")
who = f" {name}" if name else ""
mood = self.mood.label()
``` | opener = self.rng.choice(["Hey", "Hello", "Hi"])
return Reply(
text=f"{opener}{who}. I'm feeling {mood} right now — what's on your mind?",
mode="greeting",
) | chat_engine.py | _greeting_reply | ChatEngine | 508 | 516 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _empathy_reply(self, text: str, emotion: Emotion,
recalled: list) -> Reply:
head = self.rng.choice(EMPATHY.get(emotion.label, EMPATHY["neutral"]))
tail = self.rng.choice(FO... | if recalled:
parts.append(f"Earlier you mentioned “{_clip(recalled[0][0].text, 80)}” — "
f"is this connected?")
elif 2 <= len(text.split()) <= 8 and emotion.label in {"joy", "love"}:
parts.append(f"“{text.rstrip('!.?')}” — that's a good line.")
pa... | chat_engine.py | _empathy_reply | ChatEngine | 518 | 530 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _free_reply(self, text: str, emotion: Emotion, recalled: list) -> Reply:
if self.use_model and len(text.split()) >= 12:
generated = self._generate(text, max_new_tokens=45)
if gene... | if recalled:
return Reply(
text=f"“{_clip(recalled[0][0].text, 80)}” — that connects to what "
f"you just said. Tell me more.",
mode="memory-chat",
memories=[e.text for e, _ in recalled],
)
return Reply(text=sel... | chat_engine.py | _free_reply | ChatEngine | 532 | 546 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _creative_reply(self, text: str, emotion: Emotion) -> Reply:
tale = answer_tale(text, self.memory.profile().get("name"))
if tale is not None:
return Reply(text=tale, mode="story",
... | prompt, seed_text = _creative_seed(text, low)
generated = self._generate(prompt, max_new_tokens=90,
temperature=max(0.7, self.mood.temperature()))
if not generated or not _usable(generated, prompt):
return Reply(
text="My 7.9M brain ... | chat_engine.py | _creative_reply | ChatEngine | 548 | 571 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _generate(self, prompt: str, max_new_tokens: int = 60,
temperature: float | None = None) -> str:
assert self.model is not None and self.tok is not None
ids = self.tok.encode(pro... | with torch.no_grad():
out = self.model.generate(
x,
max_new_tokens=max_new_tokens,
temperature=temperature if temperature is not None else self.mood.temperature(),
top_k=50,
top_p=0.92,
repetition_penalty... | chat_engine.py | _generate | ChatEngine | 574 | 593 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _profile_sentence(profile: dict[str, str]) -> str:
parts: list[str] = []
name = profile.get("name")
if name:
parts.append(f"you're {name}")
if profile.get("age"):
parts.append(f"{prof... | extras: list[str] = []
if profile.get("likes"):
extras.append(f"you like {profile['likes']}")
if profile.get("dislikes"):
extras.append(f"you don't like {profile['dislikes']}")
if profile.get("work"):
extras.append(f"you work as {profile['work']}")
if profile.get("goal"):
... | chat_engine.py | _profile_sentence | null | 603 | 624 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _extract_city(text: str) -> str:
lower = " ".join(text.lower().split())
for hint in WEATHER_HINTS:
lower = lower.replace(hint, " ")
``` | lower = re.sub(r"\b(what|whats|what's|is|the|in|at|of|today|tomorrow|now|"
r"kya|hai|ka|ki|ke|mein|me|aaj|kal|batao|please|tell|me)\b",
" ", lower)
words = [w for w in re.findall(r"[A-Za-z\u0900-\u097F]+", lower) if len(w) > 1]
return " ".join(words[:3]).strip() | chat_engine.py | _extract_city | null | 627 | 635 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _creative_hit(low: str) -> bool:
"""True for a real story/poem/code-generation ask.
Plain substring matching would treat "history" as "story", so word-shaped
hints use boundaries and inflections are lis... | if re.search(
r"\b(story|stories|poem|poems|program|programs|programming|script|"
r"scripts|function|functions|algorithm|algorithms)\b", low):
return True
return any(phrase in low for phrase in (
"write me", "write a", "code for", "kahani", "kavita", "shayari",
"कहानी", "... | chat_engine.py | _creative_hit | null | 638 | 651 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _creative_hit(low: str) -> bool:
"""True for a real story/poem/code-generation ask.
Plain substring matching would treat "history" as "story", so word-shaped
hints use boundaries and inflections are listed explicitly.
"""
if re.search(
... | True for a real story/poem/code-generation ask. | chat_engine.py | _creative_hit | null | 638 | 651 | mit | SadikAI project |
code_generation | python | Write a Python function `_creative_hit(low: str)` that does the following:
True for a real story/poem/code-generation ask.
Return only the Python code. | def _creative_hit(low: str) -> bool:
"""True for a real story/poem/code-generation ask.
Plain substring matching would treat "history" as "story", so word-shaped
hints use boundaries and inflections are listed explicitly.
"""
if re.search(
r"\b(story|stories|poem|poems|program|programs|prog... | chat_engine.py | _creative_hit | null | 638 | 651 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _creative_seed(text: str, low: str) -> tuple[str, str]:
if "code" in low or "function" in low or "program" in low or "script" in low:
return "def ", ""
if "shayari" in low or "शायरी" in low or "poem"... | if re.search(r"[\u0900-\u097F]", text):
return "एक समय की बात है", ""
if "kahani" in low or "story" in low:
return "Once upon a time", ""
return text[:200], "" | chat_engine.py | _creative_seed | null | 654 | 665 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _two_sentences(text: str) -> str:
text = " ".join(text.split())
parts = re.split(r"(?<=[.!?।])\s+", text)
``` | out = " ".join(parts[:2]).strip()
return _clip(out, 360) | chat_engine.py | _two_sentences | null | 668 | 672 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _clip(text: str, limit: int) -> str:
text = " ".join(text.split())
if len(text) <= limit:
return text
``` | cut = text[:limit]
if " " in cut:
cut = cut.rsplit(" ", 1)[0]
return cut + "…" | chat_engine.py | _clip | null | 675 | 682 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _finish(text: str) -> str:
text = text.replace("<|endoftext|>", " ").replace("<|pad|>", " ")
text = " ".join(text.split())
``` | if not text:
return text
if text[-1] not in ".!?।\"'”’":
text += "."
return text[0].upper() + text[1:] if text[0].isalpha() else text | chat_engine.py | _finish | null | 685 | 692 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _usable(text: str, prompt: str) -> bool:
words = text.split()
if len(words) < 4:
return False
letters = sum(ch.isalpha() or ch.isspace() or ch in ".,!?;:'\"-—" for ch in text)
if letters / ma... | if len(set(lowered)) / max(1, len(lowered)) < 0.35:
return False
trigrams = Counter(tuple(lowered[i:i + 3]) for i in range(len(lowered) - 2))
if trigrams and max(trigrams.values()) >= 3:
return False
prompt_words = set(prompt.lower().split())
if prompt_words and len(prompt_words & se... | chat_engine.py | _usable | null | 695 | 711 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _send(self, code: int, body: bytes, ctype: str) -> None:
self.send_response(code)
self.send_header("Content-Type", ctype)
``` | self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body) | chat_server.py | _send | Handler | 499 | 505 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def do_GET(self) -> None: # noqa: N802
path = urlparse(self.path).path
if path in ("/", "/index.html"):
self._send(200, PAGE.encode("utf-8"), "text/html; charset=utf-8")
retu... | if path.startswith("/files/"):
relative = unquote(path[len("/files/"):])
target = (GENERATED / relative).resolve()
if GENERATED != target and GENERATED not in target.parents:
self._json(404, {"error": "not found"})
return
if not tar... | chat_server.py | do_GET | Handler | 511 | 544 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def do_POST(self) -> None: # noqa: N802
path = urlparse(self.path).path
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b"{}"
try:
... | try:
if path == "/api/chat":
text = str(payload.get("text", "")).strip()
if not text:
self._json(400, {"error": "empty message"})
return
with LOCK:
ENGINE.web = bool(payload.get("web", True))
... | chat_server.py | do_POST | Handler | 546 | 581 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
global ENGINE
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--checkpoint", defa... | ENGINE = ChatEngine(
checkpoint=args.checkpoint,
tokenizer=args.tokenizer,
memory_path=Path(args.memory),
state_path=Path(args.state),
device=args.device,
web=not args.no_web,
use_model=not args.no_model,
)
server = ThreadingHTTPServer((args.host, arg... | chat_server.py | main | null | 584 | 623 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _write(path: Path, docs) -> tuple[int, int]:
path.parent.mkdir(parents=True, exist_ok=True)
count = 0
written = 0
``` | with path.open("w", encoding="utf-8", newline="\n") as fh:
for text in docs:
line = json.dumps({"text": text}, ensure_ascii=False) + "\n"
fh.write(line)
written += len(line.encode("utf-8"))
count += 1
print(f" {path.name}: {count:,} docs, {written / MB:.2... | code_curriculum.py | _write | null | 36 | 47 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _snippet_docs() -> list[str]:
docs: list[str] = []
english = [
"Write {lang} code for {topic}.",
"Show me a {lang} example of {topic}.",
"Give me {lang} code for {topic}.",
]
... | for snippet in SNIPPETS:
language = _pretty(snippet["language"])
topic = snippet["title"].rstrip(".!?")
lang_key = snippet["language"].lower()
for template in english[:3]:
question = template.format(lang=language, topic=topic)
docs.append(
f"Q... | code_curriculum.py | _snippet_docs | null | 57 | 105 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _trace_docs(limit: int = 4000) -> list[str]:
"""Execution traces for the operations a small model can actually learn."""
docs: list[str] = []
def add(question: str, answer: str, steps: str = "") -> None... | def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(math.isqrt(n)) + 1):
if n % i == 0:
return False
return True
for n in range(1, 101):
add(f"Is {n} a prime number?", "Yes" if is_prime(n) else "No",
"Tes... | code_curriculum.py | _trace_docs | null | 108 | 175 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _trace_docs(limit: int = 4000) -> list[str]:
"""Execution traces for the operations a small model can actually learn."""
docs: list[str] = []
def add(question: str, answer: str, steps: str = "") -> None:
body = f"Question: {question}\n"
... | Execution traces for the operations a small model can actually learn. | code_curriculum.py | _trace_docs | null | 108 | 175 | mit | SadikAI project |
code_generation | python | Write a Python function `_trace_docs(limit: int=4000)` that does the following:
Execution traces for the operations a small model can actually learn.
Return only the Python code. | def _trace_docs(limit: int = 4000) -> list[str]:
"""Execution traces for the operations a small model can actually learn."""
docs: list[str] = []
def add(question: str, answer: str, steps: str = "") -> None:
body = f"Question: {question}\n"
if steps:
body += f"Solution:\n{steps}... | code_curriculum.py | _trace_docs | null | 108 | 175 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _docstring_docs(stdlib: Path, limit: int, max_bytes: int) -> list[str]:
docs: list[str] = []
written = 0
skip_parts = {"test", "tests", "idlelib", "lib2to3", "tkinter",
"site-packages",... | for path in sorted(stdlib.rglob("*.py")):
if written >= max_bytes or len(docs) >= limit:
break
if any(part.lower() in skip_parts for part in path.parts):
continue
try:
source = path.read_text(encoding="utf-8", errors="ignore")
except OSError:
... | code_curriculum.py | _docstring_docs | null | 178 | 227 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _source_docs(paths: list[Path], skip: set[str], cap: int) -> list[str]:
docs: list[str] = []
written = 0
``` | for root in paths:
if not root.exists():
continue
for path in sorted(root.rglob("*")):
if written >= cap:
return docs
if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:
continue
if any(part.lower() in ski... | code_curriculum.py | _source_docs | null | 230 | 255 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ap = argparse.ArgumentParser(description=__doc__,
fo... | doc_docs = _docstring_docs(stdlib, args.docstrings,
int(args.docstring_mb * MB))
docs, size = _write(out / "stdlib.jsonl", doc_docs)
total_docs += docs
total_bytes += size
if not args.skip_sources:
node = shutil.which("node")
js_roots = []
if n... | code_curriculum.py | main | null | 258 | 306 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def extract_code(text: str) -> tuple[str, str]:
"""Return (language, code). Language is guessed when not supplied."""
fenced = FENCE.search(text)
language = ""
if fenced:
language = (fenced.group... | if not language:
low = code.lower()
if "console.log" in low or "function " in low and "=>" in low:
language = "javascript"
elif "#include" in low:
language = "cpp"
elif low.lstrip().startswith(("select ", "insert ", "update ", "create ",
... | code_runner.py | extract_code | null | 34 | 68 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def extract_code(text: str) -> tuple[str, str]:
"""Return (language, code). Language is guessed when not supplied."""
fenced = FENCE.search(text)
language = ""
if fenced:
language = (fenced.group(1) or "").lower()
code = fenced.group(2)
... | Return (language, code). Language is guessed when not supplied. | code_runner.py | extract_code | null | 34 | 68 | mit | SadikAI project |
code_generation | python | Write a Python function `extract_code(text: str)` that does the following:
Return (language, code). Language is guessed when not supplied.
Return only the Python code. | def extract_code(text: str) -> tuple[str, str]:
"""Return (language, code). Language is guessed when not supplied."""
fenced = FENCE.search(text)
language = ""
if fenced:
language = (fenced.group(1) or "").lower()
code = fenced.group(2)
else:
code = text
for prefix in... | code_runner.py | extract_code | null | 34 | 68 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _split_sql(script: str) -> list[str]:
"""Split a SQL script on semicolons, ignoring quoted strings and comments."""
statements: list[str] = []
buffer: list[str] = []
quote = ""
i = 0
``` | while i < len(script):
ch = script[i]
if quote:
buffer.append(ch)
if ch == quote:
if i + 1 < len(script) and script[i + 1] == quote:
buffer.append(script[i + 1])
i += 1
else:
quote = "... | code_runner.py | _split_sql | null | 71 | 107 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _split_sql(script: str) -> list[str]:
"""Split a SQL script on semicolons, ignoring quoted strings and comments."""
statements: list[str] = []
buffer: list[str] = []
quote = ""
i = 0
while i < len(script):
ch = script[i]
if q... | Split a SQL script on semicolons, ignoring quoted strings and comments. | code_runner.py | _split_sql | null | 71 | 107 | mit | SadikAI project |
code_generation | python | Write a Python function `_split_sql(script: str)` that does the following:
Split a SQL script on semicolons, ignoring quoted strings and comments.
Return only the Python code. | def _split_sql(script: str) -> list[str]:
"""Split a SQL script on semicolons, ignoring quoted strings and comments."""
statements: list[str] = []
buffer: list[str] = []
quote = ""
i = 0
while i < len(script):
ch = script[i]
if quote:
buffer.append(ch)
if ... | code_runner.py | _split_sql | null | 71 | 107 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def run_sql(code: str, timeout: float = 8.0) -> dict:
"""Run a SQL script against a fresh in-memory SQLite database."""
connection = sqlite3.connect(":memory:")
deadline = time.monotonic() + timeout
expi... | try:
for statement in _split_sql(code):
cursor = connection.execute(statement)
if cursor.description:
columns = [d[0] for d in cursor.description]
rows = cursor.fetchmany(200)
lines.append(" | ".join(columns))
lines.appe... | code_runner.py | run_sql | null | 110 | 151 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def run_sql(code: str, timeout: float = 8.0) -> dict:
"""Run a SQL script against a fresh in-memory SQLite database."""
connection = sqlite3.connect(":memory:")
deadline = time.monotonic() + timeout
expired = False
def progress() -> int:
no... | Run a SQL script against a fresh in-memory SQLite database. | code_runner.py | run_sql | null | 110 | 151 | mit | SadikAI project |
code_generation | python | Write a Python function `run_sql(code: str, timeout: float=8.0)` that does the following:
Run a SQL script against a fresh in-memory SQLite database.
Return only the Python code. | def run_sql(code: str, timeout: float = 8.0) -> dict:
"""Run a SQL script against a fresh in-memory SQLite database."""
connection = sqlite3.connect(":memory:")
deadline = time.monotonic() + timeout
expired = False
def progress() -> int:
nonlocal expired
if time.monotonic() > deadli... | code_runner.py | run_sql | null | 110 | 151 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def run_code(code: str, language: str = "python", timeout: float = 8.0) -> dict:
"""Execute code in a temporary directory. Returns {ok, output, language}."""
code = code.strip()
if not code:
return {... | with tempfile.TemporaryDirectory(prefix="sadik_run_") as tmp:
suffix = ".py" if language == "python" else ".js"
path = Path(tmp) / f"snippet{suffix}"
path.write_text(code, encoding="utf-8")
command = [sys.executable, str(path)] if language == "python" else ["node", str(path)]
... | code_runner.py | run_code | null | 154 | 191 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def run_code(code: str, language: str = "python", timeout: float = 8.0) -> dict:
"""Execute code in a temporary directory. Returns {ok, output, language}."""
code = code.strip()
if not code:
return {"ok": False, "output": "No code to run.", "languag... | Execute code in a temporary directory. Returns {ok, output, language}. | code_runner.py | run_code | null | 154 | 191 | mit | SadikAI project |
code_generation | python | Write a Python function `run_code(code: str, language: str='python', timeout: float=8.0)` that does the following:
Execute code in a temporary directory. Returns {ok, output, language}.
Return only the Python code. | def run_code(code: str, language: str = "python", timeout: float = 8.0) -> dict:
"""Execute code in a temporary directory. Returns {ok, output, language}."""
code = code.strip()
if not code:
return {"ok": False, "output": "No code to run.", "language": language}
if language == "sql":
re... | code_runner.py | run_code | null | 154 | 191 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def format_result(result: dict) -> str:
language = {"python": "Python", "javascript": "JavaScript", "sql": "SQL",
"cpp": "C++", "html": "HTML", "css": "CSS",
"powershell": "PowerShell... | status = "ran" if result["ok"] else "failed"
return f"Here's what {language} {status} on this PC:\n\n{result['output']}" | code_runner.py | format_result | null | 194 | 200 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--code", required=True)
ap.add_ar... | args = ap.parse_args()
language, code = extract_code(args.code)
if args.language:
language = args.language.lower()
result = run_code(code, language, args.timeout)
print(format_result(result)) | code_runner.py | main | null | 203 | 215 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:
"""Group lines into ~chunk_chars documents, preferring paragraph breaks."""
buf: list[str] = []
size = 0
``` | with path.open("r", encoding="utf-8", errors="ignore") as fh:
for line in fh:
buf.append(line)
size += len(line)
if size >= chunk_chars and not line.strip():
doc = "".join(buf).strip()
if doc:
yield doc
b... | data_sources.py | _iter_text_file | null | 48 | 69 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:
"""Group lines into ~chunk_chars documents, preferring paragraph breaks."""
buf: list[str] = []
size = 0
with path.open("r", encoding="utf-8", errors="ignore") as fh:
... | Group lines into ~chunk_chars documents, preferring paragraph breaks. | data_sources.py | _iter_text_file | null | 48 | 69 | mit | SadikAI project |
code_generation | python | Write a Python function `_iter_text_file(path: Path, chunk_chars: int=CHUNK_CHARS)` that does the following:
Group lines into ~chunk_chars documents, preferring paragraph breaks.
Return only the Python code. | def _iter_text_file(path: Path, chunk_chars: int = CHUNK_CHARS) -> Iterator[str]:
"""Group lines into ~chunk_chars documents, preferring paragraph breaks."""
buf: list[str] = []
size = 0
with path.open("r", encoding="utf-8", errors="ignore") as fh:
for line in fh:
buf.append(line)
... | data_sources.py | _iter_text_file | null | 48 | 69 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _iter_json_file(path: Path, text_key: str) -> Iterator[str]:
try:
with path.open("r", encoding="utf-8", errors="ignore") as fh:
data = json.load(fh)
except json.JSONDecodeError:
r... | items = data if isinstance(data, list) else [data]
for obj in items:
if isinstance(obj, str):
yield obj
elif isinstance(obj, dict) and isinstance(obj.get(text_key), str):
yield obj[text_key] | data_sources.py | _iter_json_file | null | 96 | 107 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _iter_files(root: Path, text_key: str) -> Iterator[str]:
if root.is_file():
files = [root]
else:
files = sorted(
p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in ... | if not files:
raise FileNotFoundError(
f"no text files found under {root!s} "
f"(looked for {', '.join(sorted(TEXT_SUFFIXES))})"
)
for path in files:
suffix = path.suffix.lower()
if suffix == ".jsonl":
yield from _iter_jsonl_file(path, text_key... | data_sources.py | _iter_files | null | 110 | 129 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _iter_hf(
dataset: str,
config: str | None,
split: str,
text_key: str,
) -> Iterator[str]:
try:
from datasets import load_dataset
except ImportError as exc: # pragma: no cover
... | ds = load_dataset(dataset, config, split=split, streaming=True)
for row in ds:
if isinstance(row, dict):
text = row.get(text_key)
if isinstance(text, str) and text:
yield text
elif isinstance(row, str):
yield row | data_sources.py | _iter_hf | null | 132 | 152 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _repeat_docs(path: Path, text_key: str, times: int) -> Iterator[str]:
"""Yield a directory's documents `times` times (true oversampling)."""
for _ in range(max(1, times)):
yield from _iter_files(path, text_key)
``` | Yield a directory's documents `times` times (true oversampling). | data_sources.py | _repeat_docs | null | 155 | 158 | mit | SadikAI project |
code_generation | python | Write a Python function `_repeat_docs(path: Path, text_key: str, times: int)` that does the following:
Yield a directory's documents `times` times (true oversampling).
Return only the Python code. | def _repeat_docs(path: Path, text_key: str, times: int) -> Iterator[str]:
"""Yield a directory's documents `times` times (true oversampling)."""
for _ in range(max(1, times)):
yield from _iter_files(path, text_key) | data_sources.py | _repeat_docs | null | 155 | 158 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def iter_mixed_documents(
root: str | Path,
weights: dict[str, float],
text_key: str = "text",
max_bytes: int | None = None,
) -> Iterator[str]:
"""Interleave sub-directories of `root` and oversample... | if not streams:
raise SystemExit(f"no weighted sub-directories found under {root}")
cycle = list(streams)
dead: set[str] = set()
seen = 0
while len(dead) < len(streams):
progressed = False
for name in cycle:
if name in dead:
continue
t... | data_sources.py | iter_mixed_documents | null | 161 | 203 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def iter_mixed_documents(
root: str | Path,
weights: dict[str, float],
text_key: str = "text",
max_bytes: int | None = None,
) -> Iterator[str]:
"""Interleave sub-directories of `root` and oversample them by weight.
`weights` maps a directory n... | Interleave sub-directories of `root` and oversample them by weight. | data_sources.py | iter_mixed_documents | null | 161 | 203 | mit | SadikAI project |
code_generation | python | Write a Python function `iter_mixed_documents(root: str | Path, weights: dict[str, float], text_key: str='text', max_bytes: int | None=None)` that does the following:
Interleave sub-directories of `root` and oversample them by weight.
Return only the Python code. | def iter_mixed_documents(
root: str | Path,
weights: dict[str, float],
text_key: str = "text",
max_bytes: int | None = None,
) -> Iterator[str]:
"""Interleave sub-directories of `root` and oversample them by weight.
`weights` maps a directory name to a repeat count, e.g.
``{"english": 1, "c... | data_sources.py | iter_mixed_documents | null | 161 | 203 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _iter_synth(total_chars: int) -> Iterator[str]:
"""Deterministic pseudo-text; only for testing the pipeline end to end."""
alphabet = "abcdefghijklmnopqrstuvwxyz .,\n"
import random
rng = random.Ran... | written = 0
while written < total_chars:
n = rng.randint(200, 800)
doc = "".join(rng.choice(alphabet) for _ in range(n)).strip()
if doc:
yield doc
written += len(doc) | data_sources.py | _iter_synth | null | 206 | 218 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _iter_synth(total_chars: int) -> Iterator[str]:
"""Deterministic pseudo-text; only for testing the pipeline end to end."""
alphabet = "abcdefghijklmnopqrstuvwxyz .,\n"
import random
rng = random.Random(1234)
written = 0
while written < tota... | Deterministic pseudo-text; only for testing the pipeline end to end. | data_sources.py | _iter_synth | null | 206 | 218 | mit | SadikAI project |
code_generation | python | Write a Python function `_iter_synth(total_chars: int)` that does the following:
Deterministic pseudo-text; only for testing the pipeline end to end.
Return only the Python code. | def _iter_synth(total_chars: int) -> Iterator[str]:
"""Deterministic pseudo-text; only for testing the pipeline end to end."""
alphabet = "abcdefghijklmnopqrstuvwxyz .,\n"
import random
rng = random.Random(1234)
written = 0
while written < total_chars:
n = rng.randint(200, 800)
... | data_sources.py | _iter_synth | null | 206 | 218 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def iter_documents(
source: str = "files",
input_path: str | None = None,
hf_dataset: str = "wikitext",
hf_config: str | None = "wikitext-103-raw-v1",
hf_split: str = "train",
text_key: str = "te... | if source == "files":
if not input_path:
raise SystemExit("--input is required when --source files")
stream = _iter_files(Path(input_path), text_key)
elif source == "hf":
stream = _iter_hf(hf_dataset, hf_config, hf_split, text_key)
elif source == "synth":
stream =... | data_sources.py | iter_documents | null | 221 | 248 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def iter_documents(
source: str = "files",
input_path: str | None = None,
hf_dataset: str = "wikitext",
hf_config: str | None = "wikitext-103-raw-v1",
hf_split: str = "train",
text_key: str = "text",
max_bytes: int | None = None,
) -> Iterat... | Yield documents until `max_bytes` of text has been produced (or EOF). | data_sources.py | iter_documents | null | 221 | 248 | mit | SadikAI project |
code_generation | python | Write a Python function `iter_documents(source: str='files', input_path: str | None=None, hf_dataset: str='wikitext', hf_config: str | None='wikitext-103-raw-v1', hf_split: str='train', text_key: str='text', max_bytes: int | None=None)` that does the following:
Yield documents until `max_bytes` of text has been produc... | def iter_documents(
source: str = "files",
input_path: str | None = None,
hf_dataset: str = "wikitext",
hf_config: str | None = "wikitext-103-raw-v1",
hf_split: str = "train",
text_key: str = "text",
max_bytes: int | None = None,
) -> Iterator[str]:
"""Yield documents until `max_bytes` o... | data_sources.py | iter_documents | null | 221 | 248 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def update(self, emotion: Emotion) -> None:
rate = 0.35
self.valence = (1 - rate) * self.valence + rate * emotion.valence
``` | self.arousal = (1 - rate) * self.arousal + rate * emotion.arousal
self.energy = min(1.0, 0.9 * self.energy + 0.1 * (0.35 + 0.65 * emotion.arousal))
self.turns += 1
self.last_label = emotion.label | emotion.py | update | Mood | 154 | 160 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def label(self) -> str:
v = self.valence
if v >= 0.30:
base = "happy"
elif v >= 0.10:
base = "warm"
elif v <= -0.30:
base = "low"
elif v <=... | if self.arousal >= 0.62 and base in {"happy", "calm", "warm"}:
return f"{base} and energised"
if self.arousal >= 0.62:
return f"{base} and agitated"
return base | emotion.py | label | Mood | 162 | 178 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def is_greeting(text: str) -> bool:
low = " ".join(WORD_RE.findall(text.lower()))
if not low:
return False
``` | if low.strip() in GREETINGS:
return True
return any(p in low for p in GREETING_PHRASES) | emotion.py | is_greeting | null | 193 | 199 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def detect(text: str) -> Emotion:
tokens = [t.lower() for t in WORD_RE.findall(text)]
if not tokens:
return Emotion()
scores: dict[str, float] = {k: 0.0 for k in LEXICON}
hits: list[str] = []
... | for phrase, (label, weight) in PHRASES.items():
if phrase in low:
scores[label] += weight
hits.append(phrase)
pos = scores["joy"] + scores["love"] + scores["gratitude"]
neg = scores["sadness"] + scores["anger"] + scores["fear"]
total = pos + neg + scores["surprise"] * 0.... | emotion.py | detect | null | 202 | 266 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _dedupe(items: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
``` | for item in items:
key = item.lower()
if key not in seen:
seen.add(key)
out.append(item)
return out | emotion.py | _dedupe | null | 274 | 282 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _copy(checkpoint: Path) -> Path:
"""Copy before loading so a trainer mid-write can't corrupt the read."""
temp = Path(tempfile.gettempdir()) / f"sadik_export_{checkpoint.name}"
``` | shutil.copyfile(checkpoint, temp)
return temp | export_release.py | _copy | null | 536 | 540 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _copy(checkpoint: Path) -> Path:
"""Copy before loading so a trainer mid-write can't corrupt the read."""
temp = Path(tempfile.gettempdir()) / f"sadik_export_{checkpoint.name}"
shutil.copyfile(checkpoint, temp)
return temp
``` | Copy before loading so a trainer mid-write can't corrupt the read. | export_release.py | _copy | null | 536 | 540 | mit | SadikAI project |
code_generation | python | Write a Python function `_copy(checkpoint: Path)` that does the following:
Copy before loading so a trainer mid-write can't corrupt the read.
Return only the Python code. | def _copy(checkpoint: Path) -> Path:
"""Copy before loading so a trainer mid-write can't corrupt the read."""
temp = Path(tempfile.gettempdir()) / f"sadik_export_{checkpoint.name}"
shutil.copyfile(checkpoint, temp)
return temp | export_release.py | _copy | null | 536 | 540 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _zip(stage: Path, out_zip: Path) -> None:
if out_zip.exists():
out_zip.unlink()
``` | with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as bundle:
for path in sorted(stage.rglob("*")):
if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc":
bundle.write(path, path.relative_to(stage).as_posix()) | export_release.py | _zip | null | 556 | 562 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _write_checksums(stage: Path) -> None:
"""SHA-256 for every file in the release, so buyers can verify the unzip."""
lines = []
``` | for path in sorted(stage.rglob("*")):
if path.is_file() and path.name != "SHA256SUMS" and "__pycache__" not in path.parts and path.suffix != ".pyc":
lines.append(f"{_sha256(path)} {path.relative_to(stage).as_posix()}")
_write(stage / "SHA256SUMS", "\n".join(lines) + "\n") | export_release.py | _write_checksums | null | 565 | 571 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def _write_checksums(stage: Path) -> None:
"""SHA-256 for every file in the release, so buyers can verify the unzip."""
lines = []
for path in sorted(stage.rglob("*")):
if path.is_file() and path.name != "SHA256SUMS" and "__pycache__" not in path.pa... | SHA-256 for every file in the release, so buyers can verify the unzip. | export_release.py | _write_checksums | null | 565 | 571 | mit | SadikAI project |
code_generation | python | Write a Python function `_write_checksums(stage: Path)` that does the following:
SHA-256 for every file in the release, so buyers can verify the unzip.
Return only the Python code. | def _write_checksums(stage: Path) -> None:
"""SHA-256 for every file in the release, so buyers can verify the unzip."""
lines = []
for path in sorted(stage.rglob("*")):
if path.is_file() and path.name != "SHA256SUMS" and "__pycache__" not in path.parts and path.suffix != ".pyc":
lines.ap... | export_release.py | _write_checksums | null | 565 | 571 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _find_manifest(folder: Path) -> Path:
matches = sorted(folder.glob(f"*{MANIFEST_SUFFIX}"))
if not matches:
raise FileNotFoundError(
f"No *{MANIFEST_SUFFIX} file found in {folder}. "
... | if len(matches) > 1:
names = ", ".join(path.name for path in matches)
raise ValueError(
f"More than one split manifest found in {folder}: {names}. "
"Keep only one release at a time, or pass --manifest."
)
return matches[0] | join_release_zip.py | _find_manifest | null | 41 | 54 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _load_manifest(path: Path) -> dict:
try:
manifest = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise ValueError(f"cannot read {path}: {exc}") from exc
... | if not isinstance(manifest.get("parts"), list) or not manifest["parts"]:
raise ValueError(f"{path} has no parts")
if not isinstance(manifest.get("size"), int) or manifest["size"] <= 0:
raise ValueError(f"{path} has a bad total size")
if not isinstance(manifest.get("sha256"), str):
ra... | join_release_zip.py | _load_manifest | null | 57 | 72 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def join_release(folder: Path, manifest_path: Path | None = None,
*, verbose: bool = True) -> Path:
folder = Path(folder)
manifest_path = Path(manifest_path) if manifest_path else _find_manifest... | try:
with temp.open("wb") as out:
for part_path, part_size, part_sha in parts:
actual_size = part_path.stat().st_size
if actual_size != part_size:
raise ValueError(
f"{part_path} is {actual_size} bytes, expected {part_si... | join_release_zip.py | join_release | null | 75 | 149 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
ap = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
ap.add_argument("--dir", type=Path, default=Path(__file__).resol... | ap.add_argument("--manifest", type=Path, default=None,
help="exact manifest path, if the folder has more than one")
args = ap.parse_args()
try:
join_release(args.dir, args.manifest)
except (OSError, ValueError) as exc:
raise SystemExit(f"error: {exc}") from exc | join_release_zip.py | main | null | 152 | 165 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _load_manifest(path: Path) -> dict:
try:
manifest = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise ValueError(f"cannot read {path}: {exc}") from exc
... | if not isinstance(manifest.get("parts"), list) or not manifest["parts"]:
raise ValueError(f"{path} has no parts")
if not isinstance(manifest.get("size"), int) or not manifest["size"] > 0:
raise ValueError(f"{path} has a bad total size")
if not isinstance(manifest.get("sha256"), str):
... | join_weights.py | _load_manifest | null | 43 | 56 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def ensure_weights(path: str | Path = "model/weights.pt", *, verbose: bool = True) -> Path:
"""Return a complete ``weights.pt``, joining split parts when needed.
If no manifest exists next to ``path``, the file... | temp = target.parent / (target.name + ".joining")
digest = hashlib.sha256()
written = 0
if verbose:
print(f"joining {len(parts)} weights parts -> {target}", file=sys.stderr)
try:
with temp.open("wb") as out:
for part_path, part_size, part_sha in parts:
ac... | join_weights.py | ensure_weights | null | 59 | 144 | mit | SadikAI project |
code_explanation | python | Explain what this Python function does.
```python
def ensure_weights(path: str | Path = "model/weights.pt", *, verbose: bool = True) -> Path:
"""Return a complete ``weights.pt``, joining split parts when needed.
If no manifest exists next to ``path``, the file is returned unchanged when
present (normal zi... | Return a complete ``weights.pt``, joining split parts when needed. | join_weights.py | ensure_weights | null | 59 | 144 | mit | SadikAI project |
code_generation | python | Write a Python function `ensure_weights(path: str | Path='model/weights.pt', *, verbose: bool=True)` that does the following:
Return a complete ``weights.pt``, joining split parts when needed.
Return only the Python code. | def ensure_weights(path: str | Path = "model/weights.pt", *, verbose: bool = True) -> Path:
"""Return a complete ``weights.pt``, joining split parts when needed.
If no manifest exists next to ``path``, the file is returned unchanged when
present (normal zip release layout). If the file is missing or does n... | join_weights.py | ensure_weights | null | 59 | 144 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--dir", type=Path, default=Path(__fil... | try:
if args.check:
if not target.exists():
raise FileNotFoundError(f"{target} is missing")
if not manifest.exists():
raise FileNotFoundError(f"{manifest} is missing")
data = _load_manifest(manifest)
actual = sha256_file(target)... | join_weights.py | main | null | 147 | 172 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def _hit(haystack: str, keyword: str) -> bool:
keyword = keyword.lower().strip()
if not keyword:
return False
``` | if " " in keyword or any(ord(ch) > 127 for ch in keyword):
return keyword in haystack
return re.search(rf"\b{re.escape(keyword)}\b", haystack) is not None | knowledge.py | _hit | null | 890 | 896 | mit | SadikAI project |
code_completion | python | Complete the following Python code. Return only the continuation, preserving indentation.
```python
def answer_knowledge(text: str) -> str | None:
"""Return a curated lesson for a learning question, or None."""
low = _normalise(text)
if not low:
return None
first_aid_cues = (
"bleeding... | wants_explanation = any(hint in low for hint in INTENT_HINTS)
best: Lesson | None = None
best_score = 0.0
for lesson in LESSONS:
score = 0.0
for keyword in lesson.keywords:
if _hit(low, keyword):
score += 1.0 + 0.5 * (len(keyword.split()) - 1)
if score... | knowledge.py | answer_knowledge | null | 899 | 938 | mit | SadikAI project |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.