Multi-language code converter contribution
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
"""Basic tests for CodeXchange AI application."""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
from src.ai_code_converter.config import SUPPORTED_LANGUAGES, DOCUMENT_STYLES
|
||||
|
||||
|
||||
def test_supported_languages():
|
||||
"""Test that supported languages configuration is valid."""
|
||||
assert isinstance(SUPPORTED_LANGUAGES, list)
|
||||
assert len(SUPPORTED_LANGUAGES) > 0
|
||||
assert "Python" in SUPPORTED_LANGUAGES
|
||||
|
||||
|
||||
def test_document_styles():
|
||||
"""Test that document styles configuration is valid."""
|
||||
assert isinstance(DOCUMENT_STYLES, dict)
|
||||
assert len(DOCUMENT_STYLES) > 0
|
||||
|
||||
# Check that each language has at least one document style
|
||||
for language in SUPPORTED_LANGUAGES:
|
||||
assert language in DOCUMENT_STYLES, f"{language} missing from document styles"
|
||||
assert isinstance(DOCUMENT_STYLES[language], list)
|
||||
assert len(DOCUMENT_STYLES[language]) > 0
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Test module for C# language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_csharp_detection():
|
||||
"""Test the C# language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample C# code
|
||||
csharp_code = """
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MyApp
|
||||
{
|
||||
// A simple C# class
|
||||
public class Person
|
||||
{
|
||||
// Properties
|
||||
public string Name { get; set; }
|
||||
public int Age { get; private set; }
|
||||
|
||||
// Constructor
|
||||
public Person(string name, int age)
|
||||
{
|
||||
Name = name;
|
||||
Age = age;
|
||||
}
|
||||
|
||||
// Method
|
||||
public string Greet()
|
||||
{
|
||||
return $"Hello, my name is {Name} and I am {Age} years old.";
|
||||
}
|
||||
|
||||
// Method with out parameter
|
||||
public bool TryParse(string input, out int result)
|
||||
{
|
||||
return int.TryParse(input, out result);
|
||||
}
|
||||
}
|
||||
|
||||
// Interface
|
||||
public interface IRepository<T> where T : class
|
||||
{
|
||||
Task<T> GetByIdAsync(int id);
|
||||
Task<IEnumerable<T>> GetAllAsync();
|
||||
Task AddAsync(T entity);
|
||||
}
|
||||
|
||||
// Async method
|
||||
public class DataProcessor
|
||||
{
|
||||
public async Task ProcessDataAsync()
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
Console.WriteLine("Data processed!");
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
// Variable declaration with var
|
||||
var person = new Person("John", 30);
|
||||
Console.WriteLine(person.Greet());
|
||||
|
||||
// LINQ query
|
||||
var numbers = new List<int> { 1, 2, 3, 4, 5 };
|
||||
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
|
||||
|
||||
// String interpolation
|
||||
string message = $"Found {evenNumbers.Count} even numbers.";
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_csharp(csharp_code) == True
|
||||
assert detector.detect_language(csharp_code) == "C#"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(csharp_code, "C#")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_csharp_detection()
|
||||
print("All C# detection tests passed!")
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Test module for Kotlin language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_kotlin_detection():
|
||||
"""Test the Kotlin language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Kotlin code
|
||||
kotlin_code = """
|
||||
package com.example.myapp
|
||||
|
||||
import android.os.Bundle
|
||||
import android.widget.Button
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import java.util.*
|
||||
|
||||
/**
|
||||
* Main Activity for the application
|
||||
*/
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
// Properties
|
||||
private lateinit var textView: TextView
|
||||
private lateinit var button: Button
|
||||
private val viewModel: MainViewModel by viewModels()
|
||||
private val job = Job()
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main + job)
|
||||
|
||||
// Immutable property
|
||||
val API_KEY: String = "abc123"
|
||||
|
||||
// Computed property
|
||||
val isActive: Boolean
|
||||
get() = viewModel.isActive && !isFinishing
|
||||
|
||||
// Data class
|
||||
data class User(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val email: String,
|
||||
var isActive: Boolean = true
|
||||
)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
// View binding
|
||||
textView = findViewById(R.id.textView)
|
||||
button = findViewById(R.id.button)
|
||||
|
||||
// Click listener
|
||||
button.setOnClickListener {
|
||||
fetchData()
|
||||
}
|
||||
|
||||
// Observe live data
|
||||
viewModel.userData.observe(this) { user ->
|
||||
updateUI(user)
|
||||
}
|
||||
|
||||
// Extension function call
|
||||
"Hello, Kotlin!".printDebug()
|
||||
|
||||
// Using when expression
|
||||
val result = when(viewModel.status) {
|
||||
Status.LOADING -> "Loading..."
|
||||
Status.SUCCESS -> "Success!"
|
||||
Status.ERROR -> "Error!"
|
||||
else -> "Unknown"
|
||||
}
|
||||
|
||||
textView.text = result
|
||||
}
|
||||
|
||||
// Suspend function
|
||||
private suspend fun fetchUserData(): User {
|
||||
return withContext(Dispatchers.IO) {
|
||||
// Simulate network delay
|
||||
delay(1000)
|
||||
User(1, "John Doe", "john@example.com")
|
||||
}
|
||||
}
|
||||
|
||||
// Coroutine usage
|
||||
private fun fetchData() {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
textView.text = "Loading..."
|
||||
val user = fetchUserData()
|
||||
updateUI(user)
|
||||
} catch (e: Exception) {
|
||||
textView.text = "Error: ${e.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Normal function
|
||||
private fun updateUI(user: User) {
|
||||
textView.text = "Welcome, ${user.name}!"
|
||||
|
||||
// Smart cast
|
||||
val info: Any = user.email
|
||||
if (info is String) {
|
||||
// No need to cast, Kotlin knows it's a String
|
||||
textView.text = info.toUpperCase()
|
||||
}
|
||||
|
||||
// Collection operations
|
||||
val numbers = listOf(1, 2, 3, 4, 5)
|
||||
val sum = numbers.filter { it % 2 == 0 }.sum()
|
||||
|
||||
// String template
|
||||
val message = "Sum of even numbers: $sum"
|
||||
println(message)
|
||||
}
|
||||
|
||||
// Higher-order function
|
||||
private inline fun performOperation(
|
||||
value: Int,
|
||||
operation: (Int) -> Int
|
||||
): Int {
|
||||
return operation(value)
|
||||
}
|
||||
|
||||
// Companion object
|
||||
companion object {
|
||||
const val TAG = "MainActivity"
|
||||
|
||||
fun newInstance(): MainActivity {
|
||||
return MainActivity()
|
||||
}
|
||||
}
|
||||
|
||||
// Enum class
|
||||
enum class Status {
|
||||
LOADING,
|
||||
SUCCESS,
|
||||
ERROR
|
||||
}
|
||||
|
||||
// Interface definition
|
||||
interface OnDataLoadListener {
|
||||
fun onDataLoaded(data: Any)
|
||||
fun onError(message: String)
|
||||
}
|
||||
|
||||
// Object declaration (singleton)
|
||||
object Logger {
|
||||
fun log(message: String) {
|
||||
println("[$TAG] $message")
|
||||
}
|
||||
}
|
||||
|
||||
// Extension function
|
||||
fun String.printDebug() {
|
||||
println("Debug: $this")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
job.cancel() // Cancel coroutines when activity is destroyed
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_kotlin(kotlin_code) == True
|
||||
assert detector.detect_language(kotlin_code) == "Kotlin"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(kotlin_code, "Kotlin")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_kotlin_detection()
|
||||
print("All Kotlin detection tests passed!")
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Test module for Lua language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_lua_detection():
|
||||
"""Test the Lua language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Lua code
|
||||
lua_code = """
|
||||
-- Simple Lua script
|
||||
local function factorial(n)
|
||||
if n == 0 then
|
||||
return 1
|
||||
else
|
||||
return n * factorial(n - 1)
|
||||
end
|
||||
end
|
||||
|
||||
-- Variables
|
||||
local name = "John"
|
||||
local age = 30
|
||||
local is_active = true
|
||||
local value = nil
|
||||
|
||||
-- Table creation
|
||||
local person = {
|
||||
name = "John",
|
||||
age = 30,
|
||||
email = "john@example.com",
|
||||
greet = function(self)
|
||||
return "Hello, " .. self.name
|
||||
end
|
||||
}
|
||||
|
||||
-- Accessing table properties
|
||||
print(person.name)
|
||||
print(person["age"])
|
||||
print(person:greet())
|
||||
|
||||
-- Metatables
|
||||
local mt = {
|
||||
__add = function(a, b)
|
||||
return { value = a.value + b.value }
|
||||
end
|
||||
}
|
||||
|
||||
local obj1 = { value = 10 }
|
||||
local obj2 = { value = 20 }
|
||||
setmetatable(obj1, mt)
|
||||
local result = obj1 + obj2
|
||||
print(result.value) -- 30
|
||||
|
||||
-- Control structures
|
||||
for i = 1, 10 do
|
||||
print(i)
|
||||
end
|
||||
|
||||
local fruits = {"apple", "banana", "orange"}
|
||||
for i, fruit in ipairs(fruits) do
|
||||
print(i, fruit)
|
||||
end
|
||||
|
||||
for key, value in pairs(person) do
|
||||
if type(value) ~= "function" then
|
||||
print(key, value)
|
||||
end
|
||||
end
|
||||
|
||||
local count = 1
|
||||
while count <= 5 do
|
||||
print(count)
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
-- Using modules
|
||||
local math = require("math")
|
||||
print(math.floor(3.14))
|
||||
print(math.random())
|
||||
|
||||
-- String operations
|
||||
local message = "Hello, " .. name .. "!"
|
||||
print(message)
|
||||
print(string.upper(message))
|
||||
print(string.sub(message, 1, 5))
|
||||
print(string.find(message, "Hello"))
|
||||
|
||||
-- Multiple return values
|
||||
local function get_person()
|
||||
return "John", 30, true
|
||||
end
|
||||
|
||||
local name, age, active = get_person()
|
||||
print(name, age, active)
|
||||
|
||||
-- Closures
|
||||
local function counter()
|
||||
local count = 0
|
||||
return function()
|
||||
count = count + 1
|
||||
return count
|
||||
end
|
||||
end
|
||||
|
||||
local c1 = counter()
|
||||
print(c1()) -- 1
|
||||
print(c1()) -- 2
|
||||
|
||||
-- Error handling
|
||||
local status, err = pcall(function()
|
||||
error("Something went wrong")
|
||||
end)
|
||||
|
||||
if not status then
|
||||
print("Error:", err)
|
||||
end
|
||||
|
||||
-- Coroutines
|
||||
local co = coroutine.create(function()
|
||||
for i = 1, 3 do
|
||||
print("Coroutine", i)
|
||||
coroutine.yield()
|
||||
end
|
||||
end)
|
||||
|
||||
coroutine.resume(co) -- Coroutine 1
|
||||
coroutine.resume(co) -- Coroutine 2
|
||||
coroutine.resume(co) -- Coroutine 3
|
||||
|
||||
-- Multi-line strings
|
||||
local multi_line = [[
|
||||
This is a multi-line
|
||||
string in Lua.
|
||||
It can contain "quotes" without escaping.
|
||||
]]
|
||||
print(multi_line)
|
||||
|
||||
-- Bit operations (Lua 5.3+)
|
||||
local a = 10 -- 1010 in binary
|
||||
local b = 6 -- 0110 in binary
|
||||
print(a & b) -- AND: 0010 = 2
|
||||
print(a | b) -- OR: 1110 = 14
|
||||
print(a ~ b) -- XOR: 1100 = 12
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_lua(lua_code) == True
|
||||
assert detector.detect_language(lua_code) == "Lua"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(lua_code, "Lua")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_lua_detection()
|
||||
print("All Lua detection tests passed!")
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Test module for Perl language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_perl_detection():
|
||||
"""Test the Perl language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Perl code
|
||||
perl_code = """
|
||||
#!/usr/bin/perl
|
||||
use strict;
|
||||
use warnings;
|
||||
use Data::Dumper;
|
||||
use File::Basename;
|
||||
use Getopt::Long;
|
||||
|
||||
# Scalar variable
|
||||
my $name = "John Doe";
|
||||
my $age = 30;
|
||||
my $pi = 3.14159;
|
||||
|
||||
# Array variables
|
||||
my @fruits = ("apple", "banana", "orange");
|
||||
my @numbers = (1..10);
|
||||
|
||||
# Hash variables
|
||||
my %user = (
|
||||
"name" => "John",
|
||||
"age" => 30,
|
||||
"email" => "john@example.com"
|
||||
);
|
||||
|
||||
# Print statements
|
||||
print "Hello, $name!\\n";
|
||||
print "Your age is $age\\n";
|
||||
|
||||
# Accessing array elements
|
||||
print "First fruit: $fruits[0]\\n";
|
||||
print "Last fruit: $fruits[-1]\\n";
|
||||
|
||||
# Accessing hash elements
|
||||
print "User name: $user{name}\\n";
|
||||
print "User email: $user{email}\\n";
|
||||
|
||||
# Subroutine definition
|
||||
sub greet {
|
||||
my ($person) = @_;
|
||||
print "Hello, $person!\\n";
|
||||
return "Greeting sent";
|
||||
}
|
||||
|
||||
# Call the subroutine
|
||||
my $result = greet($name);
|
||||
print "Result: $result\\n";
|
||||
|
||||
# Control structures
|
||||
if ($age >= 18) {
|
||||
print "You are an adult.\\n";
|
||||
} else {
|
||||
print "You are a minor.\\n";
|
||||
}
|
||||
|
||||
# Unless example
|
||||
unless ($age < 18) {
|
||||
print "Not a minor.\\n";
|
||||
}
|
||||
|
||||
# For loop
|
||||
for my $i (0..$#fruits) {
|
||||
print "Fruit $i: $fruits[$i]\\n";
|
||||
}
|
||||
|
||||
# Foreach loop
|
||||
foreach my $fruit (@fruits) {
|
||||
print "I like $fruit\\n";
|
||||
}
|
||||
|
||||
# While loop
|
||||
my $counter = 0;
|
||||
while ($counter < 5) {
|
||||
print "Counter: $counter\\n";
|
||||
$counter++;
|
||||
}
|
||||
|
||||
# Regular expressions
|
||||
my $text = "The quick brown fox";
|
||||
if ($text =~ m/quick/) {
|
||||
print "Match found!\\n";
|
||||
}
|
||||
|
||||
# Substitution
|
||||
my $modified = $text;
|
||||
$modified =~ s/quick/slow/;
|
||||
print "Modified text: $modified\\n";
|
||||
|
||||
# Special variables
|
||||
print "Script name: $0\\n";
|
||||
print "Command line arguments: @ARGV\\n";
|
||||
print "Current line: $. \\n";
|
||||
|
||||
# File operations
|
||||
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
|
||||
print $fh "Hello, Perl!\\n";
|
||||
close $fh;
|
||||
|
||||
# Reading from standard input
|
||||
print "Enter your name: ";
|
||||
my $input = <STDIN>;
|
||||
chomp($input); # Remove newline
|
||||
print "Hello, $input!\\n";
|
||||
|
||||
# References
|
||||
my $array_ref = \\@fruits;
|
||||
print "First element via ref: ${$array_ref}[0]\\n";
|
||||
|
||||
my $hash_ref = \\%user;
|
||||
print "Name via ref: ${$hash_ref}{name}\\n";
|
||||
|
||||
# Using references for functions
|
||||
sub process_data {
|
||||
my ($data_ref) = @_;
|
||||
foreach my $key (keys %{$data_ref}) {
|
||||
print "Key: $key, Value: ${$data_ref}{$key}\\n";
|
||||
}
|
||||
}
|
||||
|
||||
process_data(\\%user);
|
||||
|
||||
# Object-oriented style
|
||||
package Person;
|
||||
|
||||
sub new {
|
||||
my ($class, $name, $age) = @_;
|
||||
return bless { name => $name, age => $age }, $class;
|
||||
}
|
||||
|
||||
sub get_name {
|
||||
my ($self) = @_;
|
||||
return $self->{name};
|
||||
}
|
||||
|
||||
sub get_age {
|
||||
my ($self) = @_;
|
||||
return $self->{age};
|
||||
}
|
||||
|
||||
package main;
|
||||
my $person = Person->new("Bob", 25);
|
||||
print "Person name: " . $person->get_name() . "\\n";
|
||||
print "Person age: " . $person->get_age() . "\\n";
|
||||
|
||||
exit 0;
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_perl(perl_code) == True
|
||||
assert detector.detect_language(perl_code) == "Perl"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(perl_code, "Perl")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_perl_detection()
|
||||
print("All Perl detection tests passed!")
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Test module for PHP language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_php_detection():
|
||||
"""Test the PHP language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample PHP code
|
||||
php_code = r"""
|
||||
<?php
|
||||
// Define namespace
|
||||
namespace App\Controllers;
|
||||
|
||||
// Import classes
|
||||
use App\Models\User;
|
||||
use App\Services\AuthService;
|
||||
use App\Exceptions\AuthException;
|
||||
|
||||
/**
|
||||
* Authentication Controller
|
||||
*
|
||||
* Handles user authentication functionality
|
||||
*/
|
||||
class AuthController
|
||||
{
|
||||
private $authService;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct(AuthService $authService)
|
||||
{
|
||||
$this->authService = $authService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login user
|
||||
*/
|
||||
public function login($request)
|
||||
{
|
||||
// Get request data
|
||||
$email = $request->input('email');
|
||||
$password = $request->input('password');
|
||||
$remember = $request->input('remember', false);
|
||||
|
||||
// Validate input
|
||||
if (empty($email) || empty($password)) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Email and password are required'
|
||||
];
|
||||
}
|
||||
|
||||
try {
|
||||
// Attempt to login
|
||||
$user = $this->authService->authenticate($email, $password);
|
||||
|
||||
// Create session
|
||||
$_SESSION['user_id'] = $user->id;
|
||||
|
||||
// Set remember me cookie if requested
|
||||
if ($remember) {
|
||||
$token = $this->authService->createRememberToken($user->id);
|
||||
setcookie('remember_token', $token, time() + 86400 * 30, '/');
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'success',
|
||||
'user' => $user
|
||||
];
|
||||
} catch (AuthException $e) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register new user
|
||||
*/
|
||||
public function register($request)
|
||||
{
|
||||
// Get request data
|
||||
$name = $request->input('name');
|
||||
$email = $request->input('email');
|
||||
$password = $request->input('password');
|
||||
|
||||
// Validate input
|
||||
if (empty($name) || empty($email) || empty($password)) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'All fields are required'
|
||||
];
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
$existingUser = User::findByEmail($email);
|
||||
if ($existingUser) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Email already registered'
|
||||
];
|
||||
}
|
||||
|
||||
// Create user
|
||||
$user = new User();
|
||||
$user->name = $name;
|
||||
$user->email = $email;
|
||||
$user->password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$user->save();
|
||||
|
||||
// Login user
|
||||
$_SESSION['user_id'] = $user->id;
|
||||
|
||||
return [
|
||||
'status' => 'success',
|
||||
'user' => $user
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
// Clear session
|
||||
unset($_SESSION['user_id']);
|
||||
session_destroy();
|
||||
|
||||
// Clear remember token cookie if it exists
|
||||
if (isset($_COOKIE['remember_token'])) {
|
||||
setcookie('remember_token', '', time() - 3600, '/');
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'success',
|
||||
'message' => 'Logged out successfully'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user profile
|
||||
*/
|
||||
public function profile()
|
||||
{
|
||||
if (!isset($_SESSION['user_id'])) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Not authenticated'
|
||||
];
|
||||
}
|
||||
|
||||
$user = User::find($_SESSION['user_id']);
|
||||
|
||||
return [
|
||||
'status' => 'success',
|
||||
'user' => $user
|
||||
];
|
||||
}
|
||||
}
|
||||
?>
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_php(php_code) == True
|
||||
assert detector.detect_language(php_code) == "PHP"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(php_code, "PHP")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_php_detection()
|
||||
print("All PHP detection tests passed!")
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Test module for R language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_r_detection():
|
||||
"""Test the R language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample R code
|
||||
r_code = """
|
||||
# Load necessary libraries
|
||||
library(tidyverse)
|
||||
library(ggplot2)
|
||||
library(dplyr)
|
||||
|
||||
# Create a data frame
|
||||
data <- data.frame(
|
||||
name = c("Alice", "Bob", "Charlie", "David"),
|
||||
age = c(25, 30, 35, 40),
|
||||
score = c(85, 92, 78, 95)
|
||||
)
|
||||
|
||||
# Basic data operations
|
||||
summary(data)
|
||||
str(data)
|
||||
head(data)
|
||||
|
||||
# Create a function
|
||||
calculate_average <- function(x) {
|
||||
return(mean(x, na.rm = TRUE))
|
||||
}
|
||||
|
||||
# Apply the function
|
||||
avg_score <- calculate_average(data$score)
|
||||
print(paste("Average score:", avg_score))
|
||||
|
||||
# Data manipulation with dplyr
|
||||
filtered_data <- data %>%
|
||||
filter(age > 30) %>%
|
||||
select(name, score) %>%
|
||||
arrange(desc(score))
|
||||
|
||||
# Control structures
|
||||
if (nrow(filtered_data) > 0) {
|
||||
print("Found records with age > 30")
|
||||
} else {
|
||||
print("No records with age > 30")
|
||||
}
|
||||
|
||||
# For loop example
|
||||
for (i in 1:nrow(data)) {
|
||||
if (data$age[i] < 30) {
|
||||
data$category[i] <- "Young"
|
||||
} else if (data$age[i] < 40) {
|
||||
data$category[i] <- "Middle"
|
||||
} else {
|
||||
data$category[i] <- "Senior"
|
||||
}
|
||||
}
|
||||
|
||||
# Create vectors
|
||||
ages <- c(25, 30, 35, 40)
|
||||
names <- c("Alice", "Bob", "Charlie", "David")
|
||||
|
||||
# Create a list
|
||||
person <- list(
|
||||
name = "Alice",
|
||||
age = 25,
|
||||
scores = c(85, 90, 92)
|
||||
)
|
||||
|
||||
# Access list elements
|
||||
person$name
|
||||
person$scores[2]
|
||||
|
||||
# Create factors
|
||||
gender <- factor(c("Male", "Female", "Female", "Male"))
|
||||
levels(gender)
|
||||
|
||||
# Basic plotting
|
||||
plot(data$age, data$score,
|
||||
main = "Age vs. Score",
|
||||
xlab = "Age",
|
||||
ylab = "Score",
|
||||
col = "blue",
|
||||
pch = 19)
|
||||
|
||||
# ggplot visualization
|
||||
ggplot(data, aes(x = age, y = score)) +
|
||||
geom_point(color = "blue", size = 3) +
|
||||
geom_smooth(method = "lm", se = FALSE) +
|
||||
labs(title = "Age vs. Score", x = "Age", y = "Score") +
|
||||
theme_minimal()
|
||||
|
||||
# Statistical analysis
|
||||
model <- lm(score ~ age, data = data)
|
||||
summary(model)
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_r(r_code) == True
|
||||
assert detector.detect_language(r_code) == "R"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(r_code, "R")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_r_detection()
|
||||
print("All R detection tests passed!")
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Test module for Ruby language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_ruby_detection():
|
||||
"""Test the Ruby language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Ruby code
|
||||
ruby_code = """
|
||||
# A simple Ruby class
|
||||
class Person
|
||||
attr_accessor :name, :age
|
||||
|
||||
def initialize(name, age)
|
||||
@name = name
|
||||
@age = age
|
||||
end
|
||||
|
||||
def greet
|
||||
puts "Hello, my name is #{@name} and I am #{@age} years old."
|
||||
end
|
||||
end
|
||||
|
||||
# Create a new Person
|
||||
person = Person.new("John", 30)
|
||||
person.greet
|
||||
|
||||
# Hash examples
|
||||
old_syntax = { :name => "Ruby", :created_by => "Yukihiro Matsumoto" }
|
||||
new_syntax = { name: "Ruby", created_by: "Yukihiro Matsumoto" }
|
||||
|
||||
# Block with parameters
|
||||
[1, 2, 3].each do |num|
|
||||
puts num * 2
|
||||
end
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_ruby(ruby_code) == True
|
||||
assert detector.detect_language(ruby_code) == "Ruby"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(ruby_code, "Ruby")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_ruby_detection()
|
||||
print("All Ruby detection tests passed!")
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Test module for Rust language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_rust_detection():
|
||||
"""Test the Rust language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Rust code
|
||||
rust_code = """
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Write};
|
||||
|
||||
// A struct in Rust
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Person {
|
||||
name: String,
|
||||
age: u32,
|
||||
}
|
||||
|
||||
// Implementation block for Person
|
||||
impl Person {
|
||||
// Constructor (associated function)
|
||||
pub fn new(name: String, age: u32) -> Self {
|
||||
Person { name, age }
|
||||
}
|
||||
|
||||
// Method
|
||||
pub fn greet(&self) -> String {
|
||||
format!("Hello, my name is {} and I am {} years old.", self.name, self.age)
|
||||
}
|
||||
|
||||
// Mutable method
|
||||
pub fn celebrate_birthday(&mut self) {
|
||||
self.age += 1;
|
||||
println!("Happy birthday! Now I am {} years old.", self.age);
|
||||
}
|
||||
}
|
||||
|
||||
// A simple function with pattern matching
|
||||
fn process_option(opt: Option<i32>) -> i32 {
|
||||
match opt {
|
||||
Some(value) => value,
|
||||
None => -1,
|
||||
}
|
||||
}
|
||||
|
||||
// Main function with vector usage
|
||||
fn main() {
|
||||
// Create a vector
|
||||
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
|
||||
numbers.push(6);
|
||||
|
||||
// Create a Person instance
|
||||
let mut person = Person::new(String::from("Alice"), 30);
|
||||
println!("{}", person.greet());
|
||||
person.celebrate_birthday();
|
||||
|
||||
// Use a HashMap
|
||||
let mut scores = HashMap::new();
|
||||
scores.insert(String::from("Blue"), 10);
|
||||
scores.insert(String::from("Red"), 50);
|
||||
|
||||
// Pattern matching with if let
|
||||
if let Some(score) = scores.get("Blue") {
|
||||
println!("Blue team score: {}", score);
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_rust(rust_code) == True
|
||||
assert detector.detect_language(rust_code) == "Rust"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(rust_code, "Rust")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_rust_detection()
|
||||
print("All Rust detection tests passed!")
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Test module for SQL language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_sql_detection():
|
||||
"""Test the SQL language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample SQL code
|
||||
sql_code = """
|
||||
-- Create database
|
||||
CREATE DATABASE ecommerce;
|
||||
|
||||
-- Use the database
|
||||
USE ecommerce;
|
||||
|
||||
-- Create tables
|
||||
CREATE TABLE customers (
|
||||
customer_id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
first_name VARCHAR(50) NOT NULL,
|
||||
last_name VARCHAR(50) NOT NULL,
|
||||
email VARCHAR(100) UNIQUE NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
is_active BOOLEAN DEFAULT TRUE
|
||||
);
|
||||
|
||||
CREATE TABLE categories (
|
||||
category_id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
parent_id INT,
|
||||
FOREIGN KEY (parent_id) REFERENCES categories(category_id)
|
||||
);
|
||||
|
||||
CREATE TABLE products (
|
||||
product_id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
price DECIMAL(10, 2) NOT NULL,
|
||||
stock_quantity INT DEFAULT 0,
|
||||
category_id INT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (category_id) REFERENCES categories(category_id)
|
||||
);
|
||||
|
||||
CREATE TABLE orders (
|
||||
order_id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
customer_id INT NOT NULL,
|
||||
order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
status ENUM('pending', 'processing', 'shipped', 'delivered', 'cancelled') DEFAULT 'pending',
|
||||
total_amount DECIMAL(10, 2) NOT NULL,
|
||||
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
|
||||
);
|
||||
|
||||
CREATE TABLE order_items (
|
||||
order_item_id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
order_id INT NOT NULL,
|
||||
product_id INT NOT NULL,
|
||||
quantity INT NOT NULL,
|
||||
price DECIMAL(10, 2) NOT NULL,
|
||||
FOREIGN KEY (order_id) REFERENCES orders(order_id),
|
||||
FOREIGN KEY (product_id) REFERENCES products(product_id)
|
||||
);
|
||||
|
||||
-- Insert sample data
|
||||
INSERT INTO categories (name, description)
|
||||
VALUES ('Electronics', 'Electronic devices and gadgets'),
|
||||
('Clothing', 'Apparel and accessories'),
|
||||
('Books', 'Books and publications');
|
||||
|
||||
INSERT INTO products (name, description, price, stock_quantity, category_id)
|
||||
VALUES ('Smartphone', 'Latest smartphone with advanced features', 699.99, 100, 1),
|
||||
('Laptop', 'High-performance laptop for professionals', 1299.99, 50, 1),
|
||||
('T-shirt', 'Cotton t-shirt in various colors', 19.99, 200, 2),
|
||||
('Jeans', 'Classic denim jeans', 49.99, 150, 2),
|
||||
('Programming Book', 'Learn programming from experts', 39.99, 75, 3);
|
||||
|
||||
-- Simple queries
|
||||
SELECT * FROM products WHERE price > 50.00;
|
||||
|
||||
SELECT p.name, p.price, c.name AS category
|
||||
FROM products p
|
||||
JOIN categories c ON p.category_id = c.category_id
|
||||
WHERE p.stock_quantity > 0
|
||||
ORDER BY p.price DESC;
|
||||
|
||||
-- Aggregate functions
|
||||
SELECT
|
||||
c.name AS category,
|
||||
COUNT(p.product_id) AS product_count,
|
||||
AVG(p.price) AS average_price,
|
||||
MIN(p.price) AS min_price,
|
||||
MAX(p.price) AS max_price
|
||||
FROM products p
|
||||
JOIN categories c ON p.category_id = c.category_id
|
||||
GROUP BY c.name
|
||||
HAVING COUNT(p.product_id) > 1;
|
||||
|
||||
-- Transactions
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
UPDATE products
|
||||
SET stock_quantity = stock_quantity - 1
|
||||
WHERE product_id = 1;
|
||||
|
||||
INSERT INTO orders (customer_id, total_amount)
|
||||
VALUES (1, 699.99);
|
||||
|
||||
INSERT INTO order_items (order_id, product_id, quantity, price)
|
||||
VALUES (LAST_INSERT_ID(), 1, 1, 699.99);
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Views
|
||||
CREATE VIEW product_details AS
|
||||
SELECT
|
||||
p.product_id,
|
||||
p.name,
|
||||
p.description,
|
||||
p.price,
|
||||
p.stock_quantity,
|
||||
c.name AS category
|
||||
FROM products p
|
||||
JOIN categories c ON p.category_id = c.category_id;
|
||||
|
||||
-- Stored procedure
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE get_product_inventory()
|
||||
BEGIN
|
||||
SELECT
|
||||
p.name,
|
||||
p.stock_quantity,
|
||||
CASE
|
||||
WHEN p.stock_quantity = 0 THEN 'Out of Stock'
|
||||
WHEN p.stock_quantity < 10 THEN 'Low Stock'
|
||||
WHEN p.stock_quantity < 50 THEN 'Medium Stock'
|
||||
ELSE 'Well Stocked'
|
||||
END AS stock_status
|
||||
FROM products p
|
||||
ORDER BY p.stock_quantity;
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
-- Triggers
|
||||
DELIMITER //
|
||||
CREATE TRIGGER after_order_insert
|
||||
AFTER INSERT ON orders
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
INSERT INTO order_history (order_id, customer_id, status, action)
|
||||
VALUES (NEW.order_id, NEW.customer_id, NEW.status, 'created');
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
-- Indexes
|
||||
CREATE INDEX idx_product_price ON products(price);
|
||||
CREATE INDEX idx_order_customer ON orders(customer_id);
|
||||
|
||||
-- Subqueries
|
||||
SELECT c.name, c.email
|
||||
FROM customers c
|
||||
WHERE c.customer_id IN (
|
||||
SELECT DISTINCT o.customer_id
|
||||
FROM orders o
|
||||
JOIN order_items oi ON o.order_id = oi.order_id
|
||||
JOIN products p ON oi.product_id = p.product_id
|
||||
WHERE p.category_id = 1
|
||||
);
|
||||
|
||||
-- Common Table Expressions (CTE)
|
||||
WITH high_value_orders AS (
|
||||
SELECT
|
||||
o.order_id,
|
||||
o.customer_id,
|
||||
o.total_amount
|
||||
FROM orders o
|
||||
WHERE o.total_amount > 500
|
||||
)
|
||||
SELECT
|
||||
c.first_name,
|
||||
c.last_name,
|
||||
COUNT(hvo.order_id) AS high_value_order_count
|
||||
FROM customers c
|
||||
JOIN high_value_orders hvo ON c.customer_id = hvo.customer_id
|
||||
GROUP BY c.customer_id;
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_sql(sql_code) == True
|
||||
assert detector.detect_language(sql_code) == "SQL"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(sql_code, "SQL")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_sql_detection()
|
||||
print("All SQL detection tests passed!")
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Test module for Swift language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_swift_detection():
|
||||
"""Test the Swift language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample Swift code
|
||||
swift_code = """
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
// A simple Swift class
|
||||
class Person {
|
||||
var name: String
|
||||
var age: Int
|
||||
|
||||
init(name: String, age: Int) {
|
||||
self.name = name
|
||||
self.age = age
|
||||
}
|
||||
|
||||
func greet() -> String {
|
||||
return "Hello, my name is \(name) and I am \(age) years old."
|
||||
}
|
||||
|
||||
func celebrateBirthday() {
|
||||
age += 1
|
||||
print("Happy birthday! Now I am \(age) years old.")
|
||||
}
|
||||
}
|
||||
|
||||
// Swift structs
|
||||
struct Point {
|
||||
let x: Double
|
||||
let y: Double
|
||||
|
||||
func distanceTo(point: Point) -> Double {
|
||||
return sqrt(pow(point.x - x, 2) + pow(point.y - y, 2))
|
||||
}
|
||||
}
|
||||
|
||||
// Swift optional binding
|
||||
func processName(name: String?) {
|
||||
if let unwrappedName = name {
|
||||
print("Hello, \(unwrappedName)!")
|
||||
} else {
|
||||
print("Hello, anonymous!")
|
||||
}
|
||||
}
|
||||
|
||||
// Guard statement
|
||||
func process(value: Int?) {
|
||||
guard let value = value else {
|
||||
print("Value is nil")
|
||||
return
|
||||
}
|
||||
|
||||
print("Value is \(value)")
|
||||
}
|
||||
|
||||
// UIKit elements
|
||||
class MyViewController: UIViewController {
|
||||
@IBOutlet weak var nameLabel: UILabel!
|
||||
|
||||
@IBAction func buttonPressed(_ sender: UIButton) {
|
||||
nameLabel.text = "Button was pressed!"
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
// Do additional setup
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_swift(swift_code) == True
|
||||
assert detector.detect_language(swift_code) == "Swift"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(swift_code, "Swift")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_swift_detection()
|
||||
print("All Swift detection tests passed!")
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Test module for TypeScript language detection."""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the src directory to the Python path
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
|
||||
|
||||
from ai_code_converter.core.language_detection import LanguageDetector
|
||||
|
||||
|
||||
def test_typescript_detection():
|
||||
"""Test the TypeScript language detection functionality."""
|
||||
detector = LanguageDetector()
|
||||
|
||||
# Sample TypeScript code
|
||||
typescript_code = """
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import axios from 'axios';
|
||||
|
||||
// Interface definition
|
||||
interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
// Type alias
|
||||
type UserResponse = User[] | null;
|
||||
|
||||
// Enum
|
||||
enum UserRole {
|
||||
Admin = 'ADMIN',
|
||||
User = 'USER',
|
||||
Guest = 'GUEST'
|
||||
}
|
||||
|
||||
// Class with type annotations
|
||||
export class UserService {
|
||||
private apiUrl: string;
|
||||
private users: User[] = [];
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
this.apiUrl = `${baseUrl}/users`;
|
||||
}
|
||||
|
||||
// Async method with return type
|
||||
public async getUsers(): Promise<User[]> {
|
||||
try {
|
||||
const response = await axios.get<UserResponse>(this.apiUrl);
|
||||
if (response.data) {
|
||||
this.users = response.data;
|
||||
return this.users;
|
||||
}
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Method with typed parameters
|
||||
public getUserById(id: number): User | undefined {
|
||||
return this.users.find(user => user.id === id);
|
||||
}
|
||||
|
||||
// Method with union type parameters
|
||||
public filterUsers(status: boolean | null): User[] {
|
||||
if (status === null) return this.users;
|
||||
return this.users.filter(user => user.isActive === status);
|
||||
}
|
||||
}
|
||||
|
||||
// Generic class
|
||||
class DataStore<T> {
|
||||
private items: T[] = [];
|
||||
|
||||
public add(item: T): void {
|
||||
this.items.push(item);
|
||||
}
|
||||
|
||||
public getAll(): T[] {
|
||||
return this.items;
|
||||
}
|
||||
}
|
||||
|
||||
// Decorator example
|
||||
@Component({
|
||||
selector: 'app-user-list',
|
||||
template: '<div>User List Component</div>'
|
||||
})
|
||||
class UserListComponent implements OnInit {
|
||||
users: User[] = [];
|
||||
userService: UserService;
|
||||
|
||||
constructor() {
|
||||
this.userService = new UserService('https://api.example.com');
|
||||
}
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
this.users = await this.userService.getUsers();
|
||||
console.log('Users loaded:', this.users.length);
|
||||
}
|
||||
}
|
||||
|
||||
// Function with default parameters
|
||||
function createUser(name: string, email: string, isActive: boolean = true): User {
|
||||
const id = Math.floor(Math.random() * 1000);
|
||||
return { id, name, email, isActive };
|
||||
}
|
||||
|
||||
// Main code
|
||||
const userStore = new DataStore<User>();
|
||||
const newUser = createUser('John Doe', 'john@example.com');
|
||||
userStore.add(newUser);
|
||||
|
||||
console.log('Users in store:', userStore.getAll().length);
|
||||
"""
|
||||
|
||||
# Test the detection
|
||||
assert detector.detect_typescript(typescript_code) == True
|
||||
assert detector.detect_language(typescript_code) == "TypeScript"
|
||||
|
||||
# Check that it's distinguishable from JavaScript
|
||||
js_code = """
|
||||
function greet(name) {
|
||||
console.log(`Hello, ${name}!`);
|
||||
}
|
||||
|
||||
const user = {
|
||||
name: 'John',
|
||||
age: 30
|
||||
};
|
||||
|
||||
greet(user.name);
|
||||
"""
|
||||
assert detector.detect_typescript(js_code) == False
|
||||
assert detector.detect_language(js_code) == "JavaScript"
|
||||
|
||||
# Check validation
|
||||
valid, _ = detector.validate_language(typescript_code, "TypeScript")
|
||||
assert valid == True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_typescript_detection()
|
||||
print("All TypeScript detection tests passed!")
|
||||
Reference in New Issue
Block a user