Model: wasabibish/similarity-code-ai-generated
Author: wasabibish
Pipeline: sentence-similarity
Library: sentence-transformers
Tags: sentence-transformers, safetensors, distilbert, sentence-similarity, feature-extraction, generated_from_trainer, dataset_size:302, loss:CosineSimilarityLoss, arxiv:1908.10084, base_model:distilbert/distilbert-base-uncased-finetuned-sst-2-english, base_model:finetune:distilbert/distilbert-base-uncased-finetuned-sst-2-english, model-index, text-embeddings-inference, endpoints_compatible, region:us
Base models (finetune): id: distilbert/distilbert-base-uncased-finetuned-sst-2-english
Card metadata: base_model: distilbert/distilbert-base-uncased-finetuned-sst-2-english
library_name: sentence-transformers
metrics: pearson_cosine, spearman_cosine, pearson_manhattan, spearman_manhattan, pearson_euclidean, spearman_euclidean, pearson_dot, spearman_dot, pearson_max, spearman_max
pipeline_tag: sentence-similarity
tags: sentence-transformers, sentence-similarity, feature-extraction, generated_from_trainer, dataset_size:302, loss:CosineSimilarityLoss
widget: source_sentence: interface Input {
  id: number;
  title: string;
  parent_id: number | null;  
}

interface Output extends Input {
  children?: Output[];  
}

function doJob(inputItems: Input[], parent_id?: number) {
  const outputItems: Output[] = [];

  for (let i = 0; i < inputItems.length; i++) {
    const children = doJob(inputItems.slice(i, inputItems.length), inputItems[i].parent_id)
    .filter(i => i.parent_id === parent_id);
    
    outputItems.push({...item, children});
  }

  return outputItems;
}
sentences: interface Task {
    id: number;
    title: string;
    parent_id: number | null;
    children?: Task[];
}

function buildTaskTree(tasks: Task[]): Task[] {
    const tasksMap = tasks.reduce((acc, task) => {
        acc[task.id] = { ...task, children: [] };
        return acc;
    }, {} as { [key: number]: Task });

    const rootTasks: Task[] = [];

    tasks.forEach(task => {
        const { id, parent_id } = task;
        if (parent_id === null) {
            rootTasks.push(tasksMap[id]);
        } else {
            if (tasksMap[parent_id]) {
                tasksMap[parent_id].children.push(tasksMap[id]);
            }
        }
    });

    return rootTasks;
}

// Test the function with the provided example
const inputTasks: Task[] = [
    { id: 1, title: 'Task 1', parent_id: null },
    { id: 2, title: 'Task 2', parent_id: 1 },
    { id: 3, title: 'Task 3', parent_id: 1 }
];
const outputTasks: Task[] = buildTaskTree(inputTasks);
console.log(outputTasks);
, const http = require('http');

async function checkUrlsStatus(urls) {
    const statusObj = {};

    const getStatus = async (url) => {
        return new Promise((resolve) => {
            http.get(url, (res) => {
                resolve(res.statusCode);
            }).on('error', (error) => {
                resolve(500); // Internal Server Error
            });
        });
    };

    await Promise.all(urls.map(async (url) => {
        const status = await getStatus(url);
        statusObj[url] = status;
    }));

    return statusObj;
}

// Example
const urls = ['https://example.com', 'https://google.com'];
checkUrlsStatus(urls)
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error(error);
    });

module.exports = checkUrlsStatus;
, def find_longest_word(words):
    max_length = 0
    longest_word = ''

    for word in words:
        if len(word) > max_length:
            max_length = len(word)
            longest_word = word

    return longest_word, max_length

# Test cases
print(find_longest_word(['hello', 'world', 'python', 'programming']))  # Output: ('programming', 11)
print(find_longest_word(['short', 'longer', 'longest', 'size']))  # Output: ('longest', 7)
, source_sentence: // inventory.module.ts
import { Module } from '@nestjs/common';
import { InventoryService } from './inventory.service';
import { InventoryController } from './inventory.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Product } from './product.entity';
@Module({
  imports: [TypeOrmModule.forFeature([Product])],
  providers: [InventoryService],
  controllers: [InventoryController],
})
export class InventoryModule {}
// inventory.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Product } from './product.entity';
import { CreateProductDto, UpdateProductDto } from './product.dto';

@Injectable()
export class InventoryService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async createProduct(createProductDto: CreateProductDto): Promise<Product> {
    const newProduct = new Product();
    newProduct.name = createProductDto.name;
    newProduct.description = createProductDto.description;
    newProduct.price = createProductDto.price;
    newProduct.availableQuantity = createProductDto.availableQuantity;

    return await this.productRepository.save(newProduct);
  }

  async updateProduct(
    productId: number,
    updateProductDto: UpdateProductDto,
  ): Promise<Product> {
    const product = await this.productRepository.findOne(productId);
    if (!product) {
      throw new NotFoundException('Product not found');
    }

    product.name = updateProductDto.name || product.name;
    product.description = updateProductDto.description || product.description;
    product.price = updateProductDto.price || product.price;
    product.availableQuantity =
      updateProductDto.availableQuantity || product.availableQuantity;

    return await this.productRepository.save(product);
  }

  async findAllProducts(): Promise<Product[]> {
    return await this.productRepository.find();
  }

  async getProductById(productId: number): Promise<Product> {
    const product = await this.productRepository.findOne(productId);
    if (!product) {
      throw new NotFoundException('Product not found');
    }
    return product;
  }

  async checkProductAvailability(productId: number, quantity: number): Promise<boolean> {
    const product = await this.productRepository.findOne(productId);
    if (!product) {
      throw new NotFoundException('Product not found');
    }
    return product.availableQuantity >= quantity;
  }
}
sentences: // inventory.dto.ts
import { IsInt, IsNotEmpty, IsNumber, IsString, Min } from 'class-validator';

export class ProductDto {
  @IsString()
  @IsNotEmpty()
  id: string;

  @IsString()
  @IsNotEmpty()
  name: string;

  @IsString()
  description: string;

  @IsNumber()
  @IsNotEmpty()
  price: number;

  @IsInt()
  @Min(0)
  @IsNotEmpty()
  availableQuantity: number;
}

// inventory.interface.ts
export interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  availableQuantity: number;
}

// inventory.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InventoryController } from './inventory.controller';
import { InventoryService } from './inventory.service';
import { Product } from './product.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Product])],
  controllers: [InventoryController],
  providers: [InventoryService]
})
export class InventoryModule {}  

// product.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  @Column('decimal')
  price: number;

  @Column()
  availableQuantity: number;
}

// inventory.controller.ts
import { Controller, Get, Post, Put, Body, Param } from '@nestjs/common';
import { InventoryService } from './inventory.service';
import { ProductDto } from './inventory.dto';

@Controller('inventory')
export class InventoryController {
  constructor(private readonly inventoryService: InventoryService) {}

  @Post('add-product')
  async addProduct(@Body() productDto: ProductDto) {
    return this.inventoryService.addProduct(productDto);
  }

  @Get('products')
  async getProducts() {
    return this.inventoryService.getProducts();
  }

  @Put('update-quantity/:id')
  async updateQuantity(@Param('id') id: string, @Body('quantity') quantity: number) {
    return this.inventoryService.updateQuantity(id, quantity);
  }
}

// inventory.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './product.entity';
import { ProductDto } from './inventory.dto';

@Injectable()
export class InventoryService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
  ) {}

  async addProduct(productDto: ProductDto): Promise<Product> {
    const newProduct = this.productRepository.create(productDto);
    return this.productRepository.save(newProduct);
  }

  async getProducts(): Promise<Product[]> {
    return this.productRepository.find();
  }

  async updateQuantity(id: string, quantity: number): Promise<Product> {
    const product = await this.productRepository.findOne(id);
    if (!product) {
      throw new Error('Product not found');
    }

    product.availableQuantity = quantity;
    return this.productRepository.save(product);
  }
}
, def move_zeros_to_end(lst):
    zero_count = 0
    for i in range(len(lst)):
        if lst[i] != 0:
            lst[i], lst[zero_count] = lst[zero_count], lst[i]
            zero_count += 1

# Test cases
lst1 = [0, 1, 0, 3, 12]
move_zeros_to_end(lst1)
print(lst1)  # Output: [1, 3, 12, 0, 0]

lst2 = [0, 0, 1]
move_zeros_to_end(lst2)
print(lst2)  # Output: [1, 0, 0]
, // inventory.dto.ts
import { IsInt, IsNotEmpty, IsNumber, IsString, Min } from 'class-validator';

export class ProductDto {
  @IsString()
  @IsNotEmpty()
  id: string;

  @IsString()
  @IsNotEmpty()
  name: string;

  @IsString()
  description: string;

  @IsNumber()
  @IsNotEmpty()
  price: number;

  @IsInt()
  @Min(0)
  @IsNotEmpty()
  availableQuantity: number;
}

// inventory.interface.ts
export interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  availableQuantity: number;
}

// inventory.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InventoryController } from './inventory.controller';
import { InventoryService } from './inventory.service';
import { Product } from './product.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Product])],
  controllers: [InventoryController],
  providers: [InventoryService]
})
export class InventoryModule {}  

// product.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  @Column('decimal')
  price: number;

  @Column()
  availableQuantity: number;
}

// inventory.controller.ts
import { Controller, Get, Post, Put, Body, Param } from '@nestjs/common';
import { InventoryService } from './inventory.service';
import { ProductDto } from './inventory.dto';

@Controller('inventory')
export class InventoryController {
  constructor(private readonly inventoryService: InventoryService) {}

  @Post('add-product')
  async addProduct(@Body() productDto: ProductDto) {
    return this.inventoryService.addProduct(productDto);
  }

  @Get('products')
  async getProducts() {
    return this.inventoryService.getProducts();
  }

  @Put('update-quantity/:id')
  async updateQuantity(@Param('id') id: string, @Body('quantity') quantity: number) {
    return this.inventoryService.updateQuantity(id, quantity);
  }
}

// inventory.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './product.entity';
import { ProductDto } from './inventory.dto';

@Injectable()
export class InventoryService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
  ) {}

  async addProduct(productDto: ProductDto): Promise<Product> {
    const newProduct = this.productRepository.create(productDto);
    return this.productRepository.save(newProduct);
  }

  async getProducts(): Promise<Product[]> {
    return this.productRepository.find();
  }

  async updateQuantity(id: string, quantity: number): Promise<Product> {
    const product = await this.productRepository.findOne(id);
    if (!product) {
      throw new Error('Product not found');
    }

    product.availableQuantity = quantity;
    return this.productRepository.save(product);
  }
}
, source_sentence: // wage-input.dto.ts
import { IsNumber, IsPositive } from 'class-validator';

export class WageInputDto {
  @IsNumber()
  @IsPositive()
  hourlyWage: number;

  @IsNumber()
  @IsPositive()
  hoursWorked: number;
}

// It will handle the input validation too.


// employee.controller.ts
import { Body, Controller, Post } from '@nestjs/common';
import { WageInputDto } from './dto/wage-input.dto';
import { EmployeeService } from './employee.service';

@Controller('employee')
export class EmployeeController {
  constructor(private readonly employeeService: EmployeeService) {}

  @Post('/wage')
  async getWage(@Body() input: WageInputDto) {
    return this.employeeService.getWage(input);
  }
}

// employee.service.ts
import { Injectable } from '@nestjs/common';
import { WageInputDto } from './dto/wage-input.dto';

const WEEKLY_HOURS = 40;

@Injectable()
export class EmployeeService {
  async getWage(input: WageInputDto) {
    let weeklyHours = 0;
    let overTimeHours = 0;
    let weeklyWage = 0;

    const hasDoneOverTime = input.hoursWorked > WEEKLY_HOURS;

    if (hasDoneOverTime) {
      weeklyHours = WEEKLY_HOURS;
      overTimeHours = input.hoursWorked - WEEKLY_HOURS;
    } else {
      weeklyHours = input.hoursWorked;
    }

    weeklyWage = weeklyHours * input.hourlyWage;

    if (hasDoneOverTime) {
      weeklyWage = weeklyWage + overTimeHours * (input.hourlyWage * 1.5);
    }

    return { weeklyWage };
  }
}
sentences: import { Controller, Post, Body, HttpException, HttpStatus } from '@nestjs/common';

interface WeeklyWageInput {
  hourlyWage: number;
  hoursWorked: number;
}

@Controller('calculate-weekly-wage')
export class WeeklyWageController {
  @Post()
  calculateWeeklyWage(@Body() data: WeeklyWageInput): { weeklyWage: number } {
    // Input validation
    if (data.hourlyWage <= 0 || data.hoursWorked <= 0 || !Number.isInteger(data.hoursWorked)) {
      throw new HttpException('Invalid input. Hourly wage must be positive and hours worked must be a positive integer', HttpStatus.BAD_REQUEST);
    }

    const regularHours = Math.min(data.hoursWorked, 40);
    const overtimeHours = Math.max(data.hoursWorked - 40, 0);

    const weeklyWage = (regularHours * data.hourlyWage) + (overtimeHours * (1.5 * data.hourlyWage));

    return { weeklyWage };
  }
}
, import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
  transform(array: any[], key: string, order: 'asc' | 'desc'): any[] {
    if (!Array.isArray(array) || !key || (order !== 'asc' && order !== 'desc')) {
      console.error('Invalid input data');
      return array;
    }

    const compareFn = (a: any, b: any): number => {
      if (a[key] < b[key]) {
        return order === 'asc' ? -1 : 1;
      }
      if (a[key] > b[key]) {
        return order === 'asc' ? 1 : -1;
      }
      return 0;
    };

    return array.slice().sort(compareFn);
  }
}
, public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
        int left = 0;
        int right = str.length() - 1;
        
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        
        return true;
    }
    
    public static void main(String[] args) {
        String input1 = "A man, a plan, a canal: Panama";
        String input2 = "race a car";
        
        System.out.println("Input: '" + input1 + "' Output: " + isPalindrome(input1));
        System.out.println("Input: '" + input2 + "' Output: " + isPalindrome(input2));
    }
}
, source_sentence: FROM python:3.8
WORKDIR /app

COPY helloworld.py .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "helloworld.py"]


## PYTHON PROGRAM
helloworld.py
print("Hello, World!")


## BUILD COMMAND
docker build -t "python:helloworld" .
docker run -itd --name python python:helloworld
sentences: # Use a slim Python base image for optimization
FROM python:3.9-slim

# Set the working directory inside the container
WORKDIR /app

# Copy the Python script into the container
COPY hello.py /app/hello.py

# Define the command to run the Python script
CMD ["python", "/app/hello.py"]
, import java.util.HashMap;

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }

        return new int[]{};
    }
}

// Example
int[] array = new int[]{2, 7, 11, 15};
int target = 9;
Solution solution = new Solution();
int[] result = solution.twoSum(array, target);
, function stripHtmlTags(input) {
    if (!input) return '';

    const tagRegex = /<[^>]*>/g;
    return input.replace(tagRegex, '');
}
, source_sentence: def move_zeroes(nums):
  count = 0
  for i in range(len(nums)):
    if nums[i] != 0:
      nums[count], nums[i]= nums[i], nums[count]
      count += 1
  for i in range(count, len(nums)):
    nums[i] =0

input = [int(x) for x in input("Enter integers separated by spaces: ").split()]
move_zeroes(input)

print(input)
sentences: import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final databaseRef = FirebaseDatabase.instance.reference().child('messages');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Real-Time Messages'),
        ),
        body: MessagesList(databaseRef: databaseRef),
        floatingActionButton: AddMessageButton(databaseRef: databaseRef),
      ),
    );
  }
}

class MessagesList extends StatelessWidget {
  final DatabaseReference databaseRef;

  MessagesList({required this.databaseRef});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: databaseRef.orderByChild('timestamp').onValue,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }

        if (!snapshot.hasData) {
          return Center(child: CircularProgressIndicator());
        }

        List<Message> messages = [];
        snapshot.data!.snapshot.value.forEach((key, value) {
          messages.add(Message.fromMap(value));
        });
        messages.sort((a, b) => a.timestamp.compareTo(b.timestamp));

        return ListView.builder(
          itemCount: messages.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(messages[index].text),
            );
          },
        );
      },
    );
  }
}

class AddMessageButton extends StatelessWidget {
  final DatabaseReference databaseRef;

  AddMessageButton({required this.databaseRef});

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: () {
        databaseRef.push().set({
          'text': 'New Message',
          'timestamp': DateTime.now().millisecondsSinceEpoch
        });
      },
      child: Icon(Icons.add),
    );
  }
}

class Message {
  final String text;
  final int timestamp;

  Message({required this.text, required this.timestamp});

  factory Message.fromMap(Map<dynamic, dynamic> map) {
    return Message(
      text: map['text'],
      timestamp: map['timestamp'],
    );
  }
}
, using System;
using System.Collections.Generic;

class BracketChecker
{
    private readonly Dictionary<char, char> bracketPairs = new Dictionary<char, char>
    {
        { '(', ')' },
        { '[', ']' },
        { '{', '}' }
    };

    public bool CheckBalancedBrackets(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return true;
        }

        Stack<char> stack = new Stack<char>();

        foreach (char c in input)
        {
            if (bracketPairs.ContainsValue(c))
            {
                if (stack.Count == 0 || bracketPairs[stack.Peek()] != c)
                {
                    return false;
                }
                stack.Pop();
            }
            else if (bracketPairs.ContainsKey(c))
            {
                stack.Push(c);
            }
        }

        return stack.Count == 0;
    }
}

class Program
{
    static void Main()
    {
        BracketChecker bracketChecker = new BracketChecker();

        string input1 = "(a+[b*c]-{d/e})";
        Console.WriteLine("Input: \"{0}\"", input1);
        Console.WriteLine("Output: {0}\n", bracketChecker.CheckBalancedBrackets(input1));

        string input2 = "(a+[b*c)-{d/e}]";
        Console.WriteLine("Input: \"{0}\"", input2);
        Console.WriteLine("Output: {0}", bracketChecker.CheckBalancedBrackets(input2));
    }
}
, def move_zeros_to_end(lst):
    zero_count = 0
    for i in range(len(lst)):
        if lst[i] != 0:
            lst[i], lst[zero_count] = lst[zero_count], lst[i]
            zero_count += 1

# Test cases
lst1 = [0, 1, 0, 3, 12]
move_zeros_to_end(lst1)
print(lst1)  # Output: [1, 3, 12, 0, 0]

lst2 = [0, 0, 1]
move_zeros_to_end(lst2)
print(lst2)  # Output: [1, 0, 0]

model-index: name: SentenceTransformer based on distilbert/distilbert-base-uncased-finetuned-sst-2-english
results: task: type: semantic-similarity
name: Semantic Similarity
dataset: name: Unknown
type: unknown
metrics: type: pearson_cosine
value: 0.9000341656513303
name: Pearson Cosine
verified: no, type: spearman_cosine
value: 0.9013693287916293
name: Spearman Cosine
verified: no, type: pearson_manhattan
value: 0.8619949591168187
name: Pearson Manhattan
verified: no, type: spearman_manhattan
value: 0.8020438201628594
name: Spearman Manhattan
verified: no, type: pearson_euclidean
value: 0.868483180326987
name: Pearson Euclidean
verified: no, type: spearman_euclidean
value: 0.8234464507775442
name: Spearman Euclidean
verified: no, type: pearson_dot
value: 0.8494699061913786
name: Pearson Dot
verified: no, type: spearman_dot
value: 0.8947516297094024
name: Spearman Dot
verified: no, type: pearson_max
value: 0.9000341656513303
name: Pearson Max
verified: no, type: spearman_max
value: 0.9013693287916293
name: Spearman Max
verified: no
Likes: 0 | All-time downloads: 12
Created: 2024-09-13 17:17:32