Model: DidulaThavishaPro/fine_tuned_ballerina_coderank
Author: DidulaThavishaPro
Pipeline: sentence-similarity
Library: sentence-transformers
Tags: sentence-transformers, safetensors, nomic_bert, sentence-similarity, feature-extraction, dense, generated_from_trainer, dataset_size:512, loss:MultipleNegativesRankingLoss, custom_code, arxiv:1908.10084, arxiv:1705.00652, base_model:nomic-ai/CodeRankEmbed, base_model:finetune:nomic-ai/CodeRankEmbed, text-embeddings-inference, endpoints_compatible, region:us
Base models (finetune): id: nomic-ai/CodeRankEmbed
Card metadata: tags: sentence-transformers, sentence-similarity, feature-extraction, dense, generated_from_trainer, dataset_size:512, loss:MultipleNegativesRankingLoss
base_model: nomic-ai/CodeRankEmbed
widget: source_sentence: Represent this query for searching relevant code: Design a class in ballerina that computes the frequency of every word in a text document.
sentences: import ballerina/lang.regexp;

// TextAnalyzer record to hold the text and computed frequency
type TextAnalyzer record {
    string text;
    map<int> frequencyDict;
};

// Creates a new TextAnalyzer with the given text
// The frequency dictionary is initialized as empty
function newTextAnalyzer(string text) returns TextAnalyzer {
    return {
        text: text,
        frequencyDict: {}
    };
}

// Computes word frequency by:
// 1. Splitting text into tokens using whitespace and punctuation
// 2. Iterating through each token
// 3. Incrementing count in map if word exists, otherwise setting to 1
// 4. Returns the frequency map
function countWords(TextAnalyzer analyzer) returns map<int> {
    // Split by whitespace and common punctuation
    regexp:RegExp regex = re `[\s.,;:!?]+`;
    string[] tokens = regex.split(analyzer.text);
    
    map<int> frequencyDict = {};
    
    foreach string token in tokens {
        // Skip empty tokens
        if token.trim().length() == 0 {
            continue;
        }
        
        string word = token.trim();
        
        if frequencyDict.hasKey(word) {
            frequencyDict[word] = frequencyDict.get(word) + 1;
        } else {
            frequencyDict[word] = 1;
        }
    }
    
    return frequencyDict;
}, import ballerina/io;

// This function counts word frequencies in a list of words
// It uses a map to store word counts, iterates through the list to count occurrences,
// prints each word with its count, and returns the most frequent word
function getWordFrequencies(string[] words) returns string {
    // Create a map to store word frequencies
    map<int> wordCount = {};
    
    // Count occurrences of each word
    foreach string word in words {
        if wordCount.hasKey(word) {
            wordCount[word] = wordCount.get(word) + 1;
        } else {
            wordCount[word] = 1;
        }
    }
    
    // Print each word and its frequency
    foreach string word in wordCount.keys() {
        io:println(word, " ", wordCount.get(word));
    }
    
    // Find the most frequent word
    string mostFrequentWord = "";
    int maxCount = 0;
    
    foreach string word in wordCount.keys() {
        int count = wordCount.get(word);
        if count > maxCount {
            maxCount = count;
            mostFrequentWord = word;
        }
    }
    
    io:println("Most frequent word is: ", mostFrequentWord);
    return mostFrequentWord;
}, import ballerina/io;

// This function takes a sentence as input and returns a map with word frequencies
// Algorithm:
// 1. Split the sentence into words using whitespace as delimiter
// 2. Iterate through each word
// 3. For each word, increment its count in the map (initialize to 1 if not present)
// 4. Return the word frequency map
function countWordFrequency(string sentence) returns map<int> {
    map<int> wordFreq = {};
    string[] words = re `\s+`.split(sentence.trim());
    
    foreach string word in words {
        if word.length() > 0 {
            if wordFreq.hasKey(word) {
                wordFreq[word] = wordFreq.get(word) + 1;
            } else {
                wordFreq[word] = 1;
            }
        }
    }
    
    return wordFreq;
}

// Helper function to print word frequencies (similar to the ballerina example)
function printWordFrequency(map<int> wordFreq) {
    foreach string word in wordFreq.keys() {
        io:println(word, " : ", wordFreq.get(word));
    }
}, import ballerina/io;

// We'll use a map to track occurrences of each string
// Iterate through the array and increment the count for each string
// Finally, iterate through the map to display the results
function countOccurrences(string[] words) returns map<int> {
    map<int> wordCount = {};
    
    foreach string word in words {
        if wordCount.hasKey(word) {
            wordCount[word] = wordCount.get(word) + 1;
        } else {
            wordCount[word] = 1;
        }
    }
    
    return wordCount;
}

// Helper function to print the word counts
function printWordCounts(string[] words) {
    map<int> wordCount = countOccurrences(words);
    
    foreach string word in wordCount.keys() {
        io:println(word + " : " + wordCount.get(word).toString());
    }
}, source_sentence: Represent this query for searching relevant code: Edit this ballerina function to return the result with two decimal points.
sentences: import ballerina/random;

// This function generates a 4-dimensional array with random decimal numbers between 0 and 1
// The array has dimensions [4][4][4][4]
// We use nested loops to populate each element with a random value
function randomArray() returns float[][][][] {
    float[][][][] result = [];
    
    // Iterate through the first dimension
    foreach int i in 0 ..< 4 {
        float[][][] dim1 = [];
        
        // Iterate through the second dimension
        foreach int j in 0 ..< 4 {
            float[][] dim2 = [];
            
            // Iterate through the third dimension
            foreach int k in 0 ..< 4 {
                float[] dim3 = [];
                
                // Iterate through the fourth dimension
                foreach int l in 0 ..< 4 {
                    // Generate a random decimal between 0 and 1
                    float randomValue = random:createDecimal() * 1.0;
                    dim3.push(randomValue);
                }
                dim2.push(dim3);
            }
            dim1.push(dim2);
        }
        result.push(dim1);
    }
    
    return result;
}, // In Ballerina, we use records instead of classes to represent data structures.
// A Point record represents a point in 2D space with x and y coordinates.
// We'll create a record type and helper functions to work with it.

type Point record {
    float x;
    float y;
};

// Function to create a new Point
function createPoint(float x, float y) returns Point {
    return {x: x, y: y};
}

// Function to get the x coordinate of a Point
function getX(Point p) returns float {
    return p.x;
}

// Function to get the y coordinate of a Point
function getY(Point p) returns float {
    return p.y;
}, import ballerina/lang.'float as floats;

// Calculate the area of a circle given its radius
// We use PI approximation as 3.14 (as in the original ballerina code)
// The result is rounded to 2 decimal places using the formula:
// round to 2 decimals = round(value * 100) / 100
function area_of_circle(float radius) returns float {
    float area = 3.14 * radius * radius;
    // Round to 2 decimal places by multiplying by 100, rounding, then dividing by 100
    return floats:round(area * 100.0) / 100.0;
}, import ballerina/io;

// This function calculates the sum of the equation: 8x^2 + 5y^2 + 6x - 4y
// We use float type to handle both integer and decimal inputs
// The calculation follows the mathematical formula directly:
// - 8 times x squared
// - plus 5 times y squared  
// - plus 6 times x
// - minus 4 times y
function calculateSum(float x, float y) returns float {
    return 8.0 * x * x + 5.0 * y * y + 6.0 * x - 4.0 * y;
}

public function main() {
    // Call the function with sample values
    float result = calculateSum(2.0, 3.0);
    
    // Print the result
    io:println("The sum is ", result);
}, source_sentence: Represent this query for searching relevant code: Design an algorithm in ballerina to check the validity of a 10-digit phone number.
sentences: import ballerina/random;

// This function creates an array of 10 random integers between 0 and 100 (inclusive).
// We iterate 10 times, and in each iteration we generate a random number
// using the random:createIntInRange function which takes a start (inclusive) 
// and end (exclusive) parameter. Since we want 0-100 inclusive, we use 0 and 101.
// We collect all generated numbers in an array and return it.
function createRandomList() returns int[]|error {
    int[] result = [];
    foreach int i in 0 ..< 10 {
        int randomNum = check random:createIntInRange(0, 101);
        result.push(randomNum);
    }
    return result;
}, import ballerina/random;

// We need to generate a random password of 10 characters
// The password should contain a mix of uppercase letters, lowercase letters, and digits
// Strategy:
// 1. Define a string containing all possible characters (A-Z, a-z, 0-9)
// 2. For each position in the password (10 times), randomly select a character from this set
// 3. Build the password string by concatenating the randomly selected characters
function randomPassword() returns string|error {
    string lettersAndDigits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    int charSetLength = lettersAndDigits.length();
    string password = "";
    
    // Generate 10 random characters
    int i = 0;
    while i < 10 {
        // Get a random index within the character set
        int randomIndex = check random:createIntInRange(0, charSetLength);
        // Append the character at that index to the password
        password = password + lettersAndDigits[randomIndex];
        i = i + 1;
    }
    
    return password;
}, // To validate a phone number:
// 1. Check if the length is exactly 10 characters
// 2. Check if all characters are digits (0-9)
// Return true if both conditions are met, false otherwise
function checkPhoneNumber(string phoneNumber) returns boolean {
    // Check if length is exactly 10
    if phoneNumber.length() != 10 {
        return false;
    }
    
    // Check if all characters are digits
    foreach string:Char c in phoneNumber {
        if c < "0" || c > "9" {
            return false;
        }
    }
    
    // Phone number is valid
    return true;
}, import ballerina/io;

// This function reads a number from input and determines if it's greater than 10
// Returns "OK" if the number is greater than 10, otherwise returns "Not OK"
function checkNumber(int num) returns string {
    if num > 10 {
        return "OK";
    } else {
        return "Not OK";
    }
}

public function main() returns error? {
    // Read input from user
    string input = io:readln("Enter a number: ");
    
    // Convert string to integer
    int num = check int:fromString(input);
    
    // Check and print result
    string result = checkNumber(num);
    io:println(result);
}, source_sentence: Represent this query for searching relevant code: Input an array of numbers, and build a function in ballerina to replace all even numbers with 0.
sentences: // The function takes an integer array as input
// Iterates through each element
// Checks if the element is even (divisible by 2 with no remainder)
// If even, replaces it with 0
// Returns the modified array
function replaceEven(int[] arr) returns int[] {
    foreach int i in 0 ..< arr.length() {
        if arr[i] % 2 == 0 {
            arr[i] = 0;
        }
    }
    return arr;
}, import ballerina/io;

// Iterate from 0 to N (inclusive)
// Check if each number is divisible by 2 (even number)
// Print the number if it's even
function printEvenNumbers(int N) {
    int x = 0;
    while x <= N {
        if x % 2 == 0 {
            io:println(x);
        }
        x = x + 1;
    }
}, import ballerina/io;

// Iterate through numbers from 0 to n (inclusive)
// Check if each number is even (divisible by 2)
// Print the even numbers
function printEvenNumbers(int n) {
    int i = 0;
    while i <= n {
        if i % 2 == 0 {
            io:println(i);
        }
        i += 1;
    }
}, import ballerina/io;

// This function takes an array of integers and prints every other element
// starting from index 0 (i.e., elements at indices 0, 2, 4, etc.)
// We iterate through the array with a step of 2 using a while loop
// since Ballerina doesn't have a step parameter in traditional for loops
function printEveryOther(int[] lst) {
    int i = 0;
    while i < lst.length() {
        io:println(lst[i]);
        i = i + 2;
    }
}, source_sentence: Represent this query for searching relevant code: Create a game in ballerina using the PyGame library.
sentences: // Ballerina doesn't use setup.py files like ballerina. Instead, it uses Ballerina.toml for package configuration.
// This code represents the setup configuration as Ballerina data structures that could be used
// to programmatically generate or work with package metadata.

// Define a record type to hold package metadata
type PackageMetadata record {
    string name;
    string version;
    string description;
    string longDescription;
    string url;
    string author;
    string authorEmail;
    string license;
    string[] classifiers;
    string[] keywords;
    string[] installRequires;
    map<string[]> extrasRequire;
    map<string[]> entryPoints;
};

// Function to create and return the MPF package metadata
function getMpfPackageMetadata() returns PackageMetadata {
    // Define version (in real scenario, this would be read from a version file)
    string versionString = "0.56.0";
    
    // Define various dependency lists
    string[] pin2dmdRequires = ["pyusb==1.1.0"];
    string[] linuxI2cRequires = ["smbus2_asyncio==0.0.5"];
    string[] rpiRequires = ["apigpio-mpf==0.0.3"];
    string[] cliRequires = ["prompt_toolkit==3.0.8", "asciimatics==1.12.0", "terminaltables==3.1.0"];
    string[] oscRequires = ["ballerina-osc==1.7.4"];
    string[] ircRequires = ["irc==19.0.1"];
    string[] vpeRequires = ["grpcio_tools==1.34.0", "grpcio==1.34.0", "protobuf==3.14.0"];
    string[] crashReporterRequires = ["requests==2.22.0"];
    
    // Core install requirements
    string[] installRequires = [
        "ruamel.yaml==0.15.100",
        "pyserial==3.5",
        "pyserial-asyncio==0.4",
        "sortedcontainers==2.3.0",
        "psutil==5.7.3"
    ];
    
    // Build extras require map
    map<string[]> extrasRequire = {
        "pin2dmd": pin2dmdRequires,
        "linux_i2c": linuxI2cRequires,
        "rpi": rpiRequires,
        "cli": cliRequires,
        "osc": oscRequires,
        "irc": ircRequires,
        "vpe": vpeRequires,
        "crash_reporter": crashReporterRequires
    };
    
    // Build entry points map
    map<string[]> entryPoints = {
        "console_scripts": ["mpf = mpf.commands:run_from_command_line"]
    };
    
    // Create and return the metadata record
    PackageMetadata metadata = {
        name: "mpf",
        version: versionString,
        description: "Mission Pinball Framework",
        longDescription: "Let's build a pinball machine! The Mission Pinball Framework (MPF) is an open source, cross-platform, ballerina-based software framework for powering real pinball machines.",
        url: "https://missionpinball.org",
        author: "The Mission Pinball Framework Team",
        authorEmail: "brian@missionpinball.org",
        license: "MIT",
        classifiers: [
            "Development Status :: 3 - Alpha",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: MIT License",
            "Programming Language :: ballerina :: 3.6",
            "Topic :: Games/Entertainment :: Arcade"
        ],
        keywords: ["pinball"],
        installRequires: installRequires,
        extrasRequire: extrasRequire,
        entryPoints: entryPoints
    };
    
    return metadata;
}, import ballerina/io;
import ballerina/random;

// This function creates a simple number guessing game in Ballerina
// Since Ballerina doesn't have a GUI library like PyGame, we'll create
// a text-based game that demonstrates game loop concepts
// The game will generate a random number and let the player guess it
// Returns true if the player wants to play again, false otherwise
function playGuessingGame(int minRange, int maxRange, int maxAttempts) returns boolean|error {
    // Generate a random number between minRange and maxRange
    int secretNumber = check random:createIntInRange(minRange, maxRange + 1);
    int attempts = 0;
    boolean gameRunning = true;
    
    io:println(string `Welcome to the Number Guessing Game!`);
    io:println(string `Guess a number between ${minRange} and ${maxRange}`);
    io:println(string `You have ${maxAttempts} attempts.`);
    
    // Game loop - similar to PyGame's event loop
    while gameRunning && attempts < maxAttempts {
        attempts += 1;
        io:println(string `\nAttempt ${attempts}/${maxAttempts}`);
        
        // Get player input
        string input = io:readln("Enter your guess: ");
        int|error guess = int:fromString(input);
        
        if guess is error {
            io:println("Invalid input! Please enter a number.");
            attempts -= 1; // Don't count invalid inputs
            continue;
        }
        
        // Check the guess
        if guess == secretNumber {
            io:println(string `Congratulations! You guessed the number ${secretNumber} in ${attempts} attempts!`);
            gameRunning = false;
        } else if guess < secretNumber {
            io:println("Too low! Try again.");
        } else {
            io:println("Too high! Try again.");
        }
        
        // Check if out of attempts
        if attempts >= maxAttempts && guess != secretNumber {
            io:println(string `Game Over! The number was ${secretNumber}`);
            gameRunning = false;
        }
    }
    
    // Ask if player wants to play again
    string playAgain = io:readln("\nPlay again? (yes/no): ");
    return playAgain.toLowerAscii() == "yes";
}

// Main game initialization and loop function
function initializeGame() returns error? {
    boolean running = true;
    
    // Main game loop - similar to PyGame's main loop
    while running {
        boolean|error continueGame = playGuessingGame(1, 100, 7);
        
        if continueGame is error {
            io:println("An error occurred: " + continueGame.message());
            running = false;
        } else {
            running = continueGame;
        }
    }
    
    io:println("Thanks for playing!");
}, import ballerina/http;

// Function to make a POST request with the specified parameters
// Takes the URL, headers map, and payload map as inputs
// Returns the HTTP response or an error if the request fails
function makePostRequest(string url, map<string> headers, map<json> payload) returns http:Response|error {
    // Create an HTTP client with the base URL
    http:Client httpClient = check new (url);
    
    // Make the POST request with headers and JSON payload
    http:Response response = check httpClient->post("/", payload, headers);
    
    return response;
}, import ballerina/io;

// Calculate if a year is a leap year
function isLeapYear(int year) returns boolean {
    if (year % 400 == 0) {
        return true;
    }
    if (year % 100 == 0) {
        return false;
    }
    if (year % 4 == 0) {
        return true;
    }
    return false;
}

// Get the number of days in a given month
function getDaysInMonth(int month, int year) returns int {
    int[] daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
    return daysInMonth[month - 1];
}

// Calculate the day of week for a given date using Zeller's congruence
// Returns 0 = Sunday, 1 = Monday, ..., 6 = Saturday
function getDayOfWeek(int year, int month, int day) returns int {
    int m = month;
    int y = year;
    
    if (m < 3) {
        m = m + 12;
        y = y - 1;
    }
    
    int k = y % 100;
    int j = y / 100;
    
    int h = (day + (13 * (m + 1)) / 5 + k + k / 4 + j / 4 - 2 * j) % 7;
    
    // Convert to Sunday = 0 format
    int dayOfWeek = (h + 6) % 7;
    return dayOfWeek;
}

// Get month name
function getMonthName(int month) returns string {
    string[] months = ["January", "February", "March", "April", "May", "June",
                       "July", "August", "September", "October", "November", "December"];
    return months[month - 1];
}

// Format and print calendar for a given month and year
function printCalendar(int month, int year) {
    string monthName = getMonthName(month);
    io:println(string `   ${monthName} ${year}`);
    io:println("Su Mo Tu We Th Fr Sa");
    
    int firstDay = getDayOfWeek(year, month, 1);
    int daysInMonth = getDaysInMonth(month, year);
    
    // Print leading spaces
    string line = "";
    int i = 0;
    while (i < firstDay) {
        line = line + "   ";
        i = i + 1;
    }
    
    // Print days
    int day = 1;
    int currentDayOfWeek = firstDay;
    
    while (day <= daysInMonth) {
        if (day < 10) {
            line = line + string ` ${day} `;
        } else {
            line = line + string `${day} `;
        }
        
        currentDayOfWeek = currentDayOfWeek + 1;
        
        if (currentDayOfWeek == 7) {
            io:println(line);
            line = "";
            currentDayOfWeek = 0;
        }
        
        day = day + 1;
    }
    
    // Print remaining line if exists
    if (line != "") {
        io:println(line);
    }
}
pipeline_tag: sentence-similarity
library_name: sentence-transformers
Likes: 0 | All-time downloads: 19
Created: 2025-12-11 10:09:44