chore: import upstream snapshot with attribution
CI / test (3.10) (push) Failing after 1s
CI / test (3.12) (push) Failing after 0s
CI / skillgen-check (push) Failing after 0s
CI / security-scan (push) Failing after 0s

This commit is contained in:
wehub-resource-sync
2026-07-13 12:09:14 +08:00
commit d88fd01084
727 changed files with 235247 additions and 0 deletions
View File
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Benchmark: sequential vs parallel AST extraction.
Usage:
python tests/bench_extract.py [path-to-repo]
Defaults to the current directory if no path is given.
Clears the AST cache between runs so every file is re-extracted.
Example output:
=== Graphify AST Extraction Benchmark ===
Files: 1,247
Languages: Python (412), TypeScript (389), Go (201), ...
Sequential: 4.32s (8,934 nodes, 12,456 edges)
Parallel (8): 1.28s (8,934 nodes, 12,456 edges)
Speedup: 3.38x
Results: ✓ identical
"""
from __future__ import annotations
import sys
import time
from collections import Counter
from pathlib import Path
# Ensure the project root is importable
_project_root = Path(__file__).resolve().parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
from graphify.extract import extract, collect_files
from graphify.cache import clear_cache
def _count_by_ext(paths: list[Path]) -> dict[str, int]:
"""Count files by extension."""
counter: Counter[str] = Counter()
for p in paths:
ext = p.suffix.lower()
counter[ext] += 1
return dict(counter.most_common())
_EXT_NAMES: dict[str, str] = {
".py": "Python",
".js": "JavaScript",
".jsx": "JSX",
".mjs": "MJS",
".ts": "TypeScript",
".tsx": "TSX",
".go": "Go",
".rs": "Rust",
".java": "Java",
".c": "C",
".h": "C Header",
".cpp": "C++",
".cc": "C++",
".cxx": "C++",
".hpp": "C++ Header",
".rb": "Ruby",
".cs": "C#",
".kt": "Kotlin",
".kts": "Kotlin Script",
".scala": "Scala",
".php": "PHP",
".swift": "Swift",
".lua": "Lua",
".toc": "Lua TOC",
".zig": "Zig",
".ps1": "PowerShell",
".ex": "Elixir",
".exs": "Elixir Script",
".m": "Obj-C",
".mm": "Obj-C++",
".jl": "Julia",
".vue": "Vue",
".svelte": "Svelte",
".dart": "Dart",
".v": "Verilog",
".sv": "SystemVerilog",
".sql": "SQL",
}
def _format_languages(ext_counts: dict[str, int]) -> str:
parts = []
for ext, count in ext_counts.items():
name = _EXT_NAMES.get(ext, ext)
parts.append(f"{name} ({count})")
return ", ".join(parts)
def _run_extraction(
paths: list[Path],
cache_root: Path,
parallel: bool,
max_workers: int | None = None,
) -> tuple[float, int, int]:
"""Run extraction, return (elapsed_seconds, node_count, edge_count)."""
clear_cache(cache_root)
t0 = time.perf_counter()
result = extract(
paths, cache_root=cache_root, parallel=parallel, max_workers=max_workers
)
elapsed = time.perf_counter() - t0
nodes = len(result.get("nodes", []))
edges = len(result.get("edges", []))
return elapsed, nodes, edges
def main() -> None:
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
target = target.resolve()
if not target.exists():
print(f"Error: {target} does not exist", file=sys.stderr)
sys.exit(1)
print("=== Graphify AST Extraction Benchmark ===\n")
print(f"Scanning {target} ...", flush=True)
paths = collect_files(target)
if not paths:
print("No extractable files found.", file=sys.stderr)
sys.exit(1)
ext_counts = _count_by_ext(paths)
print(f"Files: {len(paths):,}")
print(f"Languages: {_format_languages(ext_counts)}")
print()
cache_root = target if target.is_dir() else target.parent
# Workers count (same logic as _extract_parallel)
import os
workers = min(os.cpu_count() or 4, len(paths), 8)
# Run sequential
print("Running sequential extraction...", flush=True)
seq_time, seq_nodes, seq_edges = _run_extraction(paths, cache_root, parallel=False)
print(f"Sequential: {seq_time:.2f}s ({seq_nodes:,} nodes, {seq_edges:,} edges)")
# Run parallel
print(f"\nRunning parallel extraction ({workers} workers)...", flush=True)
par_time, par_nodes, par_edges = _run_extraction(
paths, cache_root, parallel=True, max_workers=workers
)
print(
f"Parallel ({workers}): {par_time:.2f}s ({par_nodes:,} nodes, {par_edges:,} edges)"
)
# Results
print()
if seq_time > 0:
speedup = seq_time / par_time if par_time > 0 else float("inf")
print(f"Speedup: {speedup:.2f}x")
print(f"Workers: {workers} (auto-detected)")
# Validate correctness
if seq_nodes == par_nodes and seq_edges == par_edges:
print("Results: ✓ identical (node count, edge count match)")
else:
print("Results: ✗ MISMATCH!")
print(f" Sequential: {seq_nodes} nodes, {seq_edges} edges")
print(f" Parallel: {par_nodes} nodes, {par_edges} edges")
sys.exit(1)
# Clean up cache after benchmark
clear_cache(cache_root)
print("\nCache cleared after benchmark.")
if __name__ == "__main__":
main()
+20
View File
@@ -0,0 +1,20 @@
from __future__ import annotations
from typing import Any
import pytest
_ANALYZE_WARNING_FILTERS = (
"ignore:Tensorflow not installed; ParametricUMAP will be unavailable:ImportWarning:umap",
"ignore:Please import `random` from the `scipy\\.sparse` namespace.*:"
"DeprecationWarning:hyppo\\.independence\\.hhg",
"ignore:The keyword argument 'nopython=False' was supplied.*:Warning:numba\\.core\\.decorators",
)
def pytest_collection_modifyitems(items: list[Any]) -> None:
for item in items:
if item.path.name != "test_analyze.py":
continue
for warning_filter in _ANALYZE_WARNING_FILTERS:
item.add_marker(pytest.mark.filterwarnings(warning_filter))
+11
View File
@@ -0,0 +1,11 @@
// Barrel file that re-exports from submodules
export { readCookie, writeCookie } from "./cookieHelpers";
export * from "./storageHelpers";
export { basePathRewrite, getFullUrl } from "./urlHelpers";
// Also has local exports (should still be extracted as nodes)
export function localHelper() {
return "local";
}
export const LOCAL_CONST = 42;
+12
View File
@@ -0,0 +1,12 @@
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Binding x:Key="TaxBinding" Path="Invoice.Tax" Converter="{StaticResource TaxConverter}" />
</Window.Resources>
<StackPanel x:Name="RootPanel">
<TextBlock x:Name="UserText" Text="{Binding User.Name}" />
<TextBlock x:Name="TotalText" Text="{Binding Path=Order.Total, Converter={StaticResource MoneyConverter}}" />
<Button x:Name="SaveButton" Command="{Binding SaveCommand}" />
<TextBlock x:Name="ModeText" Text="{Binding Mode=TwoWay}" />
</StackPanel>
</Window>
+12
View File
@@ -0,0 +1,12 @@
const { loadFoundation, validateConfig } = require('./foundation');
const utils = require('./utils');
const helper = require('./helpers').helperFn;
function runDispatch() {
const cfg = loadFoundation({});
validateConfig(cfg);
utils.log('go');
helper();
}
module.exports = { runDispatch };
+5
View File
@@ -0,0 +1,5 @@
export function readCookie(name: string): string {
return "";
}
export function writeCookie(name: string, value: string): void {}
+3
View File
@@ -0,0 +1,3 @@
#include "Logger.h"
void Logger::log() {}
+4
View File
@@ -0,0 +1,4 @@
class Logger {
public:
void log();
};
+3
View File
@@ -0,0 +1,3 @@
#include "Logger.h"
void Logger::log() {}
+4
View File
@@ -0,0 +1,4 @@
class Logger {
public:
void log();
};
+5
View File
@@ -0,0 +1,5 @@
#include "Foo.h"
void Foo::bar() {
value = 1;
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef FOO_H
#define FOO_H
class Foo {
public:
void bar();
int value;
};
#endif
+7
View File
@@ -0,0 +1,7 @@
#include "Foo.h"
int main() {
Foo f;
f.bar();
return 0;
}
+4
View File
@@ -0,0 +1,4 @@
class Dup {
public:
void a();
};
+4
View File
@@ -0,0 +1,4 @@
class Dup {
public:
void b();
};
+7
View File
@@ -0,0 +1,7 @@
#ifndef PLAIN_H
#define PLAIN_H
int add(int a, int b);
struct Point { int x; int y; };
#endif
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "crate_a"
version = "0.1.0"
edition = "2021"
+7
View File
@@ -0,0 +1,7 @@
pub fn start() -> bool {
true
}
pub fn parse(s: &str) -> u32 {
s.len() as u32
}
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "crate_b"
version = "0.1.0"
edition = "2021"
+18
View File
@@ -0,0 +1,18 @@
// crate_b has no dependency on crate_a.
// These calls use Type::method() (scoped_identifier) and common names that
// previously produced spurious INFERRED edges into crate_a (#908).
pub struct Server;
impl Server {
pub fn run(&self) {
// Server::start() — scoped call, should not wire to crate_a::start
let _ = Server::start();
// Url::parse() — scoped call, should not wire to crate_a::parse
let _ = Url::parse("http://example.com");
}
fn start() -> bool {
false
}
}
+33
View File
@@ -0,0 +1,33 @@
# Deploy Guide
How to deploy the QuranicWords backend.
## Prerequisites
- Docker installed
- SSH access to VPS
## Full Deploy
Run this one-liner on your VPS:
```bash
cd /opt/QuranicWords && git pull origin main && docker compose build --no-cache api
```
### Database Migration
If you changed the Prisma schema:
```sql
ALTER TABLE users ADD COLUMN points INT DEFAULT 0;
```
## Rollback
Use `git revert` to undo bad deploys.
```python
def rollback(version):
subprocess.run(["git", "checkout", version])
```
+32
View File
@@ -0,0 +1,32 @@
import { logger } from './logger';
async function processInbound(orgId: string, phone: string) {
const { shouldHandle, processMessage } = await import('./mayaEngine.js');
const handle = await shouldHandle(orgId, phone);
if (handle.sessionId) {
await processMessage({ orgId, phone }, handle.sessionId);
}
}
async function pollMessages(orgId: string) {
const { commsQueue } = await import('./queue.js');
await commsQueue.add('check-inbound', { orgId });
}
async function loadHandler(handlerName: string) {
// dynamic template literal — path not statically resolvable, should produce no edge
const mod = await import(`./handlers/${handlerName}`);
return mod.default;
}
async function loadStatic() {
// static template literal (no interpolation) — should resolve like a plain string
const { helper } = await import(`./staticHelper`);
return helper;
}
function syncOnly() {
logger.info('no dynamic imports here');
}
export { processInbound, pollMessages, loadHandler, loadStatic, syncOnly };
+16
View File
@@ -0,0 +1,16 @@
{
"nodes": [
{"id": "n_transformer", "label": "Transformer", "file_type": "code", "source_file": "model.py", "source_location": "L1"},
{"id": "n_attention", "label": "MultiHeadAttention", "file_type": "code", "source_file": "model.py", "source_location": "L10"},
{"id": "n_layernorm", "label": "LayerNorm", "file_type": "code", "source_file": "model.py", "source_location": "L20"},
{"id": "n_concept_attn","label": "attention mechanism", "file_type": "document", "source_file": "paper.md", "source_location": "§3.1"}
],
"edges": [
{"source": "n_transformer", "target": "n_attention", "relation": "contains", "confidence": "EXTRACTED", "source_file": "model.py", "weight": 1.0},
{"source": "n_transformer", "target": "n_layernorm", "relation": "contains", "confidence": "EXTRACTED", "source_file": "model.py", "weight": 1.0},
{"source": "n_attention", "target": "n_concept_attn", "relation": "implements", "confidence": "INFERRED", "source_file": "model.py", "weight": 0.8},
{"source": "n_layernorm", "target": "n_concept_attn", "relation": "referenced", "confidence": "AMBIGUOUS", "source_file": "paper.md", "weight": 0.5}
],
"input_tokens": 1200,
"output_tokens": 340
}
+1
View File
@@ -0,0 +1 @@
#import "Widget.h"
+4
View File
@@ -0,0 +1,4 @@
@interface Widget
- (void)render;
- (void)refresh;
@end
+9
View File
@@ -0,0 +1,9 @@
#import "Widget.h"
@implementation Widget
- (void)render {
[self refresh];
}
- (void)refresh {
}
@end
+5
View File
@@ -0,0 +1,5 @@
extension Widget {
func describe() -> String {
return "widget"
}
}
+18
View File
@@ -0,0 +1,18 @@
unit BaseGadget;
interface
type
TBaseGadget = class(TObject)
public
procedure Prepare;
end;
implementation
procedure TBaseGadget.Prepare;
begin
{ base prepare }
end;
end.
+21
View File
@@ -0,0 +1,21 @@
unit DerivedGadget;
interface
uses
BaseGadget;
type
TDerivedGadget = class(TBaseGadget)
public
procedure Run;
end;
implementation
procedure TDerivedGadget.Run;
begin
Prepare;
end;
end.
+18
View File
@@ -0,0 +1,18 @@
unit OtherGadget;
interface
type
TOtherGadget = class(TObject)
public
procedure Prepare;
end;
implementation
procedure TOtherGadget.Prepare;
begin
{ unrelated prepare }
end;
end.
+41
View File
@@ -0,0 +1,41 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 256
typedef struct {
int width;
int height;
} Rectangle;
static int validate(const char *input) {
return input != NULL && strlen(input) > 0;
}
char *process(const char *input) {
if (!validate(input)) {
return NULL;
}
char *result = malloc(MAX_SIZE);
strncpy(result, input, MAX_SIZE - 1);
return result;
}
Rectangle *make_rect(Rectangle *defaults) {
Rectangle *r = malloc(sizeof(Rectangle));
if (defaults) {
r->width = defaults->width;
r->height = defaults->height;
}
return r;
}
int main(int argc, char *argv[]) {
char *out = process("hello");
if (out) {
printf("%s\n", out);
free(out);
}
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
public with sharing class AccountService {
private static final String DEFAULT_TYPE = 'Customer';
public interface Notifiable {
void notify(String message);
}
public enum AccountStatus { ACTIVE, INACTIVE, PENDING }
@AuraEnabled
public static List<Account> getAccounts(String accountType) {
return [SELECT Id, Name, Type FROM Account WHERE Type = :accountType];
}
@future
public static void updateAccountsAsync(List<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account acc : accounts) {
acc.Type = DEFAULT_TYPE;
}
update accounts;
}
@InvocableMethod(label='Create Account' description='Creates a new Account')
public static List<Id> createAccounts(List<String> names) {
List<Account> toInsert = new List<Account>();
for (String n : names) {
toInsert.add(new Account(Name = n));
}
insert toInsert;
List<Id> ids = new List<Id>();
for (Account a : toInsert) {
ids.add(a.Id);
}
return ids;
}
public static void deleteOldAccounts(Date cutoff) {
List<Account> old = [SELECT Id FROM Account WHERE CreatedDate < :cutoff];
delete old;
}
@isTest
static void testGetAccounts() {
List<Account> result = getAccounts('Customer');
System.assertNotEquals(null, result);
}
@isTest
static void testCreateAccounts() {
List<Id> ids = createAccounts(new List<String>{'Test'});
System.assertEquals(1, ids.size());
}
}
+55
View File
@@ -0,0 +1,55 @@
#include <iostream>
#include <string>
#include <vector>
class HttpClient {
public:
HttpClient(const std::string& baseUrl) : baseUrl_(baseUrl) {}
std::string get(const std::string& path) {
return buildRequest("GET", path);
}
std::string post(const std::string& path, const std::string& body) {
return buildRequest("POST", path);
}
private:
std::string baseUrl_;
std::vector<std::string> tags_;
std::string buildRequest(const std::string& method, const std::string& path) {
return method + " " + baseUrl_ + path;
}
};
class AuthedHttpClient : public HttpClient {
public:
AuthedHttpClient(const std::string& baseUrl, const std::string& token)
: HttpClient(baseUrl), token_(token) {}
private:
std::string token_;
};
struct RetryingHttpClient : HttpClient {
int maxRetries;
};
template <typename T>
class Connection {
public:
T resource;
};
class PooledClient : public Connection<HttpClient> {
public:
int poolSize;
};
int main() {
HttpClient client("https://api.example.com");
std::string response = client.get("/users");
std::cout << response << std::endl;
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace GraphifyDemo
{
public interface IProcessor
{
List<string> Process(List<string> items);
}
public class Processor
{
}
public class Result<T>
{
}
public class DataProcessor : Processor, IProcessor
{
private readonly HttpClient _client;
public Processor Owner { get; set; }
public List<Processor> Workers { get; set; }
public DataProcessor()
{
_client = new HttpClient();
}
public List<string> Process(List<string> items)
{
return Validate(items);
}
public Result<DataProcessor> Build(HttpClient client)
{
return null;
}
private List<string> Validate(List<string> items)
{
var result = new List<string>();
foreach (var item in items)
{
if (!string.IsNullOrEmpty(item))
result.Add(item.Trim());
}
return result;
}
}
}
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="FluentValidation" Version="11.9.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Domain\Domain.csproj" />
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
</Project>
+30
View File
@@ -0,0 +1,30 @@
#include <cstdio>
#include <vector>
struct Vec3 {
float x;
float y;
float z;
};
__device__ float dot(const Vec3& a, const Vec3& b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
__global__ void saxpy(int n, float a, const float* x, float* y) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
y[i] = a * x[i] + y[i];
}
}
float host_norm(const Vec3& v) {
return dot(v, v);
}
int main() {
Vec3 v{1.0f, 2.0f, 3.0f};
float n = host_norm(v);
saxpy<<<1, 256>>>(256, 2.0f, nullptr, nullptr);
return 0;
}
+28
View File
@@ -0,0 +1,28 @@
object MainForm: TMainForm
Left = 100
Top = 100
Width = 640
Height = 480
Caption = 'Sample Form'
OnCreate = FormCreate
OnDestroy = FormDestroy
object Panel1: TPanel
Align = alTop
Height = 40
object ButtonOK: TButton
Caption = 'OK'
OnClick = ButtonOKClick
end
object ButtonCancel: TButton
Caption = 'Cancel'
OnClick = ButtonCancelClick
end
end
object Memo1: TMemo
Align = alClient
OnChange = Memo1Change
end
object StatusBar1: TStatusBar
Align = alBottom
end
end
+35
View File
@@ -0,0 +1,35 @@
#include "helpers.dm"
var/global_counter = 0
/proc/log_event(msg)
world.log << msg
global_counter++
/datum/weapon
var/damage = 10
var/name = "weapon"
proc/attack(mob/target)
log_event("attack")
target.take_damage(damage)
return damage
New()
log_event("weapon created")
/datum/weapon/sword
damage = 20
name = "sword"
/datum/weapon/sword/proc/sharpen()
damage += 5
log_event("sharpened")
/datum/weapon/sword/attack(mob/target)
sharpen()
return ..()
/proc/RunTest()
var/datum/weapon/sword/s = new /datum/weapon/sword()
s.attack(null)
+57
View File
@@ -0,0 +1,57 @@
window "mapwindow"
elem "mapwindow"
type = MAIN
pos = 0,0
size = 640x480
is-pane = true
elem "map"
type = MAP
pos = 0,0
size = 640x480
anchor1 = 0,0
anchor2 = 100,100
is-default = true
window "infowindow"
elem "infowindow"
type = MAIN
pos = 0,0
size = 640x480
is-pane = true
elem "info"
type = CHILD
pos = 0,30
size = 640x445
anchor1 = 0,0
anchor2 = 100,100
left = "statwindow"
right = "outputwindow"
is-vert = false
window "outputwindow"
elem "outputwindow"
type = MAIN
pos = 0,0
size = 640x480
is-pane = true
elem "output"
type = OUTPUT
pos = 0,0
size = 640x480
anchor1 = 0,0
anchor2 = 100,100
is-default = true
window "statwindow"
elem "statwindow"
type = MAIN
pos = 0,0
size = 640x480
is-pane = true
elem "stat"
type = INFO
pos = 0,0
size = 640x480
anchor1 = 0,0
anchor2 = 100,100
is-default = true
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 227 B

+14
View File
@@ -0,0 +1,14 @@
"a" = (/turf/closed/wall)
"b" = (/obj/structure/table,/area/station/maintenance)
"c" = (/obj/item/weapon/sword{name = "longsword"; damage = 25},/turf/open/floor/plating)
"d" = (
/obj/structure/table,
/obj/item/weapon/sword,
/turf/open/floor/plating,
/area/station/maintenance)
(1,1,1) = {"
aabb
acdb
aaaa
"}
+29
View File
@@ -0,0 +1,29 @@
defmodule MyApp.Accounts.User do
@moduledoc """
Handles user accounts and authentication.
"""
alias MyApp.Repo
alias MyApp.Schemas.{Account, Token}
import Ecto.Query
defstruct [:id, :name, :email]
def create(attrs) do
%__MODULE__{}
|> validate(attrs)
|> Repo.insert()
end
def find(id) do
Repo.get(__MODULE__, id)
end
defp validate(user, attrs) do
if Map.has_key?(attrs, :email) do
user
else
{:error, :missing_email}
end
end
end
+70
View File
@@ -0,0 +1,70 @@
module geometry
use constants
implicit none
real, parameter :: PI = 3.14159
type :: Point
real :: x
real :: y
end type Point
contains
subroutine circle_area(radius, area)
real, intent(in) :: radius
real, intent(out) :: area
area = PI * radius * radius
end subroutine circle_area
function distance(x1, y1, x2, y2) result(d)
real, intent(in) :: x1, y1, x2, y2
real :: d
d = sqrt((x2 - x1)**2 + (y2 - y1)**2)
end function distance
subroutine translate(p, dx, dy)
type(Point), intent(inout) :: p
real, intent(in) :: dx, dy
p%x = p%x + dx
p%y = p%y + dy
end subroutine translate
function origin() result(p)
type(Point) :: p
p%x = 0.0
p%y = 0.0
end function origin
subroutine print_area(radius)
real, intent(in) :: radius
real :: area
call circle_area(radius, area)
print *, "Area =", area
end subroutine print_area
function double_val(x) result(y)
real, intent(in) :: x
real :: y
y = x * 2.0
end function double_val
subroutine report(radius)
real, intent(in) :: radius
real :: scaled
scaled = double_val(radius)
print *, scaled
end subroutine report
end module geometry
program main
use geometry
implicit none
real :: r, a
r = 5.0
call circle_area(r, a)
print *, "Circle area:", a
end program main
+55
View File
@@ -0,0 +1,55 @@
package main
import (
"fmt"
"net/http"
)
type Server struct {
port int
}
func NewServer(port int) *Server {
return &Server{port: port}
}
func (s *Server) Start() error {
return http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil)
}
func (s *Server) Stop() {
fmt.Println("stopped")
}
type Logger interface {
Log(msg string)
}
type Reader interface {
Read() string
}
type ReaderLogger interface {
Logger
Reader
}
type BaseProcessor struct{}
type Result struct {
value int
}
type DataProcessor struct {
BaseProcessor
current *Result
}
func (d *DataProcessor) Build(input *DataProcessor) (*Result, error) {
return nil, nil
}
func main() {
s := NewServer(8080)
s.Start()
}
+35
View File
@@ -0,0 +1,35 @@
package com.nicklastrange.example
import com.nicklastrange.Processor
import com.nicklastrange.util.Helper
class SampleService {
Processor processor
SampleService(Processor processor) {
this.processor = processor
}
String process(String input) {
def result = processor.transform(input)
return Helper.clean(result)
}
private void reset() {
processor.reset()
}
}
interface Resettable {
void reset()
}
class ExtendedService extends SampleService implements Resettable {
ExtendedService(Processor processor) {
super(processor)
}
void reset() {
// no-op
}
}
+52
View File
@@ -0,0 +1,52 @@
import java.util.List;
import java.util.ArrayList;
class BaseProcessor {}
class Result<T> {}
public class DataProcessor extends BaseProcessor implements Processor {
private List<String> items;
public DataProcessor() {
this.items = new ArrayList<>();
}
public void addItem(String item) {
items.add(item);
}
public List<String> process() {
return validate(items);
}
@Override
public Result<DataProcessor> build(HttpClient client) {
return null;
}
private List<String> validate(List<String> data) {
List<String> result = new ArrayList<>();
for (String s : data) {
if (s != null && !s.isEmpty()) {
result.add(s.trim());
}
}
return result;
}
}
interface Processor {
List<String> process();
}
enum ErrorCode {
OK(0),
GAME_DONE(1001);
private final int code;
ErrorCode(int code) {
this.code = code;
}
}
+35
View File
@@ -0,0 +1,35 @@
module Geometry
using LinearAlgebra
import Base: show
using Base.Threads
using ..ParentModule
abstract type Shape end
struct Point <: Shape
x::Float64
y::Float64
end
mutable struct Circle <: Shape
center::Point
radius::Float64
end
function area(c::Circle)
return pi * c.radius^2
end
function distance(p1::Point, p2::Point)
return norm([p1.x - p2.x, p1.y - p2.y])
end
perimeter(c::Circle) = 2 * pi * c.radius
function describe(s::Shape)
show(s)
area(s)
end
end
+16
View File
@@ -0,0 +1,16 @@
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"test": "jest",
"start": "node dist/index.js"
},
"dependencies": {
"react": "^18.0.0",
"axios": "^1.6.0"
},
"devDependencies": {
"typescript": "^5.0.0"
}
}
+49
View File
@@ -0,0 +1,49 @@
import kotlinx.coroutines.delay
import kotlin.math.max
data class Config(val baseUrl: String, val timeout: Int)
class HttpClient(private val config: Config) {
fun get(path: String): String {
return buildRequest("GET", path)
}
fun post(path: String, body: String): String {
return buildRequest("POST", path)
}
private fun buildRequest(method: String, path: String): String {
return "$method ${config.baseUrl}$path"
}
}
interface Loggable {
fun log()
}
open class BaseProcessor
class Result<T>
class DataProcessor : BaseProcessor(), Loggable {
var current: Result<DataProcessor> = Result()
fun run(input: DataProcessor): Result<DataProcessor> {
return current
}
override fun log() {}
}
class LoggingList<T>(inner: MutableList<T>) : MutableList<T> by inner
fun createClient(baseUrl: String): HttpClient {
val config = Config(baseUrl, 30)
return HttpClient(config)
}
enum class ChatType {
NORMAL,
GROUP,
SYSTEM
}
+30
View File
@@ -0,0 +1,30 @@
object SampleForm: TSampleForm
Left = 100
Top = 100
Caption = 'Sample Form'
ClientHeight = 300
ClientWidth = 400
object PanelMain: TPanel
Left = 0
Top = 0
Width = 400
Height = 260
object ButtonOK: TButton
Left = 160
Top = 220
Width = 75
Height = 25
Caption = 'OK'
OnClick = ButtonOKClick
end
object LabelTitle: TLabel
Left = 10
Top = 10
Caption = 'Title'
end
end
object TimerRefresh: TTimer
Interval = 1000
OnTimer = TimerRefreshTimer
end
end
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<Package Version="5">
<Name Value="SamplePackage"/>
<Description Value="A sample Lazarus package"/>
<Files Count="2">
<Item1>
<Filename Value="sample.pas"/>
<UnitName Value="sample"/>
</Item1>
<Item2>
<Filename Value="sampleutils.pas"/>
<UnitName Value="sampleutils"/>
</Item2>
</Files>
<RequiredPkgs Count="2">
<Item1>
<PackageName Value="FCL"/>
</Item1>
<Item2>
<PackageName Value="LCL"/>
</Item2>
</RequiredPkgs>
</Package>
</CONFIG>
+35
View File
@@ -0,0 +1,35 @@
-- Luau sample (Roblox): typed Lua superset.
-- tree-sitter-lua doesn't parse the type annotations, but extracts
-- function declarations and call edges fine.
local Server = {}
Server.__index = Server
type ServerConfig = {
port: number,
name: string?,
}
function Server.new(config: ServerConfig): Server
local self = setmetatable({}, Server)
self.port = config.port
self.name = config.name or "default"
return self
end
function Server:start(): ()
print(string.format("listening on :%d", self.port))
end
function Server:stop(): ()
print("stopped")
end
local function main()
local s = Server.new({ port = 8080 })
s:start()
end
main()
return Server
+54
View File
@@ -0,0 +1,54 @@
#import <Foundation/Foundation.h>
#import "SampleDelegate.h"
@interface Animal : NSObject <SampleDelegate>
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
- (void)speak;
@end
@implementation Animal
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = name;
}
return self;
}
- (void)speak {
NSLog(@"%@ makes a sound.", self.name);
}
@end
@interface Dog : Animal
- (void)fetch;
@end
@implementation Dog
- (void)fetch {
[self speak];
NSLog(@"%@ fetches the ball!", self.name);
}
@end
@protocol Base
- (void)baseMethod;
@end
@protocol Derived <Base>
- (void)derivedMethod;
@end
+26
View File
@@ -0,0 +1,26 @@
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp/workspace"],
"env": {
"FILESYSTEM_ROOT": "/tmp/workspace"
}
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github@0.6.2"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_PLACEHOLDER_NOT_A_REAL_TOKEN"
}
},
"time": {
"command": "uvx",
"args": ["mcp-server-time", "--local-timezone=UTC"]
}
}
}
+5
View File
@@ -0,0 +1,5 @@
# Attention Is All You Need
The transformer architecture uses multi-head attention.
Layer normalization is applied before each sub-layer.
The feed-forward network consists of two linear transformations.
+21
View File
@@ -0,0 +1,21 @@
#include <metal_stdlib>
using namespace metal;
struct Vec3 {
float x;
float y;
float z;
};
float dot3(Vec3 a, Vec3 b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
kernel void saxpy(
device const float* x [[buffer(0)]],
device float* y [[buffer(1)]],
constant float& a [[buffer(2)]],
uint id [[thread_position_in_grid]]
) {
y[id] = a * x[id] + y[id];
}
+71
View File
@@ -0,0 +1,71 @@
unit SampleUnit;
interface
uses
SysUtils, Classes;
type
IProcessor = interface
procedure Process;
function GetCount: Integer;
end;
TBaseProcessor = class(TObject)
public
procedure Initialize; virtual;
function GetCount: Integer; virtual;
end;
TDataProcessor = class(TBaseProcessor, IProcessor)
private
FCount: Integer;
public
constructor Create;
procedure Initialize; override;
procedure Process;
function GetCount: Integer; override;
procedure Reset;
end;
implementation
procedure TBaseProcessor.Initialize;
begin
{ base init }
end;
function TBaseProcessor.GetCount: Integer;
begin
Result := 0;
end;
constructor TDataProcessor.Create;
begin
inherited;
FCount := 0;
end;
procedure TDataProcessor.Initialize;
begin
inherited Initialize;
FCount := 0;
end;
procedure TDataProcessor.Process;
begin
Inc(FCount);
Reset;
end;
function TDataProcessor.GetCount: Integer;
begin
Result := FCount;
end;
procedure TDataProcessor.Reset;
begin
FCount := 0;
end;
end.
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Http;
use App\Auth\Authenticator;
use App\Cache\CacheManager;
class ApiClient
{
private string $baseUrl;
private Authenticator $auth;
public function __construct(string $baseUrl)
{
$this->baseUrl = $baseUrl;
$this->auth = new Authenticator();
}
public function get(string $path): string
{
return $this->fetch($path, 'GET');
}
public function post(string $path, string $body): string
{
return $this->fetch($path, 'POST');
}
private function fetch(string $path, string $method): string
{
$token = $this->auth->getToken();
return $method . ' ' . $this->baseUrl . $path;
}
}
interface Loggable
{
public function log(): void;
}
trait HasName
{
public function getName(): string
{
return '';
}
}
class BaseProcessor {}
class Result {}
class DataProcessor extends BaseProcessor implements Loggable
{
use HasName;
private Result $current;
public function run(DataProcessor $input): Result
{
return new Result();
}
public function log(): void
{
}
}
class Service
{
public function __construct(private Result $result, string $label)
{
}
}
function parseResponse(string $raw): array
{
return json_decode($raw, true);
}
+48
View File
@@ -0,0 +1,48 @@
using namespace System.IO
using module MyModule
function Get-Data {
param(
[string]$Name,
[int]$Count = 10
)
$result = Process-Items -Name $Name -Count $Count
return $result
}
function Process-Items {
param([string]$Name, [int]$Count)
Write-Output "Processing $Count items for $Name"
}
class DataProcessor {
[string]$Source
DataProcessor([string]$source) {
$this.Source = $source
}
[string] Transform([string]$input) {
return $input.ToUpper()
}
[void] Save([string]$path) {
Set-Content -Path $path -Value $this.Source
}
}
class Shape {
[string]$Kind
[double] Area() {
return 0.0
}
}
class Circle : Shape {
[double]$Radius
[double] Area() {
return 3.14159 * $this.Radius * $this.Radius
}
}
+13
View File
@@ -0,0 +1,13 @@
@{
RootModule = 'MyModule.psm1'
ModuleVersion = '1.0.0'
GUID = 'aaaabbbb-cccc-dddd-eeee-ffffffffffff'
Author = 'Test Author'
Description = 'A sample module manifest for graphify tests.'
NestedModules = @('Helpers.psm1', 'Logger.psm1')
RequiredModules = @(
'PSReadLine',
@{ ModuleName = 'Pester'; ModuleVersion = '5.0' }
)
FunctionsToExport = @('Get-Data', 'Process-Items')
}
+6
View File
@@ -0,0 +1,6 @@
class Transformer:
def __init__(self, d_model: int):
self.d_model = d_model
def forward(self, x):
return x
+36
View File
@@ -0,0 +1,36 @@
@page "/counter"
@using Microsoft.AspNetCore.Components
@using MyApp.Services
@inject ICounterService CounterService
@inject NavigationManager Navigation
@inherits ComponentBase
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<Button OnClick="IncrementCount">Click me</Button>
<WeatherDisplay City="@city" />
<DataGrid TItem="CounterRecord" Items="@records" />
@code {
private int currentCount = 0;
private string city = "Seattle";
private List<CounterRecord> records = new();
private void IncrementCount()
{
currentCount++;
CounterService.Increment();
}
public async Task LoadData()
{
records = await CounterService.GetRecords();
}
protected override async Task OnInitializedAsync()
{
await LoadData();
}
}
+33
View File
@@ -0,0 +1,33 @@
require 'json'
require 'net/http'
class ApiClient
def initialize(base_url)
@base_url = base_url
end
def get(path)
fetch(path, 'GET')
end
def post(path, body)
fetch(path, 'POST')
end
private
def fetch(path, method)
uri = URI(@base_url + path)
Net::HTTP.get(uri)
end
end
class TimeoutApiClient < ApiClient
def fetch(path, method)
super
end
end
def parse_response(raw)
JSON.parse(raw)
end
+60
View File
@@ -0,0 +1,60 @@
use std::collections::HashMap;
struct Graph {
nodes: HashMap<String, Vec<String>>,
}
impl Graph {
fn new() -> Self {
Graph { nodes: HashMap::new() }
}
fn add_node(&mut self, id: String) {
self.nodes.insert(id, vec![]);
}
fn add_edge(&mut self, src: String, tgt: String) {
self.nodes.entry(src).or_default().push(tgt);
}
}
fn build_graph(edges: Vec<(String, String)>) -> Graph {
let mut g = Graph::new();
for (src, tgt) in edges {
g.add_edge(src, tgt);
}
g
}
trait Processor {
fn run(&self);
}
trait Logger: Processor {
fn log(&self);
}
struct Result<T> {
value: T,
}
struct DataProcessor {
current: Result<DataProcessor>,
}
impl Processor for DataProcessor {
fn run(&self) {}
}
impl DataProcessor {
fn build(input: DataProcessor) -> Result<DataProcessor> {
Result { value: input }
}
}
enum GraphEvent {
NodeAdded(Graph),
Processed { proc: DataProcessor },
}
struct GraphPair(Graph, Result<DataProcessor>);
+29
View File
@@ -0,0 +1,29 @@
import scala.collection.mutable.ListBuffer
case class Config(baseUrl: String, timeout: Int)
trait Loggable
abstract class BaseClient
class HttpClient(config: Config) extends BaseClient with Loggable {
val source: Config = config
var fallback: BaseClient = null
def get(path: String): String = {
buildRequest("GET", path)
}
def post(path: String, body: String): String = {
buildRequest("POST", path)
}
private def buildRequest(method: String, path: String): String = {
s"$method ${config.baseUrl}$path"
}
}
object HttpClientFactory {
def create(baseUrl: String): HttpClient = {
new HttpClient(Config(baseUrl, 30))
}
}
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
source ./helpers.sh
export APP_ENV="production"
build() {
echo "Building..."
local out_dir="dist"
mkdir -p "$out_dir"
}
test_suite() {
echo "Running tests..."
build
}
deploy() {
build
test_suite
echo "Deploying to $APP_ENV"
}
+20
View File
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi", "src\WebApi\WebApi.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}"
ProjectSection(ProjectDependencies) = postProject
{B2C3D4E5-F6A7-8901-BCDE-F12345678901} = {B2C3D4E5-F6A7-8901-BCDE-F12345678901}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Domain", "src\Domain\Domain.csproj", "{B2C3D4E5-F6A7-8901-BCDE-F12345678901}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "tests\Tests\Tests.csproj", "{C3D4E5F6-A7B8-9012-CDEF-123456789012}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
EndGlobal
+7
View File
@@ -0,0 +1,7 @@
<Solution>
<Project Path="src/Domain/Domain.csproj" />
<Project Path="src/WebApi/WebApi.csproj">
<BuildDependency Project="src/Domain/Domain.csproj" />
</Project>
<Project Path="tests/Tests/Tests.csproj" />
</Solution>
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE organizations (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
org_id INT REFERENCES organizations(id)
);
CREATE VIEW active_users AS
SELECT * FROM users WHERE active = true;
CREATE FUNCTION get_user(user_id INT) RETURNS users AS $$
BEGIN
RETURN QUERY SELECT * FROM users WHERE id = user_id;
END;
$$ LANGUAGE plpgsql;
+44
View File
@@ -0,0 +1,44 @@
package math_pkg;
endpackage
interface class Processor;
endclass
class BaseProcessor;
endclass
class Payload;
endclass
class Config;
endclass
class Result #(type T = Payload);
T value;
endclass
class DataProcessor extends BaseProcessor implements Processor;
Result #(Payload) current;
rand Config m_cfg;
protected BaseProcessor m_parent;
function Result #(Payload) build(Payload input);
return current;
endfunction
endclass
module leaf;
endmodule
module top;
import math_pkg::*;
function int add(input int a, input int b);
return a + b;
endfunction
task tick;
endtask
leaf u_leaf();
endmodule
+83
View File
@@ -0,0 +1,83 @@
import Foundation
import UIKit
protocol Processor {
func process() -> [String]
}
protocol Loggable {
func log()
}
class BaseProcessor {}
class Result<T> {}
class DataProcessor: BaseProcessor, Processor {
private var items: [String] = []
var current: Result<DataProcessor> = Result<DataProcessor>()
init() {}
deinit {}
func addItem(_ item: String) {
items.append(item)
}
func process() -> [String] {
return validate(items)
}
func run(input: DataProcessor) -> Result<DataProcessor> {
return current
}
private func validate(_ data: [String]) -> [String] {
return data.filter { !$0.isEmpty }
}
}
struct Config {
let baseUrl: String
let timeout: Int
subscript(key: String) -> String? {
return nil
}
}
enum NetworkError {
case timeout
case connectionFailed
case unauthorized
case failed(Config)
func describe() -> String {
return "error"
}
}
actor CacheManager {
private var store: [String: String] = [:]
func get(_ key: String) -> String? {
return store[key]
}
}
extension DataProcessor: Loggable {
func log() {
print("logging")
}
}
extension Config {
func isValid() -> Bool {
return !baseUrl.isEmpty
}
}
func createProcessor() -> DataProcessor {
return DataProcessor()
}
+8
View File
@@ -0,0 +1,8 @@
trigger AccountTrigger on Account (before insert, before update, after insert, after update) {
if (Trigger.isBefore) {
AccountService.validateAccounts(Trigger.new);
}
if (Trigger.isAfter && Trigger.isInsert) {
AccountService.sendWelcomeNotifications(Trigger.new);
}
}
+23
View File
@@ -0,0 +1,23 @@
import { Response } from './models';
class HttpClient {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async get(path: string): Promise<Response> {
return fetch(this.baseUrl + path);
}
async post(path: string, body: unknown): Promise<Response> {
return this.get(path);
}
}
function buildHeaders(token: string): Record<string, string> {
return { Authorization: `Bearer ${token}` };
}
export { HttpClient, buildHeaders };
+18
View File
@@ -0,0 +1,18 @@
function fmtDate(d: Date): string {
return d.toISOString();
}
function fmtCount(n: number): string {
return `${n} items`;
}
export function App() {
const now = new Date();
return (
<div className="app">
<h1>Header</h1>
<span>{fmtDate(now)}</span>
<span>{fmtCount(42)}</span>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
<Window x:Class="GraphifyDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Dashboard"
Loaded="Window_Loaded">
<StackPanel x:Name="RootPanel">
<TextBox Name="UserNameBox" Text="{Binding UserName}" TextChanged="UserNameChanged" />
<Button x:Name="SaveButton" Content="Save" Click="Save_Click" />
</StackPanel>
</Window>
+19
View File
@@ -0,0 +1,19 @@
using System.Windows;
namespace GraphifyDemo
{
public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void UserNameChanged(object sender, RoutedEventArgs e)
{
}
private void Save_Click(object sender, RoutedEventArgs e)
{
}
}
}
+37
View File
@@ -0,0 +1,37 @@
const std = @import("std");
const mem = @import("std").mem;
const Point = struct {
x: f64,
y: f64,
pub fn distance(self: Point, other: Point) f64 {
const dx = self.x - other.x;
const dy = self.y - other.dy;
return std.math.sqrt(dx * dx + dy * dy);
}
};
const Color = enum {
red,
green,
blue,
};
const Shape = union(enum) {
circle: f64,
rect: Point,
};
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn multiply(a: i32, b: i32) i32 {
return a * b;
}
pub fn main() void {
const result = add(1, 2);
_ = multiply(result, 3);
}
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT,
total NUMERIC
);
ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id);
+26
View File
@@ -0,0 +1,26 @@
"""Fixture: functions and methods that call each other - for call-graph extraction tests."""
def compute_score(data):
return sum(data)
def normalize(value):
return value / 100.0
def run_analysis(data):
score = compute_score(data)
return normalize(score)
class Analyzer:
def process(self, data):
return run_analysis(data)
def score(self, data):
return compute_score(data)
def full_pipeline(self, data):
raw = self.score(data)
return normalize(raw)
+10
View File
@@ -0,0 +1,10 @@
Import-Module Foo
Import-Module -Name Bar.psm1
. ./Shared.psm1
. .\Utils.ps1
function Invoke-Main {
Import-Module InnerMod
. ./InnerShared.psm1
Get-Data
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Support;
class Throttle
{
public const int DEFAULT_PER_SECOND = 60;
public const int DEFAULT_PER_DAY = 10000;
}
class RateLimiter
{
public function perSecond(): int
{
return (int) config('throttle.api.per_second', 60);
}
public function perDay(): int
{
return (int) config('throttle.api.per_day', 10000);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Providers;
class PaymentGateway {}
class StripeGateway {}
class CashierGateway {}
class AppServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentGateway::class, StripeGateway::class);
$this->app->singleton(CashierGateway::class, StripeGateway::class);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Providers;
class UserRegistered {}
class OrderPlaced {}
class SendWelcomeEmail {}
class NotifyAdmins {}
class ShipOrder {}
class EventServiceProvider
{
protected $listen = [
UserRegistered::class => [
SendWelcomeEmail::class,
NotifyAdmins::class,
],
OrderPlaced::class => [
ShipOrder::class,
],
];
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Theme;
class DefaultPalette
{
public static string $primary = '#3366ff';
public static string $accent = '#ff6633';
}
class ColorResolver
{
public function primary(): string
{
return DefaultPalette::$primary;
}
public function accent(): string
{
return DefaultPalette::$accent;
}
}
+17
View File
@@ -0,0 +1,17 @@
#define NDIM 3
module shapes
#ifdef MPI
use mpi
#endif
implicit none
contains
subroutine compute_volume(side, vol)
real, intent(in) :: side
real, intent(out) :: vol
vol = side ** NDIM
end subroutine compute_volume
end module shapes
+11
View File
@@ -0,0 +1,11 @@
CREATE TABLE Sales.Customer (
CustomerID SERIAL PRIMARY KEY,
Name TEXT NOT NULL
);
CREATE TABLE Sales.SalesOrder (
OrderID SERIAL PRIMARY KEY,
CustomerID INT REFERENCES Sales.Customer(CustomerID)
);
ALTER TABLE Sales.SalesOrder ADD CONSTRAINT fk_cust FOREIGN KEY (CustomerID) REFERENCES Sales.Customer(CustomerID);
+60
View File
@@ -0,0 +1,60 @@
unit ScopedCallsUnit;
interface
type
TFirstWidget = class(TObject)
public
procedure Configure;
procedure Reset;
end;
TSecondWidget = class(TObject)
public
procedure Configure;
procedure Reset;
end;
TBaseWidget = class(TObject)
public
procedure Prepare;
end;
TDerivedWidget = class(TBaseWidget)
public
procedure Run;
end;
implementation
procedure TFirstWidget.Configure;
begin
Reset;
end;
procedure TFirstWidget.Reset;
begin
{ first reset }
end;
procedure TSecondWidget.Configure;
begin
Reset;
end;
procedure TSecondWidget.Reset;
begin
{ second reset }
end;
procedure TBaseWidget.Prepare;
begin
{ base prepare }
end;
procedure TDerivedWidget.Run;
begin
Prepare;
end;
end.
+42
View File
@@ -0,0 +1,42 @@
package com.nicklastrange.example
import spock.lang.Specification
class SampleSpec extends Specification {
def setup() {
// common setup
}
def "should process valid input"() {
given:
def input = "hello"
when:
def result = input.toUpperCase()
then:
result == "HELLO"
}
def "should not change value when it's already correct"() {
given:
def value = "HELLO"
when:
def result = value.toUpperCase()
then:
result == value
}
def "should handle #input and return #expected"() {
expect:
input.toUpperCase() == expected
where:
input | expected
"hello" | "HELLO"
"world" | "WORLD"
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "dist",
"strict": true
},
"include": ["src"]
}
+5
View File
@@ -0,0 +1,5 @@
export function getFromStorage(key: string): string | null {
return null;
}
export function setInStorage(key: string, value: string): void {}
+3
View File
@@ -0,0 +1,3 @@
extension Foo {
func two() {}
}
+3
View File
@@ -0,0 +1,3 @@
class Foo {
func one() {}
}
+73
View File
@@ -0,0 +1,73 @@
// Test fixture for upstream PR — exercises every new extraction path.
//
// Expected nodes after this PR:
// - IUserRepository (interface)
// - UserStatus (enum) + Active, Inactive (members)
// - UserId (type_alias)
// - USER_REPOSITORY (const, value=call_expression)
// - DEFAULT_ROLES (const, value=array)
// - USER_CONFIG (const, value=object)
// - UserService (class — already extracted by current code)
// - UserModule (class — already extracted)
//
// Expected edges after this PR:
// - UserService.create() --instantiates--> User
// - UserService.bulkCreate() --instantiates--> Array
// - UserModule --provides--> UserService
// - UserModule --provides--> USER_REPOSITORY (via { provide, useClass } detection — optional)
// - UserModule --exports--> UserService
import { Module, Injectable } from '@nestjs/common';
import type { User } from './user.entity';
export interface IUserRepository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
export enum UserStatus {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Suspended = 'SUSPENDED',
}
export type UserId = string;
export const USER_REPOSITORY = Symbol('USER_REPOSITORY');
export const DEFAULT_ROLES = ['admin', 'editor', 'user'] as const;
export const USER_CONFIG = {
maxRetries: 3,
timeoutMs: 5000,
features: {
twoFactor: true,
sso: false,
},
};
@Injectable()
export class UserService {
constructor(private repo: IUserRepository) {}
create(name: string): User {
return new User(name);
}
bulkCreate(names: string[]): User[] {
return names.map((n) => new User(n));
}
getById(id: string): Promise<User | null> {
return this.repo.findById(id);
}
}
@Module({
providers: [
UserService,
{ provide: USER_REPOSITORY, useClass: PrismaUserRepository },
],
exports: [UserService],
})
export class UserModule {}
+7
View File
@@ -0,0 +1,7 @@
export function getFullUrl(path: string): string {
return "https://example.com" + path;
}
export function basePathRewrite(url: string): string {
return url;
}
+5
View File
@@ -0,0 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
</PropertyGroup>
</Project>
@@ -0,0 +1,6 @@
namespace Demo.ViewModels
{
public class DesignViewModel
{
}
}
@@ -0,0 +1,6 @@
namespace Demo.ViewModels
{
public class MainViewModel
{
}
}
@@ -0,0 +1,5 @@
namespace Demo.ViewModels;
public class PrismOrderViewModel
{
}
@@ -0,0 +1,6 @@
namespace Demo.ViewModels
{
public class SettingsViewModel
{
}
}

Some files were not shown because too many files have changed in this diff Show More