text:
<repo_name>Cazuist/netology-PHP25-2.2<file_sep>/test.php
<?php
    $testNumber = $_GET['test'];
    $testsPathList = glob('uploaded_tests/*.json');
    $currentTest = json_decode(file_get_contents($testsPathList[$testNumber - 1]) ,true);

    $totalQuestions = count($currentTest);
    $correctAnswers = 0;
?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Тест</title>
    <link rel="stylesheet" href="css/styles.css">

Тест №<?= $testNumber ?>

    <form enctype = "multipart/form-data" action = "" method = "POST" >
        <? foreach ($currentTest as $num => $test): ?>

            <fieldset>
                <legend><?= $test['question'] ?></legend>

                <? foreach ($test['varAnswers'] as $var => $questions) : ?>

                    <input type="radio" name="question<?= $num + 1 ?>" value="<?= $var ?>"><?= $questions ?>

                <? endforeach ?>

            </fieldset>

        <? endforeach ?>

        <input type="submit" name="check" value="Проверить ответы" style="margin-top: 20px;">
    </form>

    <?
        if (isset($_POST['check'])) {

            foreach ($currentTest as $key => $test) {

                if (!isset($_POST['question'.($key + 1)])) {
                    ?>

Необходимо ответить на все вопросы

                    <?
                } else {
                    if ($test['trueAnswer'] === $_POST['question'.($key + 1)]) {
                         $correctAnswers++;
                        ?>

Всего вопросов: <?= $totalQuestions ?>

Правильных ответов: <?= $correctAnswers ?>

Ваш результат: <?= round($correctAnswers / $totalQuestions * 100) ?>%

                    <?
                    }
                }
            }

        }
    ?>

    Перейти к списку тестов

branch_name: refs/heads/master

repo_language: PHP


text:
<file_sep># Aim:
It is a server for d3-react

# should know:
please set it in ~/WORKSPACE/

# command:
yarn
node index.js
<file_sep>openssl genrsa 1024 > ./private.pem
openssl req -new -key ./private.pem -out ./csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey ./private.pem -out ./file.crt<file_sep>const express = require('express');
const app = express();
app.use(express.json());
let cors = require('cors');
const fs = require('fs');
const path = require('path');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('./src/certificiate/private.pem', 'utf8');
var certificate = fs.readFileSync('./src/certificiate/file.crt', 'utf8');
var credentials = { key: privateKey, cert: certificate };

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = process.env.HTTP_PORT || 6996;
var SSLPORT = process.env.HTTPS_PORT || 6999;
var USERIP = process.env.USER_IP || "localhost";

httpServer.listen(PORT, function () {
    console.log(`HTTP Server is running on: http://${USERIP}:%s`, PORT);
});
httpsServer.listen(SSLPORT, function () {
    console.log(`HTTPS Server is running on: https://${USERIP}:%s`, SSLPORT);
});

app.use(cors());
app.get('/', function (req, res) {
    if (req.protocol === 'https') {
        res.status(200).send('Welcome to Safety Land!');
    }
    else {
        res.status(200).send('Welcome!');
    }
});

app.get('/api', (req, res) => {
    res.send([1, 2, 3, 4, 5]);
});

app.get('/api/posts/:year/:month', (req, res) => {
    res.send(req.query);
});
app.get('/api/get_info', (req, res) => {
    res.send("OK");
    // initData(0);
});
app.get('/api/get_info_next', (req, res) => {
    res.send(JSON.stringify(getInitData()));
});
app.post('/api/add_info', (req, res) => {
    const listid = req.body.listid;
    // console.log(listid);
    const whole_data = getWholeData();
    // console.log(whole_data.nodes[listid].fsPath);
    const position = {
        fsPath: whole_data.nodes[listid].fsPath,
        line: whole_data.nodes[listid].line,
        character: 0,
        time: getTime()
    }
    let mark_path = getContralMarkPath();
    // console.log(mark_path);
    fs.writeFileSync(mark_path, JSON.stringify(position));

    addData(listid);
    res.send(JSON.stringify(getAddData()));
});
app.post('/api/jump_info', (req, res) => {
    const listid = req.body.listid;
    // console.log(listid);
    const whole_data = getWholeData();
    // console.log(whole_data.nodes[listid].fsPath);
    const position = {
        fsPath: whole_data.nodes[listid].fsPath,
        line: whole_data.nodes[listid].line,
        character: 0,
        time: getTime()
    }
    let jump_path = getContralJumpPath();
    // console.log(mark_path);
    fs.writeFileSync(jump_path, JSON.stringify(position));

    // addData(listid);
    // res.send(JSON.stringify(getAddData()));
});
app.post('/api/set_info', (req, res) => {
    const listid = req.body.listid;
    // console.log(listid);
    const whole_data = getWholeData();
    // console.log(whole_data.nodes[listid].fsPath);
    const position = {
        fsPath: whole_data.nodes[listid].fsPath,
        line: whole_data.nodes[listid].line,
        character: 0,
        time: getTime()
    }
    let mark_path = getContralMarkPath();
    // console.log(mark_path);
    fs.writeFileSync(mark_path, JSON.stringify(position));

    addData(listid);
    res.send(JSON.stringify(getInitData()));
});

const WholeDataPath = "./src/data/post.json";
const DirDataPath = "./src/data/dir_position.json";
const InitDataPath = "./src/test/data.json";
const InitAddPath = "./src/test/Add.json";

function getWholeData() {
    return getJsonFileData(WholeDataPath);
}

function getDirData() {
    return getJsonFileData(DirDataPath);
}

function getInitData() {
    return getJsonFileData(InitDataPath);
}
function getAddData() {
    return getJsonFileData(InitAddPath);
}

function getContralMarkPath() {
    return path.join(getDirData().path, ".vscode", "contralmarks.json");
}

function getContralJumpPath() {
    return path.join(getDirData().path, ".vscode", "jumpmarks.json");
}

function getJsonFileData(file_path) {
    const init_nodes = fs.readFileSync(file_path).toString();//beacuse it always much big, So need use await
    return JSON.parse(init_nodes);
}

function getTime() {
    const myDate = new Date();
    return myDate.toLocaleString();
}

function initData(listid) {
    init_nodes_json = getWholeData();
    data = {
        nodes: [],
        links: []
    }
    add = {
        nodes: [],
        links: []
    }
    console.log("initData");
    addNodeAllAround(init_nodes_json, listid, data, add);
    fs.writeFileSync(InitDataPath, JSON.stringify(data, null, 4));
    fs.writeFileSync(InitAddPath, JSON.stringify(add, null, 4));

    // setEdgeForce(init_nodes_json);
}

function addData(listid) {
    init_nodes_json = getWholeData();
    let data = getInitData();
    add = {
        nodes: [],
        links: []
    }
    console.log("listid: " + listid);
    console.log("length: " + data.nodes.length);
    addNodeAllAround(init_nodes_json, listid, data, add);
    // console.log(data.nodes.length);
    fs.writeFileSync(InitDataPath, JSON.stringify(data, null, 4));
    fs.writeFileSync(InitAddPath, JSON.stringify(add, null, 4));
}

function addNode(whole_info_json, node_listid, result, add) {
    if (whole_info_json.nodes.length < node_listid || node_listid < 0) {
        return false;
    }
    let node_listid_isin = false;
    for (let i = 0; i < result.nodes.length; i++) {
        if (node_listid == result.nodes[i].listid) {
            node_listid_isin = true;
            break;
        }
    }
    if (!node_listid_isin) {
        result.nodes.push(whole_info_json.nodes[node_listid]);
        add.nodes.push(whole_info_json.nodes[node_listid]);
    }
    return true;
}

function delNode(whole_info_json, node_listid, result, del) {
    let node_listid_isin = -1;
    for (let i = 0; i < result.nodes.length; i++) {
        if (node_listid == result.nodes[i].listid) {
            node_listid_isin = i;
            break;
        }
    }
    if (node_listid_isin >= 0) {
        result.nodes.splice(node_listid_isin, 1);
        del.nodes.push(whole_info_json.nodes[node_listid]);
    }
    return true;
}

function addLink(whole_info_json, links_listid, result, add) {
    if (whole_info_json.links.length < links_listid || links_listid < 0) {
        return false;
    }
    let links_listid_isin = false;
    for (let i = 0; i < result.links.length; i++) {
        if (links_listid == result.links[i].listid) {
            links_listid_isin = true;
            break;
        }
    }
    if (!links_listid_isin) {
        result.links.push(whole_info_json.links[links_listid]);
        add.links.push(whole_info_json.links[links_listid]);
    }
    return true;
}

function delLink(whole_info_json, links_listid, result, del) {
    let links_listid_isin = -1;
    for (let i = 0; i < result.links.length; i++) {
        if (links_listid == result.links[i].listid) {
            links_listid_isin = i;
            break;
        }
    }
    if (links_listid_isin >= 0) {
        result.links.splice(links_listid_isin, 1);
        del.nodes.push(whole_info_json.links[links_listid]);

    }
    return true;
}

function findNodeListidID(whole_info_json, orinigal_id) {
    for (let i = 0; i < whole_info_json.nodes.length; i++) {
        if (whole_info_json.nodes[i].id === orinigal_id) {
            return i;
        }
    }
    return -1;
}

function addNodeWithAllLinks(whole_info_json, node_listid, result, add) {
    if (whole_info_json.nodes.length < node_listid || node_listid < 0) {
        return false;
    }
    // console.log(node_listid);
    let node_origin_id = whole_info_json.nodes[node_listid].id
    for (let i = 0; i < whole_info_json.links.length; i++) {
        // console.log(whole_info_json.links[i].source);//do not use console.log here , it will let transport fail
        if (whole_info_json.links[i].source === node_origin_id) {
            addLink(whole_info_json, whole_info_json.links[i].listid, result, add);
            let target_listid = findNodeListidID(whole_info_json, whole_info_json.links[i].target);
            addNode(whole_info_json, target_listid, result, add);
        } else if (whole_info_json.links[i].target === node_origin_id) {
            addLink(whole_info_json, whole_info_json.links[i].listid, result, add);
            let source_listid = findNodeListidID(whole_info_json, whole_info_json.links[i].source);
            addNode(whole_info_json, source_listid, result, add);
        }
    }

    for (let i = 0; i < result.nodes.length; i++) {
        if (result.nodes[i].listid === node_listid) {
            continue;
        }
        for (let j = i + 1; j < result.nodes.length; j++) {
            if (result.nodes[j].listid === node_listid) {
                continue;
            }
            let max = 2;
            for (let k = 0; k < whole_info_json.links.length; k++) {
                if (result.nodes[i].id === whole_info_json.links.target && result.nodes[j].id === whole_info_json.links.source) {
                    max -= 1;
                    addLink(whole_info_json, whole_info_json.links[k].listid, result, add);
                } else if (result.nodes[i].id === whole_info_json.links.source && result.nodes[j].id === whole_info_json.links.target) {
                    max -= 1;
                    addLink(whole_info_json, whole_info_json.links[k].listid, result, add);
                }
                if (1 === max) {
                    break;
                }
            }
        }
    }

    return true;
}

function addNodeAllAround(whole_info_json, node_listid, result, add) {
    if (addNode(whole_info_json, node_listid, result, add)) {
        // console.log("addNodeAllAround node_listid " + node_listid);
        return (addNodeWithAllLinks(whole_info_json, node_listid, result, add))
    }
    return false;
}

function jsonPath() {
    data_post = "./src/data/post.json";
    data_finial = "./src/data/finial.json";
    data_dir = "./src/data/dir_position.json";
    const info = fs.readFileSync(data_post).toString();
    const info_json = JSON.parse(info);
    const dir = fs.readFileSync(data_dir).toString();
    const dir_json = JSON.parse(dir);
    for (let i = 0; i < info_json.nodes.length; i++) {
        info_json.nodes[i].fsPath = absoluteAddress(dir_json.path, info_json.nodes[i].fsPath);
    }
    const info_finial = JSON.stringify(info_json);
    fs.writeFileSync(data_finial, info_finial);
}

function absoluteAddress(dir_position, file_path) {
    if ("NULL" != file_path) {
        if (file_path.includes(dir_position)) {
            return file_path
        } else {
            return path.join(dir_position, file_path);
        }
    }
    return "NULL";
}

languages: Markdown Shell JavaScript

repo_language: Markdown


text:
<repo_name>BenjaminSiret/coffeemachine<file_sep>/README.md
# coffeemachine

Formation Python Dr. <NAME>.

Create a virtual coffee machine.

<file_sep>/main.py
MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money": 0,
}

QUARTER = 0.25
DIME = 0.10
NICKEL = 0.05
PENNY = 0.01

# TODO 1. Prompt user by asking "what would you like ? (espresso, latte, cappuccino): "
# TODO 2. Turn off the Coffee Machine by entering “off” to the prompt.
# TODO 3. Print report
# TODO 4. Check resources sufficient?
# TODO 5. Process coins.
# TODO 6. Check transaction successful?
# TODO 7. Make Coffee.

# FUNCTIONS

def check_resources(drink):
    """check if there is enough resources to make a drink"""
    for key, value in MENU[drink]["ingredients"].items():
        if resources[key] < value:
            print(f"Sorry there is not enough {key}.")
            return False
    return True

def coins_calculator(quarters, dimes, nickels, pennies):
    """take the numbers of coins, return the sum in dollars"""
    quarters *= QUARTER
    dimes *= DIME
    nickels *= NICKEL
    pennies *= PENNY
    return quarters + dimes + nickels + pennies

def monetary_calculator(coins, coffee_price):
    """take coins and coffee_price, return rounded difference between"""
    diff = coins - coffee_price
    return round(diff, 2)

def check_transaction(coins, coffee_price):
    """take coins and coffee_price, return true if transaction possible and add price to money, else return false"""
    if coffee_price > coins:
        print("Sorry that's not enough money. Money refunded.")
        return False
    else:
        resources['money'] += coffee_price
        return True

# MACHINE IN ACTION
should_continue = True
while should_continue:
    user_choice = input("What would you like ? (espresso, latte, cappuccino): ")

    if user_choice in MENU:
        if check_resources(user_choice):
            print("Please insert coins.")

            inserted_quarters = int(input("How many quarters ?: "))
            inserted_dimes = int(input("How many dimes ?: "))
            inserted_nickels = int(input("How many nickles ?: "))
            inserted_pennies = int(input("How many pennies?: "))

            inserted_coins = coins_calculator(inserted_quarters, inserted_dimes, inserted_nickels, inserted_pennies)
            price = MENU[user_choice]['cost']

            # if transaction ok and resources ok => make the drink and deducted the resources
            if check_transaction(inserted_coins, price):
                required_ingredients = MENU[user_choice]["ingredients"]
                monetary = monetary_calculator(inserted_coins, price)
                print(f"Here is ${monetary} in change.")
                for ingredient in required_ingredients:
                    resources[ingredient] -= required_ingredients[ingredient]
                print(f"Here is your {user_choice}. Enjoy!")

    if user_choice == "report":
        print(f"Water: {resources['water']}ml")
        print(f"Milk: {resources['milk']}ml")
        print(f"Coffee: {resources['coffee']}g")
        print(f"Money: {resources['money']}")

    elif user_choice == 'off':
        should_continue = False

languages: Markdown Python

repo_name: BenjaminSiret/coffeemachine


text:
<repo_name>buengese/LibHac<file_sep>/src/LibHac/Fs/FileSystemManagerUtils.cs
using System;
using System.Buffers;
using System.Collections.Generic;
using LibHac.Fs.Accessors;

namespace LibHac.Fs
{
    public static class FileSystemManagerUtils
    {
        public static void CopyDirectory(this FileSystemManager fs, string sourcePath, string destPath,
            CreateFileOptions options = CreateFileOptions.None, IProgressReport logger = null)
        {
            using (DirectoryHandle sourceHandle = fs.OpenDirectory(sourcePath, OpenDirectoryMode.All))
            {
                foreach (DirectoryEntry entry in fs.ReadDirectory(sourceHandle))
                {
                    string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
                    string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));

                    if (entry.Type == DirectoryEntryType.Directory)
                    {
                        fs.EnsureDirectoryExists(subDstPath);

                        fs.CopyDirectory(subSrcPath, subDstPath, options, logger);
                    }

                    if (entry.Type == DirectoryEntryType.File)
                    {
                        logger?.LogMessage(subSrcPath);
                        fs.CreateOrOverwriteFile(subDstPath, entry.Size, options);

                        fs.CopyFile(subSrcPath, subDstPath, logger);
                    }
                }
            }
        }

        public static void CopyFile(this FileSystemManager fs, string sourcePath, string destPath, IProgressReport logger = null)
        {
            using (FileHandle sourceHandle = fs.OpenFile(sourcePath, OpenMode.Read))
            using (FileHandle destHandle = fs.OpenFile(destPath, OpenMode.Write | OpenMode.Append))
            {
                const int maxBufferSize = 0x10000;

                long fileSize = fs.GetFileSize(sourceHandle);
                int bufferSize = (int)Math.Min(maxBufferSize, fileSize);

                logger?.SetTotal(fileSize);

                byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
                try
                {
                    for (long offset = 0; offset < fileSize; offset += bufferSize)
                    {
                        int toRead = (int)Math.Min(fileSize - offset, bufferSize);
                        Span<byte> buf = buffer.AsSpan(0, toRead);

                        fs.ReadFile(sourceHandle, buf, offset);
                        fs.WriteFile(destHandle, buf, offset);

                        logger?.ReportAdd(toRead);
                    }
                }
                finally
                {
                    ArrayPool<byte>.Shared.Return(buffer);
                    logger?.SetTotal(0);
                }

                fs.FlushFile(destHandle);
            }
        }

        public static IEnumerable<DirectoryEntry> EnumerateEntries(this FileSystemManager fs, string path)
        {
            return fs.EnumerateEntries(path, "*");
        }

        public static IEnumerable<DirectoryEntry> EnumerateEntries(this FileSystemManager fs, string path, string searchPattern)
        {
            return fs.EnumerateEntries(path, searchPattern, SearchOptions.RecurseSubdirectories);
        }

        public static IEnumerable<DirectoryEntry> EnumerateEntries(this FileSystemManager fs, string path, string searchPattern, SearchOptions searchOptions)
        {
            bool ignoreCase = searchOptions.HasFlag(SearchOptions.CaseInsensitive);
            bool recurse = searchOptions.HasFlag(SearchOptions.RecurseSubdirectories);

            using (DirectoryHandle sourceHandle = fs.OpenDirectory(path, OpenDirectoryMode.All))
            {
                foreach (DirectoryEntry entry in fs.ReadDirectory(sourceHandle))
                {
                    if (PathTools.MatchesPattern(searchPattern, entry.Name, ignoreCase))
                    {
                        yield return entry;
                    }

                    if (entry.Type != DirectoryEntryType.Directory || !recurse) continue;

                    string subPath = PathTools.Normalize(PathTools.Combine(path, entry.Name));

                    IEnumerable<DirectoryEntry> subEntries = fs.EnumerateEntries(subPath, searchPattern, searchOptions);

                    foreach (DirectoryEntry subEntry in subEntries)
                    {
                        subEntry.FullPath = PathTools.Combine(path, subEntry.Name);
                        yield return subEntry;
                    }
                }
            }
        }

        public static bool DirectoryExists(this FileSystemManager fs, string path)
        {
            return fs.GetEntryType(path) == DirectoryEntryType.Directory;
        }

        public static bool FileExists(this FileSystemManager fs, string path)
        {
            return fs.GetEntryType(path) == DirectoryEntryType.File;
        }

        public static void EnsureDirectoryExists(this FileSystemManager fs, string path)
        {
            path = PathTools.Normalize(path);
            if (fs.DirectoryExists(path)) return;

            PathTools.GetMountNameLength(path, out int mountNameLength).ThrowIfFailure();

            // Find the first subdirectory in the path that doesn't exist
            int i;
            for (i = path.Length - 1; i > mountNameLength + 2; i--)
            {
                if (path[i] == '/')
                {
                    string subPath = path.Substring(0, i);

                    if (fs.DirectoryExists(subPath))
                    {
                        break;
                    }
                }
            }

            // path[i] will be a '/', so skip that character
            i++;

            for (; i < path.Length; i++)
            {
                if (path[i] == '/')
                {
                    string subPath = path.Substring(0, i);

                    fs.CreateDirectory(subPath);
                }
            }

            fs.CreateDirectory(path);
        }

        public static void CreateOrOverwriteFile(this FileSystemManager fs, string path, long size)
        {
            fs.CreateOrOverwriteFile(path, size, CreateFileOptions.None);
        }

        public static void CreateOrOverwriteFile(this FileSystemManager fs, string path, long size, CreateFileOptions options)
        {
            path = PathTools.Normalize(path);

            if (fs.FileExists(path)) fs.DeleteFile(path);

            fs.CreateFile(path, size, CreateFileOptions.None);
        }
    }
}

repo_language: C#

repo_name: buengese/LibHac


text:
<repo_name>Varad-0508/Face-Detection<file_sep>/README.md
# Face-Detection
OpenCV is an open source computer vision and machine learning software library. It is a BSD-licence product thus free for both business and academic purposes.The Library provides more than 2500 algorithms that include machine learning tools for classification and clustering, image processing and vision algorithm, basic algorithms and drawing functions, GUI and I/O functions for images and videos. Some applications of these algorithms include face detection, object recognition, extracting 3D models, image processing, camera calibration, motion analysis etc.  OpenCV is written natively in C/C++. It has C++, C, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS, and Android. OpenCV was designed for computational efficiency and targeted for real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing.

branch_name: refs/heads/main