prompt
stringlengths
1.3k
3.64k
language
stringclasses
16 values
label
int64
-1
5
text
stringlengths
14
130k
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: export let doorsArray: Array<string> = ['TWO', 'THREE', 'FOUR', 'FIVE']; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
1
export let doorsArray: Array<string> = ['TWO', 'THREE', 'FOUR', 'FIVE'];
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php namespace Switchm\SmartApi\Components\Tests\ProgramNames\Get\UseCases; use Prophecy\Argument as arg; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\InputData; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\Interactor; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\OutputBoundary; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\OutputData; use Switchm\SmartApi\Components\Tests\TestCase; use Switchm\SmartApi\Queries\Dao\Rdb\ProgramNamesDao; class InteractorTest extends TestCase { private $programNamesDao; private $outputBoundary; private $target; public function setUp(): void { parent::setUp(); $this->programNamesDao = $this->prophesize(ProgramNamesDao::class); $this->outputBoundary = $this->prophesize(OutputBoundary::class); $this->target = new Interactor($this->programNamesDao->reveal(), $this->outputBoundary->reveal()); } /** * @test * @dataProvider dataProvider * @param $programFlag * @param $digitalAndBs */ public function invoke($programFlag, $digitalAndBs): void { $this->programNamesDao ->findProgramNames(arg::cetera()) ->willReturn(['data']) ->shouldBeCalled(); $this->outputBoundary ->__invoke(new OutputData(['data'])) ->willReturn() ->shouldBeCalled(); $input = new InputData( '2019-01-01 05:00:00', '2019-01-31 04:59:00', '世界', [], $digitalAndBs, $programFlag, [1, 2, 3, 4, 5, 6, 7], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25], 0, '1', [], [], 1, [0], [], ['1', '2', '3', '4', '5', '6', '0'], true ); $this->target->__invoke($input); } public function dataProvider() { After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php namespace Switchm\SmartApi\Components\Tests\ProgramNames\Get\UseCases; use Prophecy\Argument as arg; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\InputData; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\Interactor; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\OutputBoundary; use Switchm\SmartApi\Components\ProgramNames\Get\UseCases\OutputData; use Switchm\SmartApi\Components\Tests\TestCase; use Switchm\SmartApi\Queries\Dao\Rdb\ProgramNamesDao; class InteractorTest extends TestCase { private $programNamesDao; private $outputBoundary; private $target; public function setUp(): void { parent::setUp(); $this->programNamesDao = $this->prophesize(ProgramNamesDao::class); $this->outputBoundary = $this->prophesize(OutputBoundary::class); $this->target = new Interactor($this->programNamesDao->reveal(), $this->outputBoundary->reveal()); } /** * @test * @dataProvider dataProvider * @param $programFlag * @param $digitalAndBs */ public function invoke($programFlag, $digitalAndBs): void { $this->programNamesDao ->findProgramNames(arg::cetera()) ->willReturn(['data']) ->shouldBeCalled(); $this->outputBoundary ->__invoke(new OutputData(['data'])) ->willReturn() ->shouldBeCalled(); $input = new InputData( '2019-01-01 05:00:00', '2019-01-31 04:59:00', '世界', [], $digitalAndBs, $programFlag, [1, 2, 3, 4, 5, 6, 7], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25], 0, '1', [], [], 1, [0], [], ['1', '2', '3', '4', '5', '6', '0'], true ); $this->target->__invoke($input); } public function dataProvider() { return [ [ /*programFlag*/ false, /*digitalAndBs*/ 'digital', ], [ /*programFlag*/ true, /*digitalAndBs*/ 'digital', ], [ /*programFlag*/ true, /*digitalAndBs*/ 'bs1', ], [ /*programFlag*/ true, /*digitalAndBs*/ 'bs2', ], ]; } }
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: using System.Collections.Generic; namespace EagleRepair.IntegrationTests.Cli.DataProvider.TypeCheckAndCast { public static class TypeCheckAndCastDoubleDataProvider { private const string Input = @" using System; using System.Globalization; namespace Entry { public class C { public decimal M(object primitiveValue) { if (primitiveValue is Double) { decimal doubleToDecimalR; if (decimal.TryParse(((Double)primitiveValue).ToString(""R"", CultureInfo.InvariantCulture), out doubleToDecimalR)) { return doubleToDecimalR; } } return new decimal(3.4); } } }"; private const string ExpectedOutput = @" using System; using System.Globalization; namespace Entry { public class C { public decimal M(object primitiveValue) { if (primitiveValue is Double d) { decimal doubleToDecimalR; if (decimal.TryParse(d.ToString(""R"", CultureInfo.InvariantCulture), out doubleToDecimalR)) { return doubleToDecimalR; } } return new decimal(3.4); } } }"; public static IEnumerable<object[]> TestCases() { yield return new object[] {Input, ExpectedOutput}; } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
3
using System.Collections.Generic; namespace EagleRepair.IntegrationTests.Cli.DataProvider.TypeCheckAndCast { public static class TypeCheckAndCastDoubleDataProvider { private const string Input = @" using System; using System.Globalization; namespace Entry { public class C { public decimal M(object primitiveValue) { if (primitiveValue is Double) { decimal doubleToDecimalR; if (decimal.TryParse(((Double)primitiveValue).ToString(""R"", CultureInfo.InvariantCulture), out doubleToDecimalR)) { return doubleToDecimalR; } } return new decimal(3.4); } } }"; private const string ExpectedOutput = @" using System; using System.Globalization; namespace Entry { public class C { public decimal M(object primitiveValue) { if (primitiveValue is Double d) { decimal doubleToDecimalR; if (decimal.TryParse(d.ToString(""R"", CultureInfo.InvariantCulture), out doubleToDecimalR)) { return doubleToDecimalR; } } return new decimal(3.4); } } }"; public static IEnumerable<object[]> TestCases() { yield return new object[] {Input, ExpectedOutput}; } } }
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import actionCreaterFactory from "typescript-fsa"; import { Card } from "../../domain/entity/todoCard"; const actionCraeter = actionCreaterFactory(); const todoCardActions = { setTodoCardTitle: actionCraeter<string>("SET_TODO_CARD_TITLE"), addTodoCardList: actionCraeter<string>("ADD_TODO_CARD_LIST"), setTodoText: actionCraeter<{provTodoText: string, index: number}>("SET_TODO_TEXT"), addTodo: actionCraeter<{provTodoText: string, doneFlg: boolean, index: number}>("ADD_TODOS"), setDoneFlg: actionCraeter<{doneFlg: boolean, cardIndex: number, index: number}>("SET_DONE_FLG"), sortTodoCardList: actionCraeter<{card: Card, index: number, atIndex: number}>("SORT_TODO_CARD_LIST"), deleteTodoCard: actionCraeter<{cardIndex: number}>("DELETE_TODO_CARD"), deleteTodo: actionCraeter<{cardIndex: number, todoIndex: number}>("DELETE_TODO"), }; export default todoCardActions; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
2
import actionCreaterFactory from "typescript-fsa"; import { Card } from "../../domain/entity/todoCard"; const actionCraeter = actionCreaterFactory(); const todoCardActions = { setTodoCardTitle: actionCraeter<string>("SET_TODO_CARD_TITLE"), addTodoCardList: actionCraeter<string>("ADD_TODO_CARD_LIST"), setTodoText: actionCraeter<{provTodoText: string, index: number}>("SET_TODO_TEXT"), addTodo: actionCraeter<{provTodoText: string, doneFlg: boolean, index: number}>("ADD_TODOS"), setDoneFlg: actionCraeter<{doneFlg: boolean, cardIndex: number, index: number}>("SET_DONE_FLG"), sortTodoCardList: actionCraeter<{card: Card, index: number, atIndex: number}>("SORT_TODO_CARD_LIST"), deleteTodoCard: actionCraeter<{cardIndex: number}>("DELETE_TODO_CARD"), deleteTodo: actionCraeter<{cardIndex: number, todoIndex: number}>("DELETE_TODO"), }; export default todoCardActions;
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // // Util.swift // WebRTCHandsOn // // Created by JaesungMoon on 2017/06/18. // Copyright © 2017年 JaesungMoon. All rights reserved. // import Foundation func LOG(_ body: String = "", function: String = #function, line: Int = #line){ print("[\(function)] : [\(line)] \(body)") } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
2
// // Util.swift // WebRTCHandsOn // // Created by JaesungMoon on 2017/06/18. // Copyright © 2017年 JaesungMoon. All rights reserved. // import Foundation func LOG(_ body: String = "", function: String = #function, line: Int = #line){ print("[\(function)] : [\(line)] \(body)") }
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: const path = require('path') const fs = require('fs') const shortid = require('shortid') const eachSeries = require('async/eachSeries') const protectedRoute = require('../authenticate/protected-route') const sgMail = require('@sendgrid/mail') const { check, validationResult } = require('express-validator') const db = require('../lib/db') try { sgMail.setApiKey(process.env.SENDGRID_API_KEY) } catch (error) { console.error(error) } function assignments (app) { let sanitizationChain = [] app.post( '/users/:user_id/tasks/:task_id/assignments/create', protectedRoute, (req, res, next) => { // build sanitization chain dynamically sanitizationChain = Object .keys(req.body) .filter(key => key.indexOf('assignee_email_') > -1) .map(key => check(key).isEmail().trim().escape()) next() }, sanitizationChain, async function (req, res) { const { user_id, task_id } = req.params const errors = validationResult(req) if (!errors.isEmpty()) { req.flash('data', req.body) req.flash('error', 'One or several inputs are invalid.') return res.redirect(`/users/${req.user}/tasks`) } if (req.params.user_id !== req.user) { return res.redirect(`/users/${req.user}/tasks`) } const listOfAssignees = Object .keys(req.body) .filter(key => key.indexOf('assignee_email_') > -1) .map(id => req.body[id]) .filter(email => { const EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/ return !!email.match(EMAIL_REGEXP) }) let ownEmailAddress = null try { ownEmailAddress = await db.get(`user!${req.user}:email`) } catch (err) {} eachSeries( listOfAssignees, (email, callback) => { let newAssignmentId = shortid.generate().toLowerCase() let newAssignmentKey = `user!${req.user}!task!${task_id}!assignment!${newAssignmentId}` After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
2
const path = require('path') const fs = require('fs') const shortid = require('shortid') const eachSeries = require('async/eachSeries') const protectedRoute = require('../authenticate/protected-route') const sgMail = require('@sendgrid/mail') const { check, validationResult } = require('express-validator') const db = require('../lib/db') try { sgMail.setApiKey(process.env.SENDGRID_API_KEY) } catch (error) { console.error(error) } function assignments (app) { let sanitizationChain = [] app.post( '/users/:user_id/tasks/:task_id/assignments/create', protectedRoute, (req, res, next) => { // build sanitization chain dynamically sanitizationChain = Object .keys(req.body) .filter(key => key.indexOf('assignee_email_') > -1) .map(key => check(key).isEmail().trim().escape()) next() }, sanitizationChain, async function (req, res) { const { user_id, task_id } = req.params const errors = validationResult(req) if (!errors.isEmpty()) { req.flash('data', req.body) req.flash('error', 'One or several inputs are invalid.') return res.redirect(`/users/${req.user}/tasks`) } if (req.params.user_id !== req.user) { return res.redirect(`/users/${req.user}/tasks`) } const listOfAssignees = Object .keys(req.body) .filter(key => key.indexOf('assignee_email_') > -1) .map(id => req.body[id]) .filter(email => { const EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/ return !!email.match(EMAIL_REGEXP) }) let ownEmailAddress = null try { ownEmailAddress = await db.get(`user!${req.user}:email`) } catch (err) {} eachSeries( listOfAssignees, (email, callback) => { let newAssignmentId = shortid.generate().toLowerCase() let newAssignmentKey = `user!${req.user}!task!${task_id}!assignment!${newAssignmentId}` db.get(newAssignmentKey, (error) => { if (!error) { newAssignmentId = shortid.generate().toLowerCase() newAssignmentKey = `user!${req.user}!task!${task_id}!assignment!${newAssignmentId}` } const newAssignmentDate = new Date() const startOffset = Math.ceil(Math.random() * 10000) const newAssignment = { captions: {}, accepted: false, completed: false, date_created: newAssignmentDate, date_updated: newAssignmentDate, id: newAssignmentId, task_id: task_id, start_offset: startOffset, email: email, user: null } if (email === ownEmailAddress) { newAssignment.accepted = true newAssignment.user = req.user return db.get(`user!${user_id}!task!${task_id}`, (error, task) => { if (error) { return callback(error) } const userAssignment = { user_id: user_id, task_id: task_id, assignment_id: newAssignmentId, title: task.title } return db.put(`user!${req.user}!assignment!${newAssignmentId}`, userAssignment, (error) => { if (error) { return callback(error) } db.put(newAssignmentKey, newAssignment, callback) }) }) } else { const host = process.env.development ? 'http://localhost:80' : 'https://trk.network' const message = { to: email, from: '<EMAIL>', subject: 'You are invited to collaborate to a mechanical turk project', template_id: 'd-fffadd0bcf184f2196a5c50ac011c707', dynamic_template_data: { inviteLink: `${host}/users/${req.user}/tasks/${task_id}/assignments/${newAssignmentId}` } } try { sgMail.send(message, error => { if (error) { throw error } db.put(newAssignmentKey, newAssignment, callback) }) } catch (error) { db.put(newAssignmentKey, newAssignment, callback) } } }) }, (err) => { if (err) { console.error(err) req.flash('error', 'Unable to invite all collaborators, please try again.') } return res.redirect(`/users/${req.user}/tasks/${task_id}`) } ) } ) app.get('/users/:user_id/tasks/:task_id/assignments/:assignment_id', protectedRoute, async function (req, res) { const { user_id, assignment_id, task_id } = req.params try { const task = await db.get(`user!${user_id}!task!${task_id}`) const assignmentKey = `user!${user_id}!task!${task_id}!assignment!${assignment_id}` const assignment = await db.get(assignmentKey) let taskCount = task.limit || task.files.length let textPreview = null if (task.type === 'text') { const textContent = fs.readFileSync(path.join(__dirname, '../text', task_id, task.files[0]), 'utf8') taskCount = task.limit || textContent.split('\n').length textPreview = textContent.split('\n')[0] } if (!assignment.accepted) { const params = { previewFile: task.files[0], task_id, assignment_id, type: task.type, warning: task.warning, taskCount: taskCount, textPreview: textPreview, taskPrice: task.price || 0.1, pageTitle: 'TRK - Project Preview' } return res.render('preview', params) } if (assignment.user !== req.user) { req.flash('error', 'Task not found') return res.redirect(`/users/${user_id}/tasks`) } const params = { files: task.files, user_id: user_id, task_id, assignment_id, type: task.type, warning: task.warning, title: task.title, instructions: task.instructions, start_offset: assignment.start_offset, taskCount: taskCount, pageTitle: 'TRK - Training Tool' } return res.render('caption', params) } catch (err) { console.log(err) if (err.notFound) { req.flash('error', 'Task not found') return res.redirect(`/404`) } else { req.flash('error', 'Internal server error') return res.redirect(`/404`) } } }) app.get('/users/:user_id/tasks/:task_id/assignments/:assignment_id/accept', protectedRoute, async function (req, res) { const { user_id, assignment_id, task_id } = req.params try { const task = await db.get(`user!${user_id}!task!${task_id}`) const assignmentKey = `user!${user_id}!task!${task_id}!assignment!${assignment_id}` const assignment = await db.get(assignmentKey) assignment.accepted = true assignment.user = req.user await db.put(assignmentKey, assignment) const userAssignment = { user_id: user_id, task_id: task_id, assignment_id: assignment_id, title: task.title } await db.put(`user!${req.user}!assignment!${assignment_id}`, userAssignment) return res.redirect(`/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}`) } catch (err) { console.log(err) req.flash('error', 'Internal server error') return res.redirect(`/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}`) } }) app.get('/users/:user_id/tasks/:task_id/assignments/:assignment_id/progress', async function (req, res) { if (!req.isAuthenticated()) { return res.json({ status: 'failure', error: 'user needs to sign in' }) } const { user_id, assignment_id, task_id } = req.params try { const assignmentKey = `user!${user_id}!task!${task_id}!assignment!${assignment_id}` const assignment = await db.get(assignmentKey) const progress = parseFloat(req.query.progress) if (Number.isNaN(progress)) { throw new Error('Invalid input') } assignment.progress = progress await db.put(assignmentKey, assignment) return res.json({status: 'success'}) } catch (err) { console.log(err) return res.json({status: 'failure', error: err}) } }) app.get('/users/:user_id/tasks/:task_id/assignments/:assignment_id/submit', protectedRoute, async function (req, res) { const { user_id, assignment_id, task_id } = req.params try { const task = await db.get(`user!${user_id}!task!${task_id}`) const params = { user_id: user_id, task_id: task_id, assignment_id: assignment_id, title: task.title, ask_name: task.ask_name, ask_location: task.ask_location, ask_age: task.ask_age, ask_expertise: task.ask_expertise, actionUrl: `/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}/submit`, pageTitle: 'TRK - Submit Captions' } res.render('submit', params) } catch (err) { console.log(err) req.flash('error', 'Internal server error') return res.redirect(`/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}`) } }) app.post( '/users/:user_id/tasks/:task_id/assignments/:assignment_id/submit', protectedRoute, [ check('name').trim().escape(), check('location').trim().escape(), check('age').trim().escape(), check('expertise').trim().escape(), check('captions').trim() ], async function (req, res) { const { user_id, assignment_id, task_id } = req.params const errors = validationResult(req) if (!errors.isEmpty()) { req.flash('data', req.body) req.flash('error', 'One or several inputs are invalid.') return res.redirect(`/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}/submit`) } try { const assignmentKey = `user!${user_id}!task!${task_id}!assignment!${assignment_id}` const assignment = await db.get(assignmentKey) const captions = JSON.parse(req.body.captions) if (!Array.isArray(captions)) { throw new Error('Captions are not an array') } // TODO validate captions // const invalidCaptions = captions // .some(caption => { // return Number.isNaN(parseFloat(caption.x)) || // Number.isNaN(parseFloat(caption.y)) || // Number.isNaN(parseFloat(caption.width)) || // Number.isNaN(parseFloat(caption.height)) || // typeof caption.name !== 'string' || // (typeof caption.id !== 'string' && typeof caption.id !== 'number') || // Object.keys(caption).length !== 6 // }) // if (invalidCaptions) { // throw new Error('One or more options are invalid') // } assignment.captions = JSON.parse(req.body.captions) assignment.completed = true if (req.body.name) assignment.assigneeName = req.body.name if (req.body.location) assignment.assigneeLocation = req.body.location if (req.body.age) assignment.assigneeAge = req.body.age if (req.body.expertise) assignment.assigneeExpertise = req.body.expertise await db.put(assignmentKey, assignment) } catch (err) { console.log('err', err) req.flash('error', 'Internal server error. Please try again.') return res.redirect(`/users/${user_id}/tasks/${task_id}/assignments/${assignment_id}/submit`) } res.redirect('/thank-you') } ) app.get('/thank-you', async function (req, res) { res.render('thank-you', { pageTitle: 'TRK - Thank you' }) }) } module.exports = assignments
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php declare(strict_types=1); use Illuminate\Routing\Router; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::group(['middleware' => 'auth:api'], function (Router $router) { $router->group(['prefix' => 'account', 'namespace' => 'Account'], function (Router $router): void { $router->resource('/', 'AccountApiController', ['only' => ['index']]); $router->resource('bs', 'BsAccountApiController', ['only' => ['store', 'update']]); $router->resource('pl', 'PlAccountApiController', ['only' => ['store', 'update']]); }); $router->group(['prefix' => 'journal', 'namespace' => 'Journal'], function (Router $router): void { $router->post('trial-balance', 'LedgerApiController@showTrialBalance'); $router->get('opening/{bsAccountId}', 'LedgerApiController@showOpeningBalance'); $router->get('ledger/{accountId}/{month}', 'LedgerApiController@index'); $router->resource('schedule', 'ScheduleApiController', ['only' => ['index', 'store', 'update']]); }); $router->resource('journal', 'Journal\JournalApiController', ['only' => ['store', 'update', 'destroy']]); }); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php declare(strict_types=1); use Illuminate\Routing\Router; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::group(['middleware' => 'auth:api'], function (Router $router) { $router->group(['prefix' => 'account', 'namespace' => 'Account'], function (Router $router): void { $router->resource('/', 'AccountApiController', ['only' => ['index']]); $router->resource('bs', 'BsAccountApiController', ['only' => ['store', 'update']]); $router->resource('pl', 'PlAccountApiController', ['only' => ['store', 'update']]); }); $router->group(['prefix' => 'journal', 'namespace' => 'Journal'], function (Router $router): void { $router->post('trial-balance', 'LedgerApiController@showTrialBalance'); $router->get('opening/{bsAccountId}', 'LedgerApiController@showOpeningBalance'); $router->get('ledger/{accountId}/{month}', 'LedgerApiController@index'); $router->resource('schedule', 'ScheduleApiController', ['only' => ['index', 'store', 'update']]); }); $router->resource('journal', 'Journal\JournalApiController', ['only' => ['store', 'update', 'destroy']]); });
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: require 'rails_helper' describe Custom::CssController do describe 'routing' do it 'routes to #override.css' do expect(get('/custom/override.css')).to route_to('custom/css#show', format: 'css') end end end After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
1
require 'rails_helper' describe Custom::CssController do describe 'routing' do it 'routes to #override.css' do expect(get('/custom/override.css')).to route_to('custom/css#show', format: 'css') end end end
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: #!/bin/sh # source this file to get environment setup for the # pyang below here export PATH="$PWD/bin:$PATH" export MANPATH="$PWD/man:$MANPATH" export PYTHONPATH="$PWD:$PYTHONPATH" export YANG_MODPATH="$PWD/modules:$YANG_MODPATH" export PYANG_XSLT_DIR="$PWD/xslt" export PYANG_RNG_LIBDIR="$PWD/schema" export W="$PWD" After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
2
#!/bin/sh # source this file to get environment setup for the # pyang below here export PATH="$PWD/bin:$PATH" export MANPATH="$PWD/man:$MANPATH" export PYTHONPATH="$PWD:$PYTHONPATH" export YANG_MODPATH="$PWD/modules:$YANG_MODPATH" export PYANG_XSLT_DIR="$PWD/xslt" export PYANG_RNG_LIBDIR="$PWD/schema" export W="$PWD"
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: using System; namespace BowlingGame { public class Game { private const int RollsPerGame = 20; private const int FramesPerGame = 10; private const int MaxFrameScore = 10; private int[] _rolls = new int[RollsPerGame]; private int _roll = 0; public void Roll(int pins) { _rolls[_roll++] = pins; } public int Score() { // frameIndex is the first roll of each frame var frameIndex = 0; var score = 0; for(var frame = 0; frame < FramesPerGame; frame++) { if (IsSpare(frameIndex)) { score += GetTotalSpareScore(frameIndex); frameIndex += 2; continue; } if (IsStrike(frameIndex)) { score += GetTotalStrikeScore(frameIndex); frameIndex += 1; continue; } // neither spare nor strike score += GetTotalFrameScore(frameIndex); frameIndex += 2; } return score; } private int GetTotalFrameScore(int frameIndex) => _rolls[frameIndex] + _rolls[frameIndex + 1]; // the spare bonus is the value of // the first roll of the next frame private int GetTotalSpareScore(int frameIndex) => MaxFrameScore + _rolls[frameIndex + 2]; // the strike bonus is the value of // both rolls of the next frame private int GetTotalStrikeScore(int frameIndex) => MaxFrameScore + _rolls[frameIndex + 1] + _rolls[frameIndex + 2]; private bool IsStrike(int frameIndex) => _rolls[frameIndex] == MaxFrameScore; private bool IsSpare(int frameIndex) => _rolls[frameIndex] + _rolls[frameIndex + 1] == MaxFrameScore; } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
4
using System; namespace BowlingGame { public class Game { private const int RollsPerGame = 20; private const int FramesPerGame = 10; private const int MaxFrameScore = 10; private int[] _rolls = new int[RollsPerGame]; private int _roll = 0; public void Roll(int pins) { _rolls[_roll++] = pins; } public int Score() { // frameIndex is the first roll of each frame var frameIndex = 0; var score = 0; for(var frame = 0; frame < FramesPerGame; frame++) { if (IsSpare(frameIndex)) { score += GetTotalSpareScore(frameIndex); frameIndex += 2; continue; } if (IsStrike(frameIndex)) { score += GetTotalStrikeScore(frameIndex); frameIndex += 1; continue; } // neither spare nor strike score += GetTotalFrameScore(frameIndex); frameIndex += 2; } return score; } private int GetTotalFrameScore(int frameIndex) => _rolls[frameIndex] + _rolls[frameIndex + 1]; // the spare bonus is the value of // the first roll of the next frame private int GetTotalSpareScore(int frameIndex) => MaxFrameScore + _rolls[frameIndex + 2]; // the strike bonus is the value of // both rolls of the next frame private int GetTotalStrikeScore(int frameIndex) => MaxFrameScore + _rolls[frameIndex + 1] + _rolls[frameIndex + 2]; private bool IsStrike(int frameIndex) => _rolls[frameIndex] == MaxFrameScore; private bool IsSpare(int frameIndex) => _rolls[frameIndex] + _rolls[frameIndex + 1] == MaxFrameScore; } }
Below is an extract from a C program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid C code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical C concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., kernel development and compiler design). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching C. It should be similar to a school exercise, a tutorial, or a C course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: #include <list> #include <libtensor/core/contraction2_list_builder.h> #include "../test_utils.h" using namespace libtensor; namespace { struct loop_list_node { private: size_t m_weight; size_t m_inca, m_incb, m_incc; public: loop_list_node() : m_weight(0), m_inca(0), m_incb(0), m_incc(0) { } loop_list_node(size_t weight, size_t inca, size_t incb, size_t incc) : m_weight(weight), m_inca(inca), m_incb(incb), m_incc(incc) { } }; class loop_list_adapter { private: std::list<loop_list_node> &m_list; public: loop_list_adapter(std::list<loop_list_node> &list) : m_list(list) { } void append(size_t weight, size_t inca, size_t incb, size_t incc) { m_list.push_back(loop_list_node(weight, inca, incb, incc)); } }; } // unnamed namespace int test_1() { static const char testname[] = "contraction2_list_builder::test_1()"; try { contraction2<1, 3, 1> contr; contr.contract(0, 3); libtensor::index<2> ia1, ia2; ia2[0] = 5; ia2[1] = 9; libtensor::index<4> ib1, ib2; ib2[0] = 9; ib2[1] = 9; ib2[2] = 9; ib2[3] = 5; libtensor::index<4> ic1, ic2; ic2[0] = 9; ic2[1] = 9; ic2[2] = 9; ic2[3] = 9; dimensions<2> dima(index_range<2>(ia1, ia2)); dimensions<4> dimb(index_range<4>(ib1, ib2)); dimensions<4> dimc(index_range<4>(ic1, ic2)); std::list<loop_list_node> lst; loop_list_adapter adapter(lst); contraction2_list_builder<1, 3, 1> bldr(contr); bldr.populate(adapter, dima, dimb, dimc); } catch(exception &e) { return fail_test(testname, __FILE__, __LINE__, e.what()); } return 0; } int main() { return test_1(); } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
c
2
#include <list> #include <libtensor/core/contraction2_list_builder.h> #include "../test_utils.h" using namespace libtensor; namespace { struct loop_list_node { private: size_t m_weight; size_t m_inca, m_incb, m_incc; public: loop_list_node() : m_weight(0), m_inca(0), m_incb(0), m_incc(0) { } loop_list_node(size_t weight, size_t inca, size_t incb, size_t incc) : m_weight(weight), m_inca(inca), m_incb(incb), m_incc(incc) { } }; class loop_list_adapter { private: std::list<loop_list_node> &m_list; public: loop_list_adapter(std::list<loop_list_node> &list) : m_list(list) { } void append(size_t weight, size_t inca, size_t incb, size_t incc) { m_list.push_back(loop_list_node(weight, inca, incb, incc)); } }; } // unnamed namespace int test_1() { static const char testname[] = "contraction2_list_builder::test_1()"; try { contraction2<1, 3, 1> contr; contr.contract(0, 3); libtensor::index<2> ia1, ia2; ia2[0] = 5; ia2[1] = 9; libtensor::index<4> ib1, ib2; ib2[0] = 9; ib2[1] = 9; ib2[2] = 9; ib2[3] = 5; libtensor::index<4> ic1, ic2; ic2[0] = 9; ic2[1] = 9; ic2[2] = 9; ic2[3] = 9; dimensions<2> dima(index_range<2>(ia1, ia2)); dimensions<4> dimb(index_range<4>(ib1, ib2)); dimensions<4> dimc(index_range<4>(ic1, ic2)); std::list<loop_list_node> lst; loop_list_adapter adapter(lst); contraction2_list_builder<1, 3, 1> bldr(contr); bldr.populate(adapter, dima, dimb, dimc); } catch(exception &e) { return fail_test(testname, __FILE__, __LINE__, e.what()); } return 0; } int main() { return test_1(); }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: Rails.application.routes.draw do resources :tests, only: %i[index] end After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
2
Rails.application.routes.draw do resources :tests, only: %i[index] end
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Java concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package br.com.whatsappandroid.cursoandroid.whatsapp.activity; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.rtoshiro.util.format.SimpleMaskFormatter; import com.github.rtoshiro.util.format.text.MaskTextWatcher; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Random; import br.com.whatsappandroid.cursoandroid.whatsapp.R; import br.com.whatsappandroid.cursoandroid.whatsapp.helper.Permissao; import br.com.whatsappandroid.cursoandroid.whatsapp.helper.Preferencias; public class LoginActivity extends AppCompatActivity { private EditText paisCodigo; private EditText ddd; private EditText telefone; private EditText nome; private Button botaoCadastrar; //PERMISSOES A PARTIR DO SDK 23 private String[] permissoesNecessarias = new String[]{ Manifest.permission.SEND_SMS, Manifest.permission.INTERNET }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Permissao.validaPermissoes(1, this, permissoesNecessarias); telefone = findViewById(R.id.editTextTelefone); paisCodigo = findViewById(R.id.editTextCodigoPais); ddd = findViewById(R.id.editTextDdd); nome = findViewById(R.id.editTextNome); botaoCadastrar = findViewById(R.id.buttonCadastrarTelefone); //definir mascaras SimpleMaskFormatter simpleMaskTelefone = new SimpleMaskFormatter("N After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
java
2
package br.com.whatsappandroid.cursoandroid.whatsapp.activity; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.rtoshiro.util.format.SimpleMaskFormatter; import com.github.rtoshiro.util.format.text.MaskTextWatcher; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Random; import br.com.whatsappandroid.cursoandroid.whatsapp.R; import br.com.whatsappandroid.cursoandroid.whatsapp.helper.Permissao; import br.com.whatsappandroid.cursoandroid.whatsapp.helper.Preferencias; public class LoginActivity extends AppCompatActivity { private EditText paisCodigo; private EditText ddd; private EditText telefone; private EditText nome; private Button botaoCadastrar; //PERMISSOES A PARTIR DO SDK 23 private String[] permissoesNecessarias = new String[]{ Manifest.permission.SEND_SMS, Manifest.permission.INTERNET }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Permissao.validaPermissoes(1, this, permissoesNecessarias); telefone = findViewById(R.id.editTextTelefone); paisCodigo = findViewById(R.id.editTextCodigoPais); ddd = findViewById(R.id.editTextDdd); nome = findViewById(R.id.editTextNome); botaoCadastrar = findViewById(R.id.buttonCadastrarTelefone); //definir mascaras SimpleMaskFormatter simpleMaskTelefone = new SimpleMaskFormatter("NNNNN-NNNN"); SimpleMaskFormatter simpleMaskPaisCodigo = new SimpleMaskFormatter("+NN"); SimpleMaskFormatter simpleMaskDdd = new SimpleMaskFormatter("NN"); //declara mascara MaskTextWatcher maskTelefone = new MaskTextWatcher(telefone, simpleMaskTelefone); MaskTextWatcher maskPaisCodigo = new MaskTextWatcher(paisCodigo, simpleMaskPaisCodigo); MaskTextWatcher maskDdd = new MaskTextWatcher(ddd, simpleMaskDdd); //Aplica mascara telefone.addTextChangedListener(maskTelefone); //responsável por formatar paisCodigo.addTextChangedListener(maskPaisCodigo); ddd.addTextChangedListener(maskDdd); botaoCadastrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String nomeUsuario = nome.getText().toString(); String telefoneCompleto = (paisCodigo.getText().toString() + ddd.getText().toString() + telefone.getText().toString()).replace("+", "").replace("-", ""); //gerar Token Random randomico = new Random(); int intToken = randomico.nextInt(9999 - 100) + 1000; String token = String.valueOf(intToken); String mensagemEnvio = "WhatsApp Código de Confirmação: " + token + " "; Log.i("Token", "T: " + token); //Salvar dados para validação Preferencias preferencias = new Preferencias(getApplicationContext()); //preferencias.salvarUsuarioPreferencia(nomeUsuario, telefoneCompleto, token); //HashMap<String, String> usuario = preferencias.getDadosUsuario(); //Log.i("TOKEN", "T: " + usuario.get("token") + " Nome: " + usuario.get("nome") + " Telefone: " + usuario.get("telefone")); //Envio de SMS - precisa do + boolean enviadoSMS = enviaSMS("+" + telefoneCompleto, mensagemEnvio); if(enviadoSMS){ Intent validacao = new Intent(LoginActivity.this, ValidadorActivity.class); startActivity(validacao); finish(); //destroi activity atual } else { Toast.makeText(LoginActivity.this, "Problema ao enviar o SMS, tente novamente", Toast.LENGTH_LONG).show(); } } }); } private boolean enviaSMS(String telefone, String msg){ try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(telefone, "", msg, null, null); return true; } catch (Exception e){ e.printStackTrace(); return false; } } //informa usuario que precisa permitir public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){ super.onRequestPermissionsResult(requestCode, permissions, grantResults); //override for(int resultado : grantResults) { if(resultado == PackageManager.PERMISSION_DENIED){ alertaValidacaoPermissao(); } } } private void alertaValidacaoPermissao() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Permissões Negadas"); builder.setMessage("Para utilizar o App, é necessário aceitar as permissões"); builder.setPositiveButton("CONFIRMA", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); AlertDialog dialog = builder.create(); dialog.show(); } }
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package tahery.meslage.epicture import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import tahery.meslage.epicture.LayoutAdapters.AccountImagesAdapter import kotlinx.android.synthetic.main.activity_account_images.* import tahery.meslage.epicture.ImgurService.RunnerItImgurAccount import tahery.meslage.epicture.OauthReleated.clientInfo class AccountImagesActivity : AppCompatActivity(){ private var accountImagesWrap = AccountImagesWrapper() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account_images) //sounds good doesn't work RunnerItImgurAccount.runAccountImages(clientInfo.access_token, this, accountImages) } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
1
package tahery.meslage.epicture import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import tahery.meslage.epicture.LayoutAdapters.AccountImagesAdapter import kotlinx.android.synthetic.main.activity_account_images.* import tahery.meslage.epicture.ImgurService.RunnerItImgurAccount import tahery.meslage.epicture.OauthReleated.clientInfo class AccountImagesActivity : AppCompatActivity(){ private var accountImagesWrap = AccountImagesWrapper() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account_images) //sounds good doesn't work RunnerItImgurAccount.runAccountImages(clientInfo.access_token, this, accountImages) } }
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package com.geek.kotlin13.ui.fragments import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import com.geek.kotlin13.MainViewModel import com.geek.kotlin13.base.BaseFragment import com.geek.kotlin13.databinding.FragmentListBinding import com.geek.kotlin13.ui.adapters.MyAdapter class ListFragment : BaseFragment<FragmentListBinding>() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) liveData.observer.observe(requireActivity(), { binding.recList.adapter = MyAdapter(liveData.getHistory()) }) } override fun initLiveData(): MainViewModel { return ViewModelProvider(requireActivity()).get(MainViewModel::class.java) } override fun bind(): FragmentListBinding { return FragmentListBinding.inflate(layoutInflater) } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
2
package com.geek.kotlin13.ui.fragments import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import com.geek.kotlin13.MainViewModel import com.geek.kotlin13.base.BaseFragment import com.geek.kotlin13.databinding.FragmentListBinding import com.geek.kotlin13.ui.adapters.MyAdapter class ListFragment : BaseFragment<FragmentListBinding>() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) liveData.observer.observe(requireActivity(), { binding.recList.adapter = MyAdapter(liveData.getHistory()) }) } override fun initLiveData(): MainViewModel { return ViewModelProvider(requireActivity()).get(MainViewModel::class.java) } override fun bind(): FragmentListBinding { return FragmentListBinding.inflate(layoutInflater) } }
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import { Request, Response } from "express"; import { AppError } from "../domain/errors/AppError"; import { CreateCompleteUserService } from "../domain/services/CreateCompleteUserService"; type BodyParams = { email?: any password?: any username?: any permissions?: any[] roles?: any[] } export class CreateCompleteUserController { constructor( private readonly createUserCompleteService: CreateCompleteUserService ) { } handle = async (request: Request, response: Response) => { const { email, password, username, permissions=[], roles=[] } = request.body as BodyParams const validations = [] if (!email) validations.push("Need to pass a valid email") if (!password) validations.push("Need to pass a valid password") if (!username) validations.push("Need to pass a valid username") if (validations.length > 0) return response.status(400).json({ errors: validations }) try { const user = await this.createUserCompleteService.execute({ email, password, username, permissionsNames: permissions, rolesNames: roles }) return response.status(201).json(user) } catch (err) { if (err instanceof AppError) { return response.status(err.statusCode).json(err.body) } else { console.log(err) return response.status(500).json({ "errors": 'Server error' }) } } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
3
import { Request, Response } from "express"; import { AppError } from "../domain/errors/AppError"; import { CreateCompleteUserService } from "../domain/services/CreateCompleteUserService"; type BodyParams = { email?: any password?: any username?: any permissions?: any[] roles?: any[] } export class CreateCompleteUserController { constructor( private readonly createUserCompleteService: CreateCompleteUserService ) { } handle = async (request: Request, response: Response) => { const { email, password, username, permissions=[], roles=[] } = request.body as BodyParams const validations = [] if (!email) validations.push("Need to pass a valid email") if (!password) validations.push("Need to pass a valid password") if (!username) validations.push("Need to pass a valid username") if (validations.length > 0) return response.status(400).json({ errors: validations }) try { const user = await this.createUserCompleteService.execute({ email, password, username, permissionsNames: permissions, rolesNames: roles }) return response.status(201).json(user) } catch (err) { if (err instanceof AppError) { return response.status(err.statusCode).json(err.body) } else { console.log(err) return response.status(500).json({ "errors": 'Server error' }) } } } }
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: {%extends 'annuaire/base.html' %} {% block content %} <div class="vcontainer"> <h1>{{titre}}</h1> <form action="." method='POST'> {% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="submit" value="modifier"> <div style="width:20px;"></div> <a href="{% url 'delete' pk=object.id %}">Effacer</a> </div> </form> </div> {% endblock content %} After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
{%extends 'annuaire/base.html' %} {% block content %} <div class="vcontainer"> <h1>{{titre}}</h1> <form action="." method='POST'> {% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="submit" value="modifier"> <div style="width:20px;"></div> <a href="{% url 'delete' pk=object.id %}">Effacer</a> </div> </form> </div> {% endblock content %}
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: #!/bin/bash environment=$1 echo $environment silver_path=`pwd` echo $silver_path cd $ansiblepath && ansible-playbook full-deploy.yml -i inventories/$environment/ After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
2
#!/bin/bash environment=$1 echo $environment silver_path=`pwd` echo $silver_path cd $ansiblepath && ansible-playbook full-deploy.yml -i inventories/$environment/
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: require 'acts_as_tokenizable' After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
1
require 'acts_as_tokenizable'
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations. - Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments. - Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments. - Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design. - Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code. The extract: SELECT * FROM sakila.payment LIMIT 10; SELECT payment_id,rental_id,amount, rental_id * amount AS total_amount FROM sakila.payment ORDER BY payment_id LIMIT 20; SELECT 2*6; SELECT Trim(' ab v '); SELECT NOW(); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
sql
1
SELECT * FROM sakila.payment LIMIT 10; SELECT payment_id,rental_id,amount, rental_id * amount AS total_amount FROM sakila.payment ORDER BY payment_id LIMIT 20; SELECT 2*6; SELECT Trim(' ab v '); SELECT NOW();
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: --- author: author1 title: Post One layout: default_post categories: - iOS - Mobile --- Author one post one After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
1
--- author: author1 title: Post One layout: default_post categories: - iOS - Mobile --- Author one post one
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: # [VM Scale Set Extensions] (https://docs.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-extensions-configuration-samples) - 01/13/2017 * Putting customized microservices on your VM scaleset to do VM specific tasks such as resetting passwords or executing scripts ## How to install <br> The below command is an example of how to install the CustomScriptForLinux extension on a scale set. You must pass in the necessary settings for a successful install and this will update the VMSS model. ``` juluk@justins-mbp-2:~/documents/github/Azure-For-Everyone-Else$ az vmss extension set --resource-group exportvmss --vmss-name linuxvmss --publisher Microsoft.OSTCExtensions --name CustomScriptForLinux --version 1.5 --settings '{"fileUris": ["https://raw.githubusercontent.com/gatneil/scripts/master/hello.sh"], "commandToExecute": "sh hello.sh"}' ``` ## Resources After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
3
# [VM Scale Set Extensions] (https://docs.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-extensions-configuration-samples) - 01/13/2017 * Putting customized microservices on your VM scaleset to do VM specific tasks such as resetting passwords or executing scripts ## How to install <br> The below command is an example of how to install the CustomScriptForLinux extension on a scale set. You must pass in the necessary settings for a successful install and this will update the VMSS model. ``` juluk@justins-mbp-2:~/documents/github/Azure-For-Everyone-Else$ az vmss extension set --resource-group exportvmss --vmss-name linuxvmss --publisher Microsoft.OSTCExtensions --name CustomScriptForLinux --version 1.5 --settings '{"fileUris": ["https://raw.githubusercontent.com/gatneil/scripts/master/hello.sh"], "commandToExecute": "sh hello.sh"}' ``` ## Resources
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>D-Bus: dbus-server.c Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">D-Bus &#160;<span id="projectnumber">1.6.8</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">dbus-server.c</div> </div> </div><!--header--> <div class="contents"> <div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/* -*- mode: C; c-file-style: &quot;gnu&quot;; indent-tabs-mode: nil; -*- */</span> <a name="l00002"></a>00002 <span class="comment">/* dbus-server.c DBusServer object</span> <a name="l00003"></a>00003 <span class="comment"> *</span> <a name="l00004"></a>00004 <span class="comment"> * Copyright (C) 2002, 2003, 2004, 2005 Red Hat After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>D-Bus: dbus-server.c Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">D-Bus &#160;<span id="projectnumber">1.6.8</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">dbus-server.c</div> </div> </div><!--header--> <div class="contents"> <div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/* -*- mode: C; c-file-style: &quot;gnu&quot;; indent-tabs-mode: nil; -*- */</span> <a name="l00002"></a>00002 <span class="comment">/* dbus-server.c DBusServer object</span> <a name="l00003"></a>00003 <span class="comment"> *</span> <a name="l00004"></a>00004 <span class="comment"> * Copyright (C) 2002, 2003, 2004, 2005 Red Hat Inc.</span> <a name="l00005"></a>00005 <span class="comment"> *</span> <a name="l00006"></a>00006 <span class="comment"> * Licensed under the Academic Free License version 2.1</span> <a name="l00007"></a>00007 <span class="comment"> * </span> <a name="l00008"></a>00008 <span class="comment"> * This program is free software; you can redistribute it and/or modify</span> <a name="l00009"></a>00009 <span class="comment"> * it under the terms of the GNU General Public License as published by</span> <a name="l00010"></a>00010 <span class="comment"> * the Free Software Foundation; either version 2 of the License, or</span> <a name="l00011"></a>00011 <span class="comment"> * (at your option) any later version.</span> <a name="l00012"></a>00012 <span class="comment"> *</span> <a name="l00013"></a>00013 <span class="comment"> * This program is distributed in the hope that it will be useful,</span> <a name="l00014"></a>00014 <span class="comment"> * but WITHOUT ANY WARRANTY; without even the implied warranty of</span> <a name="l00015"></a>00015 <span class="comment"> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span> <a name="l00016"></a>00016 <span class="comment"> * GNU General Public License for more details.</span> <a name="l00017"></a>00017 <span class="comment"> * </span> <a name="l00018"></a>00018 <span class="comment"> * You should have received a copy of the GNU General Public License</span> <a name="l00019"></a>00019 <span class="comment"> * along with this program; if not, write to the Free Software</span> <a name="l00020"></a>00020 <span class="comment"> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA</span> <a name="l00021"></a>00021 <span class="comment"> *</span> <a name="l00022"></a>00022 <span class="comment"> */</span> <a name="l00023"></a>00023 <a name="l00024"></a>00024 <span class="preprocessor">#include &lt;config.h&gt;</span> <a name="l00025"></a>00025 <span class="preprocessor">#include &quot;dbus-server.h&quot;</span> <a name="l00026"></a>00026 <span class="preprocessor">#include &quot;dbus-server-unix.h&quot;</span> <a name="l00027"></a>00027 <span class="preprocessor">#include &quot;dbus-server-socket.h&quot;</span> <a name="l00028"></a>00028 <span class="preprocessor">#include &quot;dbus-string.h&quot;</span> <a name="l00029"></a>00029 <span class="preprocessor">#ifdef DBUS_BUILD_TESTS</span> <a name="l00030"></a>00030 <span class="preprocessor"></span><span class="preprocessor">#include &quot;dbus-server-debug-pipe.h&quot;</span> <a name="l00031"></a>00031 <span class="preprocessor">#endif</span> <a name="l00032"></a>00032 <span class="preprocessor"></span><span class="preprocessor">#include &quot;dbus-address.h&quot;</span> <a name="l00033"></a>00033 <span class="preprocessor">#include &quot;dbus-protocol.h&quot;</span> <a name="l00034"></a>00034 <a name="l00056"></a>00056 <span class="preprocessor">#ifndef _dbus_server_trace_ref</span> <a name="l00057"></a>00057 <span class="preprocessor"></span><span class="keywordtype">void</span> <a name="l00058"></a>00058 _dbus_server_trace_ref (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00059"></a>00059 <span class="keywordtype">int</span> old_refcount, <a name="l00060"></a>00060 <span class="keywordtype">int</span> new_refcount, <a name="l00061"></a>00061 <span class="keyword">const</span> <span class="keywordtype">char</span> *why) <a name="l00062"></a>00062 { <a name="l00063"></a>00063 <span class="keyword">static</span> <span class="keywordtype">int</span> enabled = -1; <a name="l00064"></a>00064 <a name="l00065"></a>00065 _dbus_trace_ref (<span class="stringliteral">&quot;DBusServer&quot;</span>, server, old_refcount, new_refcount, why, <a name="l00066"></a>00066 <span class="stringliteral">&quot;DBUS_SERVER_TRACE&quot;</span>, &amp;enabled); <a name="l00067"></a>00067 } <a name="l00068"></a>00068 <span class="preprocessor">#endif</span> <a name="l00069"></a>00069 <span class="preprocessor"></span> <a name="l00070"></a>00070 <span class="comment">/* this is a little fragile since it assumes the address doesn&#39;t</span> <a name="l00071"></a>00071 <span class="comment"> * already have a guid, but it shouldn&#39;t</span> <a name="l00072"></a>00072 <span class="comment"> */</span> <a name="l00073"></a>00073 <span class="keyword">static</span> <span class="keywordtype">char</span>* <a name="l00074"></a>00074 copy_address_with_guid_appended (<span class="keyword">const</span> <a class="code" href="structDBusString.html">DBusString</a> *address, <a name="l00075"></a>00075 <span class="keyword">const</span> <a class="code" href="structDBusString.html">DBusString</a> *guid_hex) <a name="l00076"></a>00076 { <a name="l00077"></a>00077 <a class="code" href="structDBusString.html">DBusString</a> with_guid; <a name="l00078"></a>00078 <span class="keywordtype">char</span> *retval; <a name="l00079"></a>00079 <a name="l00080"></a>00080 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusString.html#ga348252317f7bb8ac43529972945830ae" title="Initializes a string.">_dbus_string_init</a> (&amp;with_guid)) <a name="l00081"></a>00081 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00082"></a>00082 <a name="l00083"></a>00083 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusString.html#ga3c10f0d1bcaa3b450025b9c6a8b901d7" title="Like _dbus_string_move(), but does not delete the section of the source string that&#39;s copied to the d...">_dbus_string_copy</a> (address, 0, &amp;with_guid, <a name="l00084"></a>00084 _dbus_string_get_length (&amp;with_guid)) || <a name="l00085"></a>00085 !<a class="code" href="group__DBusString.html#ga100c5ce0696822c5a4cfbdfaba674d96" title="Appends a nul-terminated C-style string to a DBusString.">_dbus_string_append</a> (&amp;with_guid, <span class="stringliteral">&quot;,guid=&quot;</span>) || <a name="l00086"></a>00086 !<a class="code" href="group__DBusString.html#ga3c10f0d1bcaa3b450025b9c6a8b901d7" title="Like _dbus_string_move(), but does not delete the section of the source string that&#39;s copied to the d...">_dbus_string_copy</a> (guid_hex, 0, <a name="l00087"></a>00087 &amp;with_guid, _dbus_string_get_length (&amp;with_guid))) <a name="l00088"></a>00088 { <a name="l00089"></a>00089 <a class="code" href="group__DBusString.html#ga781ca91acda49a834dce7d0ed0eef212" title="Frees a string created by _dbus_string_init().">_dbus_string_free</a> (&amp;with_guid); <a name="l00090"></a>00090 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00091"></a>00091 } <a name="l00092"></a>00092 <a name="l00093"></a>00093 retval = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00094"></a>00094 <a class="code" href="group__DBusString.html#ga556cc30c3ab032dbc63e217119f0d1f5" title="Like _dbus_string_get_data(), but removes the gotten data from the original string.">_dbus_string_steal_data</a> (&amp;with_guid, &amp;retval); <a name="l00095"></a>00095 <a name="l00096"></a>00096 <a class="code" href="group__DBusString.html#ga781ca91acda49a834dce7d0ed0eef212" title="Frees a string created by _dbus_string_init().">_dbus_string_free</a> (&amp;with_guid); <a name="l00097"></a>00097 <a name="l00098"></a>00098 <span class="keywordflow">return</span> retval; <span class="comment">/* may be NULL if steal_data failed */</span> <a name="l00099"></a>00099 } <a name="l00100"></a>00100 <a name="l00110"></a>00110 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00111"></a><a class="code" href="group__DBusServerInternals.html#gaacfb3d29553f205b362c850cfda02fd9">00111</a> <a class="code" href="group__DBusServerInternals.html#gaacfb3d29553f205b362c850cfda02fd9" title="Initializes the members of the DBusServer base class.">_dbus_server_init_base</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00112"></a>00112 <span class="keyword">const</span> <a class="code" href="structDBusServerVTable.html" title="Virtual table to be implemented by all server &quot;subclasses&quot;.">DBusServerVTable</a> *vtable, <a name="l00113"></a>00113 <span class="keyword">const</span> <a class="code" href="structDBusString.html">DBusString</a> *address) <a name="l00114"></a>00114 { <a name="l00115"></a>00115 server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a> = vtable; <a name="l00116"></a>00116 <a name="l00117"></a>00117 <span class="preprocessor">#ifdef DBUS_DISABLE_ASSERT</span> <a name="l00118"></a>00118 <span class="preprocessor"></span> <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00119"></a>00119 <span class="preprocessor">#else</span> <a name="l00120"></a>00120 <span class="preprocessor"></span> { <a name="l00121"></a>00121 dbus_int32_t old_refcount = <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00122"></a>00122 <a name="l00123"></a>00123 _dbus_assert (old_refcount == 0); <a name="l00124"></a>00124 } <a name="l00125"></a>00125 <span class="preprocessor">#endif</span> <a name="l00126"></a>00126 <span class="preprocessor"></span> <a name="l00127"></a>00127 server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00128"></a>00128 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00129"></a>00129 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00130"></a>00130 server-&gt;<a class="code" href="structDBusServer.html#a01a6dbb2573ce35f639873cd4dd85b4d" title="flag which indicates that server has published its bus address.">published_address</a> = <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00131"></a>00131 <a name="l00132"></a>00132 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusString.html#ga348252317f7bb8ac43529972945830ae" title="Initializes a string.">_dbus_string_init</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>)) <a name="l00133"></a>00133 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00134"></a>00134 <a name="l00135"></a>00135 <a class="code" href="group__DBusInternalsUtils.html#ga08c2922335845e5c857e88399436b9ba" title="Generates a new UUID.">_dbus_generate_uuid</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a799a94be0e3078f2e636f322f57d66f9" title="Globally unique ID of server.">guid</a>); <a name="l00136"></a>00136 <a name="l00137"></a>00137 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusInternalsUtils.html#gaf08364813376bd2d8f455d435d85323e" title="Hex-encode a UUID.">_dbus_uuid_encode</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a799a94be0e3078f2e636f322f57d66f9" title="Globally unique ID of server.">guid</a>, &amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>)) <a name="l00138"></a>00138 <span class="keywordflow">goto</span> failed; <a name="l00139"></a>00139 <a name="l00140"></a>00140 server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a> = copy_address_with_guid_appended (address, <a name="l00141"></a>00141 &amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>); <a name="l00142"></a>00142 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a> == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00143"></a>00143 <span class="keywordflow">goto</span> failed; <a name="l00144"></a>00144 <a name="l00145"></a>00145 <a class="code" href="group__DBusThreadsInternals.html#ga191deedb97c76fae82bdbc8e1559a849" title="Creates a new mutex or creates a no-op mutex if threads are not initialized.">_dbus_rmutex_new_at_location</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a89c4751e61ed16591254b00cb9db1661" title="Lock on the server object.">mutex</a>); <a name="l00146"></a>00146 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#a89c4751e61ed16591254b00cb9db1661" title="Lock on the server object.">mutex</a> == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00147"></a>00147 <span class="keywordflow">goto</span> failed; <a name="l00148"></a>00148 <a name="l00149"></a>00149 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = <a class="code" href="group__DBusWatchInternals.html#ga5d9db5d0af5916a5ec890eb38d5741eb" title="Creates a new watch list.">_dbus_watch_list_new</a> (); <a name="l00150"></a>00150 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00151"></a>00151 <span class="keywordflow">goto</span> failed; <a name="l00152"></a>00152 <a name="l00153"></a>00153 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = <a class="code" href="group__DBusTimeoutInternals.html#ga5b122b35cdb3926b7dc2d084ddff9d62" title="Creates a new timeout list.">_dbus_timeout_list_new</a> (); <a name="l00154"></a>00154 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00155"></a>00155 <span class="keywordflow">goto</span> failed; <a name="l00156"></a>00156 <a name="l00157"></a>00157 <a class="code" href="group__DBusDataSlot.html#ga6de49b3a1210202215d40a5a19806992" title="Initializes a slot list.">_dbus_data_slot_list_init</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a0601cca8307ba17d4a8bcebe48b08362" title="Data stored by allocated integer ID.">slot_list</a>); <a name="l00158"></a>00158 <a name="l00159"></a>00159 _dbus_verbose (<span class="stringliteral">&quot;Initialized server on address %s\n&quot;</span>, server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a>); <a name="l00160"></a>00160 <a name="l00161"></a>00161 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00162"></a>00162 <a name="l00163"></a>00163 failed: <a name="l00164"></a>00164 <a class="code" href="group__DBusThreadsInternals.html#gae1c95a3f47bcc78d32fc0a5a8ed37c91" title="Frees a DBusRMutex or removes it from the uninitialized mutex list; does nothing if passed a NULL poi...">_dbus_rmutex_free_at_location</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a89c4751e61ed16591254b00cb9db1661" title="Lock on the server object.">mutex</a>); <a name="l00165"></a>00165 server-&gt;<a class="code" href="structDBusServer.html#a89c4751e61ed16591254b00cb9db1661" title="Lock on the server object.">mutex</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00166"></a>00166 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a>) <a name="l00167"></a>00167 { <a name="l00168"></a>00168 <a class="code" href="group__DBusWatchInternals.html#gac3f75c0da2c8c51e8708f45dd27f9e2d" title="Frees a DBusWatchList.">_dbus_watch_list_free</a> (server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a>); <a name="l00169"></a>00169 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00170"></a>00170 } <a name="l00171"></a>00171 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a>) <a name="l00172"></a>00172 { <a name="l00173"></a>00173 <a class="code" href="group__DBusTimeoutInternals.html#ga1b399ef2d7f128e59bb32dbb5b590e1b" title="Frees a DBusTimeoutList.">_dbus_timeout_list_free</a> (server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a>); <a name="l00174"></a>00174 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00175"></a>00175 } <a name="l00176"></a>00176 <span class="keywordflow">if</span> (server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a>) <a name="l00177"></a>00177 { <a name="l00178"></a>00178 <a class="code" href="group__DBusMemory.html#ga34e666b19b015035a9a31e53da84b39a" title="Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().">dbus_free</a> (server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a>); <a name="l00179"></a>00179 server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00180"></a>00180 } <a name="l00181"></a>00181 <a class="code" href="group__DBusString.html#ga781ca91acda49a834dce7d0ed0eef212" title="Frees a string created by _dbus_string_init().">_dbus_string_free</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>); <a name="l00182"></a>00182 <a name="l00183"></a>00183 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00184"></a>00184 } <a name="l00185"></a>00185 <a name="l00192"></a>00192 <span class="keywordtype">void</span> <a name="l00193"></a><a class="code" href="group__DBusServerInternals.html#ga93b5bca90e69122d5acbbeef2b4ca03e">00193</a> <a class="code" href="group__DBusServerInternals.html#ga93b5bca90e69122d5acbbeef2b4ca03e" title="Finalizes the members of the DBusServer base class.">_dbus_server_finalize_base</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00194"></a>00194 { <a name="l00195"></a>00195 <span class="comment">/* We don&#39;t have the lock, but nobody should be accessing</span> <a name="l00196"></a>00196 <span class="comment"> * concurrently since they don&#39;t have a ref</span> <a name="l00197"></a>00197 <span class="comment"> */</span> <a name="l00198"></a>00198 <span class="preprocessor">#ifndef DBUS_DISABLE_CHECKS</span> <a name="l00199"></a>00199 <span class="preprocessor"></span> _dbus_assert (!server-&gt;<a class="code" href="structDBusServer.html#adba8dd016471a800525a42926f9ee061" title="Does someone have the server mutex locked.">have_server_lock</a>); <a name="l00200"></a>00200 <span class="preprocessor">#endif</span> <a name="l00201"></a>00201 <span class="preprocessor"></span> _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a>); <a name="l00202"></a>00202 <a name="l00203"></a>00203 <span class="comment">/* calls out to application code... */</span> <a name="l00204"></a>00204 <a class="code" href="group__DBusDataSlot.html#gabc399733376c462c3010271a2d431e73" title="Frees the data slot list and all data slots contained in it, calling application-provided free functi...">_dbus_data_slot_list_free</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a0601cca8307ba17d4a8bcebe48b08362" title="Data stored by allocated integer ID.">slot_list</a>); <a name="l00205"></a>00205 <a name="l00206"></a>00206 <a class="code" href="group__DBusServer.html#gaa14d9109e04adccffd9a40460c28c53b" title="Sets a function to be used for handling new connections.">dbus_server_set_new_connection_function</a> (server, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00207"></a>00207 <a name="l00208"></a>00208 <a class="code" href="group__DBusWatchInternals.html#gac3f75c0da2c8c51e8708f45dd27f9e2d" title="Frees a DBusWatchList.">_dbus_watch_list_free</a> (server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a>); <a name="l00209"></a>00209 <a class="code" href="group__DBusTimeoutInternals.html#ga1b399ef2d7f128e59bb32dbb5b590e1b" title="Frees a DBusTimeoutList.">_dbus_timeout_list_free</a> (server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a>); <a name="l00210"></a>00210 <a name="l00211"></a>00211 <a class="code" href="group__DBusThreadsInternals.html#gae1c95a3f47bcc78d32fc0a5a8ed37c91" title="Frees a DBusRMutex or removes it from the uninitialized mutex list; does nothing if passed a NULL poi...">_dbus_rmutex_free_at_location</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a89c4751e61ed16591254b00cb9db1661" title="Lock on the server object.">mutex</a>); <a name="l00212"></a>00212 <a name="l00213"></a>00213 <a class="code" href="group__DBusMemory.html#ga34e666b19b015035a9a31e53da84b39a" title="Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().">dbus_free</a> (server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a>); <a name="l00214"></a>00214 <a name="l00215"></a>00215 <a class="code" href="group__DBusMemory.html#gac200b2dbc8b3f6ecac4d42426fb97b40" title="Frees a NULL-terminated array of strings.">dbus_free_string_array</a> (server-&gt;<a class="code" href="structDBusServer.html#adc1032bbed41413e5d0e01578f2bfffc" title="Array of allowed authentication mechanisms.">auth_mechanisms</a>); <a name="l00216"></a>00216 <a name="l00217"></a>00217 <a class="code" href="group__DBusString.html#ga781ca91acda49a834dce7d0ed0eef212" title="Frees a string created by _dbus_string_init().">_dbus_string_free</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>); <a name="l00218"></a>00218 } <a name="l00219"></a>00219 <a name="l00220"></a>00220 <a name="l00222"></a><a class="code" href="group__DBusServerInternals.html#gab3c673c1e36e293c5f2baa92418603a3">00222</a> <span class="keyword">typedef</span> <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> (* <a class="code" href="group__DBusConnectionInternals.html#gab3c673c1e36e293c5f2baa92418603a3" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchAddFunction</a>) (<a class="code" href="structDBusWatchList.html" title="DBusWatchList implementation details.">DBusWatchList</a> *list, <a name="l00223"></a>00223 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch); <a name="l00225"></a><a class="code" href="group__DBusServerInternals.html#ga475a0e9a2f2b7a279ba07fa3352114d4">00225</a> <span class="keyword">typedef</span> void (* <a class="code" href="group__DBusConnectionInternals.html#ga475a0e9a2f2b7a279ba07fa3352114d4" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchRemoveFunction</a>) (<a class="code" href="structDBusWatchList.html" title="DBusWatchList implementation details.">DBusWatchList</a> *list, <a name="l00226"></a>00226 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch); <a name="l00228"></a><a class="code" href="group__DBusServerInternals.html#ga851f0958d46980f5a39bcfb874a4cb78">00228</a> <span class="keyword">typedef</span> void (* <a class="code" href="group__DBusConnectionInternals.html#ga851f0958d46980f5a39bcfb874a4cb78" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchToggleFunction</a>) (<a class="code" href="structDBusWatchList.html" title="DBusWatchList implementation details.">DBusWatchList</a> *list, <a name="l00229"></a>00229 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch, <a name="l00230"></a>00230 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled); <a name="l00231"></a>00231 <a name="l00232"></a>00232 <span class="keyword">static</span> <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00233"></a>00233 protected_change_watch (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00234"></a>00234 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch, <a name="l00235"></a>00235 <a class="code" href="group__DBusConnectionInternals.html#gab3c673c1e36e293c5f2baa92418603a3" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchAddFunction</a> add_function, <a name="l00236"></a>00236 <a class="code" href="group__DBusConnectionInternals.html#ga475a0e9a2f2b7a279ba07fa3352114d4" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchRemoveFunction</a> remove_function, <a name="l00237"></a>00237 <a class="code" href="group__DBusConnectionInternals.html#ga851f0958d46980f5a39bcfb874a4cb78" title="Function to be called in protected_change_watch() with refcount held.">DBusWatchToggleFunction</a> toggle_function, <a name="l00238"></a>00238 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled) <a name="l00239"></a>00239 { <a name="l00240"></a>00240 <a class="code" href="structDBusWatchList.html" title="DBusWatchList implementation details.">DBusWatchList</a> *watches; <a name="l00241"></a>00241 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> retval; <a name="l00242"></a>00242 <a name="l00243"></a>00243 HAVE_LOCK_CHECK (server); <a name="l00244"></a>00244 <a name="l00245"></a>00245 <span class="comment">/* This isn&#39;t really safe or reasonable; a better pattern is the &quot;do</span> <a name="l00246"></a>00246 <span class="comment"> * everything, then drop lock and call out&quot; one; but it has to be</span> <a name="l00247"></a>00247 <span class="comment"> * propagated up through all callers</span> <a name="l00248"></a>00248 <span class="comment"> */</span> <a name="l00249"></a>00249 <a name="l00250"></a>00250 watches = server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a>; <a name="l00251"></a>00251 <span class="keywordflow">if</span> (watches) <a name="l00252"></a>00252 { <a name="l00253"></a>00253 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00254"></a>00254 <a class="code" href="group__DBusServerInternals.html#ga987e9bf42ab4e4cededa8e8f65c54e2e" title="Like dbus_server_ref() but does not acquire the lock (must already be held)">_dbus_server_ref_unlocked</a> (server); <a name="l00255"></a>00255 SERVER_UNLOCK (server); <a name="l00256"></a>00256 <a name="l00257"></a>00257 <span class="keywordflow">if</span> (add_function) <a name="l00258"></a>00258 retval = (* add_function) (watches, watch); <a name="l00259"></a>00259 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (remove_function) <a name="l00260"></a>00260 { <a name="l00261"></a>00261 retval = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00262"></a>00262 (* remove_function) (watches, watch); <a name="l00263"></a>00263 } <a name="l00264"></a>00264 <span class="keywordflow">else</span> <a name="l00265"></a>00265 { <a name="l00266"></a>00266 retval = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00267"></a>00267 (* toggle_function) (watches, watch, enabled); <a name="l00268"></a>00268 } <a name="l00269"></a>00269 <a name="l00270"></a>00270 SERVER_LOCK (server); <a name="l00271"></a>00271 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = watches; <a name="l00272"></a>00272 <a class="code" href="group__DBusServerInternals.html#ga6e1d0b379c98b0d59ebd19dc9b8a2dbe" title="Like dbus_server_unref() but does not acquire the lock (must already be held)">_dbus_server_unref_unlocked</a> (server); <a name="l00273"></a>00273 <a name="l00274"></a>00274 <span class="keywordflow">return</span> retval; <a name="l00275"></a>00275 } <a name="l00276"></a>00276 <span class="keywordflow">else</span> <a name="l00277"></a>00277 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00278"></a>00278 } <a name="l00279"></a>00279 <a name="l00287"></a>00287 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00288"></a><a class="code" href="group__DBusServerInternals.html#ga0866e5b205b8a570c77c8ad787b665fd">00288</a> <a class="code" href="group__DBusServerInternals.html#ga0866e5b205b8a570c77c8ad787b665fd" title="Adds a watch for this server, chaining out to application-provided watch handlers.">_dbus_server_add_watch</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00289"></a>00289 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch) <a name="l00290"></a>00290 { <a name="l00291"></a>00291 HAVE_LOCK_CHECK (server); <a name="l00292"></a>00292 <span class="keywordflow">return</span> protected_change_watch (server, watch, <a name="l00293"></a>00293 <a class="code" href="group__DBusWatchInternals.html#gaec61655a4bd6186a6a1ec104771d8af5" title="Adds a new watch to the watch list, invoking the application DBusAddWatchFunction if appropriate...">_dbus_watch_list_add_watch</a>, <a name="l00294"></a>00294 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00295"></a>00295 } <a name="l00296"></a>00296 <a name="l00303"></a>00303 <span class="keywordtype">void</span> <a name="l00304"></a><a class="code" href="group__DBusServerInternals.html#ga61cfdbfcc9316d4bae55f83b069f248c">00304</a> <a class="code" href="group__DBusServerInternals.html#ga61cfdbfcc9316d4bae55f83b069f248c" title="Removes a watch previously added with _dbus_server_remove_watch().">_dbus_server_remove_watch</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00305"></a>00305 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch) <a name="l00306"></a>00306 { <a name="l00307"></a>00307 HAVE_LOCK_CHECK (server); <a name="l00308"></a>00308 protected_change_watch (server, watch, <a name="l00309"></a>00309 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a name="l00310"></a>00310 <a class="code" href="group__DBusWatchInternals.html#ga76894d297bc7d7d23cbacdc2b1778884" title="Removes a watch from the watch list, invoking the application&#39;s DBusRemoveWatchFunction if appropriat...">_dbus_watch_list_remove_watch</a>, <a name="l00311"></a>00311 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00312"></a>00312 } <a name="l00313"></a>00313 <a name="l00323"></a>00323 <span class="keywordtype">void</span> <a name="l00324"></a><a class="code" href="group__DBusServerInternals.html#ga7bef63b643f53ec984f5da35653689e7">00324</a> <a class="code" href="group__DBusServerInternals.html#ga7bef63b643f53ec984f5da35653689e7" title="Toggles a watch and notifies app via server&#39;s DBusWatchToggledFunction if available.">_dbus_server_toggle_watch</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00325"></a>00325 <a class="code" href="structDBusWatch.html" title="Implementation of DBusWatch.">DBusWatch</a> *watch, <a name="l00326"></a>00326 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled) <a name="l00327"></a>00327 { <a name="l00328"></a>00328 _dbus_assert (watch != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00329"></a>00329 <a name="l00330"></a>00330 HAVE_LOCK_CHECK (server); <a name="l00331"></a>00331 protected_change_watch (server, watch, <a name="l00332"></a>00332 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a name="l00333"></a>00333 <a class="code" href="group__DBusWatchInternals.html#ga14bb50e8663a1d9d3960b4f73c09c097" title="Sets a watch to the given enabled state, invoking the application&#39;s DBusWatchToggledFunction if appro...">_dbus_watch_list_toggle_watch</a>, <a name="l00334"></a>00334 enabled); <a name="l00335"></a>00335 } <a name="l00336"></a>00336 <a name="l00338"></a><a class="code" href="group__DBusServerInternals.html#ga6ca28a0af7de84c51fdbafe8786d3446">00338</a> <span class="keyword">typedef</span> <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> (* <a class="code" href="group__DBusConnectionInternals.html#ga6ca28a0af7de84c51fdbafe8786d3446" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutAddFunction</a>) (<a class="code" href="structDBusTimeoutList.html" title="DBusTimeoutList implementation details.">DBusTimeoutList</a> *list, <a name="l00339"></a>00339 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout); <a name="l00341"></a><a class="code" href="group__DBusServerInternals.html#gafe75d05f2abf712c7fe13691ef27754c">00341</a> <span class="keyword">typedef</span> void (* <a class="code" href="group__DBusConnectionInternals.html#gafe75d05f2abf712c7fe13691ef27754c" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutRemoveFunction</a>) (<a class="code" href="structDBusTimeoutList.html" title="DBusTimeoutList implementation details.">DBusTimeoutList</a> *list, <a name="l00342"></a>00342 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout); <a name="l00344"></a><a class="code" href="group__DBusServerInternals.html#ga1b4c97e7ef6f2cb8704cf74acc03c727">00344</a> <span class="keyword">typedef</span> void (* <a class="code" href="group__DBusConnectionInternals.html#ga1b4c97e7ef6f2cb8704cf74acc03c727" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutToggleFunction</a>) (<a class="code" href="structDBusTimeoutList.html" title="DBusTimeoutList implementation details.">DBusTimeoutList</a> *list, <a name="l00345"></a>00345 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout, <a name="l00346"></a>00346 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled); <a name="l00347"></a>00347 <a name="l00348"></a>00348 <a name="l00349"></a>00349 <span class="keyword">static</span> <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00350"></a>00350 protected_change_timeout (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00351"></a>00351 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout, <a name="l00352"></a>00352 <a class="code" href="group__DBusConnectionInternals.html#ga6ca28a0af7de84c51fdbafe8786d3446" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutAddFunction</a> add_function, <a name="l00353"></a>00353 <a class="code" href="group__DBusConnectionInternals.html#gafe75d05f2abf712c7fe13691ef27754c" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutRemoveFunction</a> remove_function, <a name="l00354"></a>00354 <a class="code" href="group__DBusConnectionInternals.html#ga1b4c97e7ef6f2cb8704cf74acc03c727" title="Function to be called in protected_change_timeout() with refcount held.">DBusTimeoutToggleFunction</a> toggle_function, <a name="l00355"></a>00355 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled) <a name="l00356"></a>00356 { <a name="l00357"></a>00357 <a class="code" href="structDBusTimeoutList.html" title="DBusTimeoutList implementation details.">DBusTimeoutList</a> *timeouts; <a name="l00358"></a>00358 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> retval; <a name="l00359"></a>00359 <a name="l00360"></a>00360 HAVE_LOCK_CHECK (server); <a name="l00361"></a>00361 <a name="l00362"></a>00362 <span class="comment">/* This isn&#39;t really safe or reasonable; a better pattern is the &quot;do everything, then</span> <a name="l00363"></a>00363 <span class="comment"> * drop lock and call out&quot; one; but it has to be propagated up through all callers</span> <a name="l00364"></a>00364 <span class="comment"> */</span> <a name="l00365"></a>00365 <a name="l00366"></a>00366 timeouts = server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a>; <a name="l00367"></a>00367 <span class="keywordflow">if</span> (timeouts) <a name="l00368"></a>00368 { <a name="l00369"></a>00369 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00370"></a>00370 <a class="code" href="group__DBusServerInternals.html#ga987e9bf42ab4e4cededa8e8f65c54e2e" title="Like dbus_server_ref() but does not acquire the lock (must already be held)">_dbus_server_ref_unlocked</a> (server); <a name="l00371"></a>00371 SERVER_UNLOCK (server); <a name="l00372"></a>00372 <a name="l00373"></a>00373 <span class="keywordflow">if</span> (add_function) <a name="l00374"></a>00374 retval = (* add_function) (timeouts, timeout); <a name="l00375"></a>00375 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (remove_function) <a name="l00376"></a>00376 { <a name="l00377"></a>00377 retval = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00378"></a>00378 (* remove_function) (timeouts, timeout); <a name="l00379"></a>00379 } <a name="l00380"></a>00380 <span class="keywordflow">else</span> <a name="l00381"></a>00381 { <a name="l00382"></a>00382 retval = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00383"></a>00383 (* toggle_function) (timeouts, timeout, enabled); <a name="l00384"></a>00384 } <a name="l00385"></a>00385 <a name="l00386"></a>00386 SERVER_LOCK (server); <a name="l00387"></a>00387 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = timeouts; <a name="l00388"></a>00388 <a class="code" href="group__DBusServerInternals.html#ga6e1d0b379c98b0d59ebd19dc9b8a2dbe" title="Like dbus_server_unref() but does not acquire the lock (must already be held)">_dbus_server_unref_unlocked</a> (server); <a name="l00389"></a>00389 <a name="l00390"></a>00390 <span class="keywordflow">return</span> retval; <a name="l00391"></a>00391 } <a name="l00392"></a>00392 <span class="keywordflow">else</span> <a name="l00393"></a>00393 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00394"></a>00394 } <a name="l00395"></a>00395 <a name="l00405"></a>00405 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00406"></a><a class="code" href="group__DBusServerInternals.html#ga7e10a662386fb7f693e0d168161e395b">00406</a> <a class="code" href="group__DBusServerInternals.html#ga7e10a662386fb7f693e0d168161e395b" title="Adds a timeout for this server, chaining out to application-provided timeout handlers.">_dbus_server_add_timeout</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00407"></a>00407 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout) <a name="l00408"></a>00408 { <a name="l00409"></a>00409 <span class="keywordflow">return</span> protected_change_timeout (server, timeout, <a name="l00410"></a>00410 <a class="code" href="group__DBusTimeoutInternals.html#ga14955f061551ece122808b9e6ddc0757" title="Adds a new timeout to the timeout list, invoking the application DBusAddTimeoutFunction if appropriat...">_dbus_timeout_list_add_timeout</a>, <a name="l00411"></a>00411 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00412"></a>00412 } <a name="l00413"></a>00413 <a name="l00420"></a>00420 <span class="keywordtype">void</span> <a name="l00421"></a><a class="code" href="group__DBusServerInternals.html#ga69509697f091e354442cedb63886c20e">00421</a> <a class="code" href="group__DBusServerInternals.html#ga69509697f091e354442cedb63886c20e" title="Removes a timeout previously added with _dbus_server_add_timeout().">_dbus_server_remove_timeout</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00422"></a>00422 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout) <a name="l00423"></a>00423 { <a name="l00424"></a>00424 protected_change_timeout (server, timeout, <a name="l00425"></a>00425 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a name="l00426"></a>00426 <a class="code" href="group__DBusTimeoutInternals.html#gaec0ffafdcac87f23878a2ddded044822" title="Removes a timeout from the timeout list, invoking the application&#39;s DBusRemoveTimeoutFunction if appr...">_dbus_timeout_list_remove_timeout</a>, <a name="l00427"></a>00427 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00428"></a>00428 } <a name="l00429"></a>00429 <a name="l00439"></a>00439 <span class="keywordtype">void</span> <a name="l00440"></a><a class="code" href="group__DBusServerInternals.html#ga74d2714ce80a089d2607a6fc5763d819">00440</a> <a class="code" href="group__DBusServerInternals.html#ga74d2714ce80a089d2607a6fc5763d819" title="Toggles a timeout and notifies app via server&#39;s DBusTimeoutToggledFunction if available.">_dbus_server_toggle_timeout</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00441"></a>00441 <a class="code" href="structDBusTimeout.html" title="Internals of DBusTimeout.">DBusTimeout</a> *timeout, <a name="l00442"></a>00442 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> enabled) <a name="l00443"></a>00443 { <a name="l00444"></a>00444 protected_change_timeout (server, timeout, <a name="l00445"></a>00445 <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a name="l00446"></a>00446 <a class="code" href="group__DBusTimeoutInternals.html#ga3d1ee0968a47651c5428ebf48711b217" title="Sets a timeout to the given enabled state, invoking the application&#39;s DBusTimeoutToggledFunction if a...">_dbus_timeout_list_toggle_timeout</a>, <a name="l00447"></a>00447 enabled); <a name="l00448"></a>00448 } <a name="l00449"></a>00449 <a name="l00450"></a>00450 <a name="l00456"></a>00456 <span class="keywordtype">void</span> <a name="l00457"></a><a class="code" href="group__DBusServerInternals.html#ga987e9bf42ab4e4cededa8e8f65c54e2e">00457</a> <a class="code" href="group__DBusServerInternals.html#ga987e9bf42ab4e4cededa8e8f65c54e2e" title="Like dbus_server_ref() but does not acquire the lock (must already be held)">_dbus_server_ref_unlocked</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00458"></a>00458 { <a name="l00459"></a>00459 dbus_int32_t old_refcount; <a name="l00460"></a>00460 <a name="l00461"></a>00461 _dbus_assert (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00462"></a>00462 HAVE_LOCK_CHECK (server); <a name="l00463"></a>00463 <a name="l00464"></a>00464 old_refcount = <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00465"></a>00465 _dbus_assert (old_refcount &gt; 0); <a name="l00466"></a>00466 _dbus_server_trace_ref (server, old_refcount, old_refcount + 1, <a name="l00467"></a>00467 <span class="stringliteral">&quot;ref_unlocked&quot;</span>); <a name="l00468"></a>00468 } <a name="l00469"></a>00469 <a name="l00475"></a>00475 <span class="keywordtype">void</span> <a name="l00476"></a><a class="code" href="group__DBusServerInternals.html#ga6e1d0b379c98b0d59ebd19dc9b8a2dbe">00476</a> <a class="code" href="group__DBusServerInternals.html#ga6e1d0b379c98b0d59ebd19dc9b8a2dbe" title="Like dbus_server_unref() but does not acquire the lock (must already be held)">_dbus_server_unref_unlocked</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00477"></a>00477 { <a name="l00478"></a>00478 dbus_int32_t old_refcount; <a name="l00479"></a>00479 <a name="l00480"></a>00480 <span class="comment">/* Keep this in sync with dbus_server_unref */</span> <a name="l00481"></a>00481 <a name="l00482"></a>00482 _dbus_assert (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00483"></a>00483 <a name="l00484"></a>00484 HAVE_LOCK_CHECK (server); <a name="l00485"></a>00485 <a name="l00486"></a>00486 old_refcount = <a class="code" href="group__DBusSysdeps.html#ga3c50a069f795dceeb9172fe2b517bbdc" title="Atomically decrement an integer.">_dbus_atomic_dec</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00487"></a>00487 _dbus_assert (old_refcount &gt; 0); <a name="l00488"></a>00488 <a name="l00489"></a>00489 _dbus_server_trace_ref (server, old_refcount, old_refcount - 1, <a name="l00490"></a>00490 <span class="stringliteral">&quot;unref_unlocked&quot;</span>); <a name="l00491"></a>00491 <a name="l00492"></a>00492 <span class="keywordflow">if</span> (old_refcount == 1) <a name="l00493"></a>00493 { <a name="l00494"></a>00494 _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a>); <a name="l00495"></a>00495 <a name="l00496"></a>00496 SERVER_UNLOCK (server); <a name="l00497"></a>00497 <a name="l00498"></a>00498 _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#acd97315e812352da38449f910775b08d" title="The finalize method must free the server.">finalize</a> != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00499"></a>00499 <a name="l00500"></a>00500 (* server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#acd97315e812352da38449f910775b08d" title="The finalize method must free the server.">finalize</a>) (server); <a name="l00501"></a>00501 } <a name="l00502"></a>00502 } <a name="l00503"></a>00503 <a name="l00525"></a>00525 <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">struct </span>{ <a name="l00526"></a>00526 DBusServerListenResult (* func) (<a class="code" href="structDBusAddressEntry.html" title="Internals of DBusAddressEntry.">DBusAddressEntry</a> *entry, <a name="l00527"></a>00527 <a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> **server_p, <a name="l00528"></a>00528 <a class="code" href="structDBusError.html" title="Object representing an exception.">DBusError</a> *error); <a name="l00529"></a>00529 } listen_funcs[] = { <a name="l00530"></a>00530 { <a class="code" href="group__DBusServerSocket.html#ga90a89943c15760592e5ddce31bf0e021" title="Tries to interpret the address entry for various socket-related addresses (well, currently only tcp a...">_dbus_server_listen_socket</a> } <a name="l00531"></a>00531 , { <a class="code" href="group__DBusServerUnix.html#gaec00cdf4977b9bd33621df684406a779" title="Tries to interpret the address entry in a platform-specific way, creating a platform-specific server ...">_dbus_server_listen_platform_specific</a> } <a name="l00532"></a>00532 <span class="preprocessor">#ifdef DBUS_BUILD_TESTS</span> <a name="l00533"></a>00533 <span class="preprocessor"></span> , { _dbus_server_listen_debug_pipe } <a name="l00534"></a>00534 <span class="preprocessor">#endif</span> <a name="l00535"></a>00535 <span class="preprocessor"></span>}; <a name="l00536"></a>00536 <a name="l00557"></a>00557 <a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a>* <a name="l00558"></a><a class="code" href="group__DBusServer.html#ga4c83cf9f2c186afa97decdc25ac163d8">00558</a> <a class="code" href="group__DBusServer.html#ga4c83cf9f2c186afa97decdc25ac163d8" title="Listens for new connections on the given address.">dbus_server_listen</a> (<span class="keyword">const</span> <span class="keywordtype">char</span> *address, <a name="l00559"></a>00559 <a class="code" href="structDBusError.html" title="Object representing an exception.">DBusError</a> *error) <a name="l00560"></a>00560 { <a name="l00561"></a>00561 <a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server; <a name="l00562"></a>00562 <a class="code" href="structDBusAddressEntry.html" title="Internals of DBusAddressEntry.">DBusAddressEntry</a> **entries; <a name="l00563"></a>00563 <span class="keywordtype">int</span> len, i; <a name="l00564"></a>00564 <a class="code" href="structDBusError.html" title="Object representing an exception.">DBusError</a> first_connect_error = <a class="code" href="group__DBusErrorInternals.html#ga961cc70e3891282a65205c4c8418d88e" title="Expands to a suitable initializer for a DBusError on the stack.">DBUS_ERROR_INIT</a>; <a name="l00565"></a>00565 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> handled_once; <a name="l00566"></a>00566 <a name="l00567"></a>00567 _dbus_return_val_if_fail (address != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00568"></a>00568 _dbus_return_val_if_error_is_set (error, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00569"></a>00569 <a name="l00570"></a>00570 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusAddress.html#ga3cbf5947262b79601598276c720e2098" title="Parses an address string of the form:">dbus_parse_address</a> (address, &amp;entries, &amp;len, error)) <a name="l00571"></a>00571 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00572"></a>00572 <a name="l00573"></a>00573 server = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00574"></a>00574 handled_once = <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00575"></a>00575 <a name="l00576"></a>00576 <span class="keywordflow">for</span> (i = 0; i &lt; len; i++) <a name="l00577"></a>00577 { <a name="l00578"></a>00578 <span class="keywordtype">int</span> j; <a name="l00579"></a>00579 <a name="l00580"></a>00580 <span class="keywordflow">for</span> (j = 0; j &lt; (int) _DBUS_N_ELEMENTS (listen_funcs); ++j) <a name="l00581"></a>00581 { <a name="l00582"></a>00582 DBusServerListenResult result; <a name="l00583"></a>00583 <a class="code" href="structDBusError.html" title="Object representing an exception.">DBusError</a> tmp_error = <a class="code" href="group__DBusErrorInternals.html#ga961cc70e3891282a65205c4c8418d88e" title="Expands to a suitable initializer for a DBusError on the stack.">DBUS_ERROR_INIT</a>; <a name="l00584"></a>00584 <a name="l00585"></a>00585 result = (* listen_funcs[j].func) (entries[i], <a name="l00586"></a>00586 &amp;server, <a name="l00587"></a>00587 &amp;tmp_error); <a name="l00588"></a>00588 <a name="l00589"></a>00589 <span class="keywordflow">if</span> (result == DBUS_SERVER_LISTEN_OK) <a name="l00590"></a>00590 { <a name="l00591"></a>00591 _dbus_assert (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00592"></a>00592 _DBUS_ASSERT_ERROR_IS_CLEAR (&amp;tmp_error); <a name="l00593"></a>00593 handled_once = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00594"></a>00594 <span class="keywordflow">goto</span> out; <a name="l00595"></a>00595 } <a name="l00596"></a>00596 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (result == DBUS_SERVER_LISTEN_ADDRESS_ALREADY_USED) <a name="l00597"></a>00597 { <a name="l00598"></a>00598 _dbus_assert (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00599"></a>00599 <a class="code" href="group__DBusErrors.html#ga89d2ad4bde21f9e0057fac07a79885e3" title="Assigns an error name and message to a DBusError.">dbus_set_error</a> (error, <a name="l00600"></a>00600 <a class="code" href="group__DBusProtocol.html#ga3d13424a19bb774cf3481216bf4ba366" title="Can&#39;t bind a socket since its address is in use (i.e.">DBUS_ERROR_ADDRESS_IN_USE</a>, <a name="l00601"></a>00601 <span class="stringliteral">&quot;Address &#39;%s&#39; already used&quot;</span>, <a name="l00602"></a>00602 <a class="code" href="group__DBusAddress.html#ga7e6b2572d6e637826acada01377b5487" title="Returns the method string of an address entry.">dbus_address_entry_get_method</a> (entries[0])); <a name="l00603"></a>00603 handled_once = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00604"></a>00604 <span class="keywordflow">goto</span> out; <a name="l00605"></a>00605 } <a name="l00606"></a>00606 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (result == DBUS_SERVER_LISTEN_BAD_ADDRESS) <a name="l00607"></a>00607 { <a name="l00608"></a>00608 _dbus_assert (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00609"></a>00609 _DBUS_ASSERT_ERROR_IS_SET (&amp;tmp_error); <a name="l00610"></a>00610 <a class="code" href="group__DBusErrors.html#ga0a27fb9f1af0c2bfd105d7e8622b93f4" title="Moves an error src into dest, freeing src and overwriting dest.">dbus_move_error</a> (&amp;tmp_error, error); <a name="l00611"></a>00611 handled_once = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00612"></a>00612 <span class="keywordflow">goto</span> out; <a name="l00613"></a>00613 } <a name="l00614"></a>00614 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (result == DBUS_SERVER_LISTEN_NOT_HANDLED) <a name="l00615"></a>00615 { <a name="l00616"></a>00616 _dbus_assert (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00617"></a>00617 _DBUS_ASSERT_ERROR_IS_CLEAR (&amp;tmp_error); <a name="l00618"></a>00618 <a name="l00619"></a>00619 <span class="comment">/* keep trying addresses */</span> <a name="l00620"></a>00620 } <a name="l00621"></a>00621 <span class="keywordflow">else</span> <span class="keywordflow">if</span> (result == DBUS_SERVER_LISTEN_DID_NOT_CONNECT) <a name="l00622"></a>00622 { <a name="l00623"></a>00623 _dbus_assert (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00624"></a>00624 _DBUS_ASSERT_ERROR_IS_SET (&amp;tmp_error); <a name="l00625"></a>00625 <span class="keywordflow">if</span> (!<a class="code" href="group__DBusErrors.html#gab0ed62e9fc2685897eb2d41467c89405" title="Checks whether an error occurred (the error is set).">dbus_error_is_set</a> (&amp;first_connect_error)) <a name="l00626"></a>00626 <a class="code" href="group__DBusErrors.html#ga0a27fb9f1af0c2bfd105d7e8622b93f4" title="Moves an error src into dest, freeing src and overwriting dest.">dbus_move_error</a> (&amp;tmp_error, &amp;first_connect_error); <a name="l00627"></a>00627 <span class="keywordflow">else</span> <a name="l00628"></a>00628 <a class="code" href="group__DBusErrors.html#gaac6c14ead14829ee4e090f39de6a7568" title="Frees an error that&#39;s been set (or just initialized), then reinitializes the error as in dbus_error_i...">dbus_error_free</a> (&amp;tmp_error); <a name="l00629"></a>00629 <a name="l00630"></a>00630 handled_once = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00631"></a>00631 <a name="l00632"></a>00632 <span class="comment">/* keep trying addresses */</span> <a name="l00633"></a>00633 } <a name="l00634"></a>00634 } <a name="l00635"></a>00635 <a name="l00636"></a>00636 _dbus_assert (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00637"></a>00637 _DBUS_ASSERT_ERROR_IS_CLEAR (error); <a name="l00638"></a>00638 } <a name="l00639"></a>00639 <a name="l00640"></a>00640 out: <a name="l00641"></a>00641 <a name="l00642"></a>00642 <span class="keywordflow">if</span> (!handled_once) <a name="l00643"></a>00643 { <a name="l00644"></a>00644 _DBUS_ASSERT_ERROR_IS_CLEAR (error); <a name="l00645"></a>00645 <span class="keywordflow">if</span> (len &gt; 0) <a name="l00646"></a>00646 <a class="code" href="group__DBusErrors.html#ga89d2ad4bde21f9e0057fac07a79885e3" title="Assigns an error name and message to a DBusError.">dbus_set_error</a> (error, <a name="l00647"></a>00647 <a class="code" href="group__DBusProtocol.html#ga3fa04eb600edda4afc2dd9fe2e0f8b02" title="A D-Bus bus address was malformed.">DBUS_ERROR_BAD_ADDRESS</a>, <a name="l00648"></a>00648 <span class="stringliteral">&quot;Unknown address type &#39;%s&#39;&quot;</span>, <a name="l00649"></a>00649 <a class="code" href="group__DBusAddress.html#ga7e6b2572d6e637826acada01377b5487" title="Returns the method string of an address entry.">dbus_address_entry_get_method</a> (entries[0])); <a name="l00650"></a>00650 <span class="keywordflow">else</span> <a name="l00651"></a>00651 <a class="code" href="group__DBusErrors.html#ga89d2ad4bde21f9e0057fac07a79885e3" title="Assigns an error name and message to a DBusError.">dbus_set_error</a> (error, <a name="l00652"></a>00652 <a class="code" href="group__DBusProtocol.html#ga3fa04eb600edda4afc2dd9fe2e0f8b02" title="A D-Bus bus address was malformed.">DBUS_ERROR_BAD_ADDRESS</a>, <a name="l00653"></a>00653 <span class="stringliteral">&quot;Empty address &#39;%s&#39;&quot;</span>, <a name="l00654"></a>00654 address); <a name="l00655"></a>00655 } <a name="l00656"></a>00656 <a name="l00657"></a>00657 <a class="code" href="group__DBusAddress.html#ga37a7009b07cf991ff07f3e86d71bf352" title="Frees a NULL-terminated array of address entries.">dbus_address_entries_free</a> (entries); <a name="l00658"></a>00658 <a name="l00659"></a>00659 <span class="keywordflow">if</span> (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00660"></a>00660 { <a name="l00661"></a>00661 _dbus_assert (error == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a> || <a class="code" href="group__DBusErrors.html#gab0ed62e9fc2685897eb2d41467c89405" title="Checks whether an error occurred (the error is set).">dbus_error_is_set</a> (&amp;first_connect_error) || <a name="l00662"></a>00662 <a class="code" href="group__DBusErrors.html#gab0ed62e9fc2685897eb2d41467c89405" title="Checks whether an error occurred (the error is set).">dbus_error_is_set</a> (error)); <a name="l00663"></a>00663 <a name="l00664"></a>00664 <span class="keywordflow">if</span> (error &amp;&amp; <a class="code" href="group__DBusErrors.html#gab0ed62e9fc2685897eb2d41467c89405" title="Checks whether an error occurred (the error is set).">dbus_error_is_set</a> (error)) <a name="l00665"></a>00665 { <a name="l00666"></a>00666 <span class="comment">/* already set the error */</span> <a name="l00667"></a>00667 } <a name="l00668"></a>00668 <span class="keywordflow">else</span> <a name="l00669"></a>00669 { <a name="l00670"></a>00670 <span class="comment">/* didn&#39;t set the error but either error should be</span> <a name="l00671"></a>00671 <span class="comment"> * NULL or first_connect_error should be set.</span> <a name="l00672"></a>00672 <span class="comment"> */</span> <a name="l00673"></a>00673 _dbus_assert (error == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a> || <a class="code" href="group__DBusErrors.html#gab0ed62e9fc2685897eb2d41467c89405" title="Checks whether an error occurred (the error is set).">dbus_error_is_set</a> (&amp;first_connect_error)); <a name="l00674"></a>00674 <a class="code" href="group__DBusErrors.html#ga0a27fb9f1af0c2bfd105d7e8622b93f4" title="Moves an error src into dest, freeing src and overwriting dest.">dbus_move_error</a> (&amp;first_connect_error, error); <a name="l00675"></a>00675 } <a name="l00676"></a>00676 <a name="l00677"></a>00677 _DBUS_ASSERT_ERROR_IS_CLEAR (&amp;first_connect_error); <span class="comment">/* be sure we freed it */</span> <a name="l00678"></a>00678 _DBUS_ASSERT_ERROR_IS_SET (error); <a name="l00679"></a>00679 <a name="l00680"></a>00680 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00681"></a>00681 } <a name="l00682"></a>00682 <span class="keywordflow">else</span> <a name="l00683"></a>00683 { <a name="l00684"></a>00684 _DBUS_ASSERT_ERROR_IS_CLEAR (error); <a name="l00685"></a>00685 <span class="keywordflow">return</span> server; <a name="l00686"></a>00686 } <a name="l00687"></a>00687 } <a name="l00688"></a>00688 <a name="l00695"></a>00695 <a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> * <a name="l00696"></a><a class="code" href="group__DBusServer.html#gabe1c14264ef6bf3e5fe446ab9bf8b913">00696</a> <a class="code" href="group__DBusServer.html#gabe1c14264ef6bf3e5fe446ab9bf8b913" title="Increments the reference count of a DBusServer.">dbus_server_ref</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00697"></a>00697 { <a name="l00698"></a>00698 dbus_int32_t old_refcount; <a name="l00699"></a>00699 <a name="l00700"></a>00700 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00701"></a>00701 <a name="l00702"></a>00702 <span class="comment">/* can&#39;t get the refcount without a side-effect */</span> <a name="l00703"></a>00703 old_refcount = <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00704"></a>00704 <a name="l00705"></a>00705 <span class="preprocessor">#ifndef DBUS_DISABLE_CHECKS</span> <a name="l00706"></a>00706 <span class="preprocessor"></span> <span class="keywordflow">if</span> (_DBUS_UNLIKELY (old_refcount &lt;= 0)) <a name="l00707"></a>00707 { <a name="l00708"></a>00708 <span class="comment">/* undo side-effect first */</span> <a name="l00709"></a>00709 <a class="code" href="group__DBusSysdeps.html#ga3c50a069f795dceeb9172fe2b517bbdc" title="Atomically decrement an integer.">_dbus_atomic_dec</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00710"></a>00710 <a class="code" href="group__DBusInternalsUtils.html#ga63f2f8a068454b781f214ba596e313b4" title="Prints a &quot;critical&quot; warning to stderr when an assertion fails; differs from _dbus_warn primarily in t...">_dbus_warn_check_failed</a> (<a class="code" href="group__DBusInternalsUtils.html#ga748d6ccfb8090bf9f0bf338946c8f5e2" title="String used in _dbus_return_if_fail macro.">_dbus_return_if_fail_warning_format</a>, <a name="l00711"></a>00711 _DBUS_FUNCTION_NAME, <span class="stringliteral">&quot;old_refcount &gt; 0&quot;</span>, <a name="l00712"></a>00712 __FILE__, __LINE__); <a name="l00713"></a>00713 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00714"></a>00714 } <a name="l00715"></a>00715 <span class="preprocessor">#endif</span> <a name="l00716"></a>00716 <span class="preprocessor"></span> <a name="l00717"></a>00717 _dbus_server_trace_ref (server, old_refcount, old_refcount + 1, <span class="stringliteral">&quot;ref&quot;</span>); <a name="l00718"></a>00718 <a name="l00719"></a>00719 <span class="keywordflow">return</span> server; <a name="l00720"></a>00720 } <a name="l00721"></a>00721 <a name="l00730"></a>00730 <span class="keywordtype">void</span> <a name="l00731"></a><a class="code" href="group__DBusServer.html#ga95d0b6cb9795b4919aa08f667807c555">00731</a> <a class="code" href="group__DBusServer.html#ga95d0b6cb9795b4919aa08f667807c555" title="Decrements the reference count of a DBusServer.">dbus_server_unref</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00732"></a>00732 { <a name="l00733"></a>00733 dbus_int32_t old_refcount; <a name="l00734"></a>00734 <a name="l00735"></a>00735 <span class="comment">/* keep this in sync with unref_unlocked */</span> <a name="l00736"></a>00736 <a name="l00737"></a>00737 _dbus_return_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00738"></a>00738 <a name="l00739"></a>00739 <span class="comment">/* can&#39;t get the refcount without a side-effect */</span> <a name="l00740"></a>00740 old_refcount = <a class="code" href="group__DBusSysdeps.html#ga3c50a069f795dceeb9172fe2b517bbdc" title="Atomically decrement an integer.">_dbus_atomic_dec</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00741"></a>00741 <a name="l00742"></a>00742 <span class="preprocessor">#ifndef DBUS_DISABLE_CHECKS</span> <a name="l00743"></a>00743 <span class="preprocessor"></span> <span class="keywordflow">if</span> (_DBUS_UNLIKELY (old_refcount &lt;= 0)) <a name="l00744"></a>00744 { <a name="l00745"></a>00745 <span class="comment">/* undo side-effect first */</span> <a name="l00746"></a>00746 <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00747"></a>00747 <a class="code" href="group__DBusInternalsUtils.html#ga63f2f8a068454b781f214ba596e313b4" title="Prints a &quot;critical&quot; warning to stderr when an assertion fails; differs from _dbus_warn primarily in t...">_dbus_warn_check_failed</a> (<a class="code" href="group__DBusInternalsUtils.html#ga748d6ccfb8090bf9f0bf338946c8f5e2" title="String used in _dbus_return_if_fail macro.">_dbus_return_if_fail_warning_format</a>, <a name="l00748"></a>00748 _DBUS_FUNCTION_NAME, <span class="stringliteral">&quot;old_refcount &gt; 0&quot;</span>, <a name="l00749"></a>00749 __FILE__, __LINE__); <a name="l00750"></a>00750 <span class="keywordflow">return</span>; <a name="l00751"></a>00751 } <a name="l00752"></a>00752 <span class="preprocessor">#endif</span> <a name="l00753"></a>00753 <span class="preprocessor"></span> <a name="l00754"></a>00754 _dbus_server_trace_ref (server, old_refcount, old_refcount - 1, <span class="stringliteral">&quot;unref&quot;</span>); <a name="l00755"></a>00755 <a name="l00756"></a>00756 <span class="keywordflow">if</span> (old_refcount == 1) <a name="l00757"></a>00757 { <a name="l00758"></a>00758 <span class="comment">/* lock not held! */</span> <a name="l00759"></a>00759 _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a>); <a name="l00760"></a>00760 <a name="l00761"></a>00761 _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#acd97315e812352da38449f910775b08d" title="The finalize method must free the server.">finalize</a> != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00762"></a>00762 <a name="l00763"></a>00763 (* server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#acd97315e812352da38449f910775b08d" title="The finalize method must free the server.">finalize</a>) (server); <a name="l00764"></a>00764 } <a name="l00765"></a>00765 } <a name="l00766"></a>00766 <a name="l00775"></a>00775 <span class="keywordtype">void</span> <a name="l00776"></a><a class="code" href="group__DBusServer.html#ga1ff306fbaaa608306b0619ba5c0029a1">00776</a> <a class="code" href="group__DBusServer.html#ga1ff306fbaaa608306b0619ba5c0029a1" title="Releases the server&#39;s address and stops listening for new clients.">dbus_server_disconnect</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00777"></a>00777 { <a name="l00778"></a>00778 _dbus_return_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00779"></a>00779 <a name="l00780"></a>00780 <span class="preprocessor">#ifdef DBUS_DISABLE_CHECKS</span> <a name="l00781"></a>00781 <span class="preprocessor"></span> <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00782"></a>00782 <span class="preprocessor">#else</span> <a name="l00783"></a>00783 <span class="preprocessor"></span> { <a name="l00784"></a>00784 dbus_int32_t old_refcount = <a class="code" href="group__DBusSysdeps.html#gae74c3fcf12acaeccdb152ef907de951c" title="Atomically increments an integer.">_dbus_atomic_inc</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a7578bd99fc8aee641cbb5198cb2e7004" title="Reference count.">refcount</a>); <a name="l00785"></a>00785 <a name="l00786"></a>00786 _dbus_return_if_fail (old_refcount &gt; 0); <a name="l00787"></a>00787 } <a name="l00788"></a>00788 <span class="preprocessor">#endif</span> <a name="l00789"></a>00789 <span class="preprocessor"></span> <a name="l00790"></a>00790 SERVER_LOCK (server); <a name="l00791"></a>00791 <a name="l00792"></a>00792 _dbus_assert (server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#a148b105ac0a3a5ae8efbba29bf7fe676" title="Disconnect this server.">disconnect</a> != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00793"></a>00793 <a name="l00794"></a>00794 <span class="keywordflow">if</span> (!server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a>) <a name="l00795"></a>00795 { <a name="l00796"></a>00796 <span class="comment">/* this has to be first so recursive calls to disconnect don&#39;t happen */</span> <a name="l00797"></a>00797 server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a> = <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l00798"></a>00798 <a name="l00799"></a>00799 (* server-&gt;<a class="code" href="structDBusServer.html#aa5068890fea8c7e7261b600e7256e009" title="Virtual methods for this instance.">vtable</a>-&gt;<a class="code" href="structDBusServerVTable.html#a148b105ac0a3a5ae8efbba29bf7fe676" title="Disconnect this server.">disconnect</a>) (server); <a name="l00800"></a>00800 } <a name="l00801"></a>00801 <a name="l00802"></a>00802 SERVER_UNLOCK (server); <a name="l00803"></a>00803 <a class="code" href="group__DBusServer.html#ga95d0b6cb9795b4919aa08f667807c555" title="Decrements the reference count of a DBusServer.">dbus_server_unref</a> (server); <a name="l00804"></a>00804 } <a name="l00805"></a>00805 <a name="l00811"></a>00811 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00812"></a><a class="code" href="group__DBusServer.html#ga93c36d8b42a3f2a4f3706a0c3609b3d1">00812</a> <a class="code" href="group__DBusServer.html#ga93c36d8b42a3f2a4f3706a0c3609b3d1" title="Returns TRUE if the server is still listening for new connections.">dbus_server_get_is_connected</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00813"></a>00813 { <a name="l00814"></a>00814 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> retval; <a name="l00815"></a>00815 <a name="l00816"></a>00816 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00817"></a>00817 <a name="l00818"></a>00818 SERVER_LOCK (server); <a name="l00819"></a>00819 retval = !server-&gt;<a class="code" href="structDBusServer.html#a7dabb30cdc09d6102810029fb56b8dfe" title="TRUE if we are disconnected.">disconnected</a>; <a name="l00820"></a>00820 SERVER_UNLOCK (server); <a name="l00821"></a>00821 <a name="l00822"></a>00822 <span class="keywordflow">return</span> retval; <a name="l00823"></a>00823 } <a name="l00824"></a>00824 <a name="l00832"></a>00832 <span class="keywordtype">char</span>* <a name="l00833"></a><a class="code" href="group__DBusServer.html#ga63a133dc2786afed48c87127baa96927">00833</a> <a class="code" href="group__DBusServer.html#ga63a133dc2786afed48c87127baa96927" title="Returns the address of the server, as a newly-allocated string which must be freed by the caller...">dbus_server_get_address</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00834"></a>00834 { <a name="l00835"></a>00835 <span class="keywordtype">char</span> *retval; <a name="l00836"></a>00836 <a name="l00837"></a>00837 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00838"></a>00838 <a name="l00839"></a>00839 SERVER_LOCK (server); <a name="l00840"></a>00840 retval = <a class="code" href="group__DBusInternalsUtils.html#ga9d00d77f6595b9d7ac1baf59d44bf58c" title="Duplicates a string.">_dbus_strdup</a> (server-&gt;<a class="code" href="structDBusServer.html#a359852bf33b3051180a9477da4d89acd" title="Address this server is listening on.">address</a>); <a name="l00841"></a>00841 SERVER_UNLOCK (server); <a name="l00842"></a>00842 <a name="l00843"></a>00843 <span class="keywordflow">return</span> retval; <a name="l00844"></a>00844 } <a name="l00845"></a>00845 <a name="l00868"></a>00868 <span class="keywordtype">char</span>* <a name="l00869"></a><a class="code" href="group__DBusServer.html#ga3b2920b3c65836113781d9dd00d1e139">00869</a> <a class="code" href="group__DBusServer.html#ga3b2920b3c65836113781d9dd00d1e139" title="Returns the unique ID of the server, as a newly-allocated string which must be freed by the caller...">dbus_server_get_id</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server) <a name="l00870"></a>00870 { <a name="l00871"></a>00871 <span class="keywordtype">char</span> *retval; <a name="l00872"></a>00872 <a name="l00873"></a>00873 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00874"></a>00874 <a name="l00875"></a>00875 SERVER_LOCK (server); <a name="l00876"></a>00876 retval = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00877"></a>00877 <a class="code" href="group__DBusString.html#ga7e509d4f959d19d96f83250e62287b06" title="Copies the data from the string into a char*.">_dbus_string_copy_data</a> (&amp;server-&gt;<a class="code" href="structDBusServer.html#a79cd5d1b25412d56b7fd41902d575794" title="Hex-encoded version of GUID.">guid_hex</a>, &amp;retval); <a name="l00878"></a>00878 SERVER_UNLOCK (server); <a name="l00879"></a>00879 <a name="l00880"></a>00880 <span class="keywordflow">return</span> retval; <a name="l00881"></a>00881 } <a name="l00882"></a>00882 <a name="l00903"></a>00903 <span class="keywordtype">void</span> <a name="l00904"></a><a class="code" href="group__DBusServer.html#gaa14d9109e04adccffd9a40460c28c53b">00904</a> <a class="code" href="group__DBusServer.html#gaa14d9109e04adccffd9a40460c28c53b" title="Sets a function to be used for handling new connections.">dbus_server_set_new_connection_function</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00905"></a>00905 <a class="code" href="group__DBusServer.html#ga8478cd198973f6a6cb224ec23175faa7" title="Called when a new connection to the server is available.">DBusNewConnectionFunction</a> <span class="keyword">function</span>, <a name="l00906"></a>00906 <span class="keywordtype">void</span> *data, <a name="l00907"></a>00907 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> free_data_function) <a name="l00908"></a>00908 { <a name="l00909"></a>00909 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> old_free_function; <a name="l00910"></a>00910 <span class="keywordtype">void</span> *old_data; <a name="l00911"></a>00911 <a name="l00912"></a>00912 _dbus_return_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l00913"></a>00913 <a name="l00914"></a>00914 SERVER_LOCK (server); <a name="l00915"></a>00915 old_free_function = server-&gt;<a class="code" href="structDBusServer.html#a5d5b68a92cf47a3eb50e5e6ec7d2ca3a" title="Callback to invoke to free new_connection_data when server is finalized or data is replaced...">new_connection_free_data_function</a>; <a name="l00916"></a>00916 old_data = server-&gt;<a class="code" href="structDBusServer.html#acfba406ae6f288887feaccc3d621d094" title="Data for new connection callback.">new_connection_data</a>; <a name="l00917"></a>00917 <a name="l00918"></a>00918 server-&gt;<a class="code" href="structDBusServer.html#a964ff125a29a7dac02f81e1a26233ff6" title="Callback to invoke when a new connection is created.">new_connection_function</a> = <span class="keyword">function</span>; <a name="l00919"></a>00919 server-&gt;<a class="code" href="structDBusServer.html#acfba406ae6f288887feaccc3d621d094" title="Data for new connection callback.">new_connection_data</a> = data; <a name="l00920"></a>00920 server-&gt;<a class="code" href="structDBusServer.html#a5d5b68a92cf47a3eb50e5e6ec7d2ca3a" title="Callback to invoke to free new_connection_data when server is finalized or data is replaced...">new_connection_free_data_function</a> = free_data_function; <a name="l00921"></a>00921 SERVER_UNLOCK (server); <a name="l00922"></a>00922 <a name="l00923"></a>00923 <span class="keywordflow">if</span> (old_free_function != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l00924"></a>00924 (* old_free_function) (old_data); <a name="l00925"></a>00925 } <a name="l00926"></a>00926 <a name="l00943"></a>00943 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00944"></a><a class="code" href="group__DBusServer.html#gaa5723810ea52e9f1815062fd91395892">00944</a> <a class="code" href="group__DBusServer.html#gaa5723810ea52e9f1815062fd91395892" title="Sets the watch functions for the server.">dbus_server_set_watch_functions</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00945"></a>00945 <a class="code" href="group__DBusConnection.html#ga9188ca3fd89c957dc269dbe8601b270e" title="Called when libdbus needs a new watch to be monitored by the main loop.">DBusAddWatchFunction</a> add_function, <a name="l00946"></a>00946 <a class="code" href="group__DBusConnection.html#gaaab846a872d938b27503129551ea0c62" title="Called when libdbus no longer needs a watch to be monitored by the main loop.">DBusRemoveWatchFunction</a> remove_function, <a name="l00947"></a>00947 <a class="code" href="group__DBusConnection.html#gace13544ff3075b5fccbce896682ec6ff" title="Called when dbus_watch_get_enabled() may return a different value than it did before.">DBusWatchToggledFunction</a> toggled_function, <a name="l00948"></a>00948 <span class="keywordtype">void</span> *data, <a name="l00949"></a>00949 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> free_data_function) <a name="l00950"></a>00950 { <a name="l00951"></a>00951 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> result; <a name="l00952"></a>00952 <a class="code" href="structDBusWatchList.html" title="DBusWatchList implementation details.">DBusWatchList</a> *watches; <a name="l00953"></a>00953 <a name="l00954"></a>00954 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l00955"></a>00955 <a name="l00956"></a>00956 SERVER_LOCK (server); <a name="l00957"></a>00957 watches = server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a>; <a name="l00958"></a>00958 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l00959"></a>00959 <span class="keywordflow">if</span> (watches) <a name="l00960"></a>00960 { <a name="l00961"></a>00961 SERVER_UNLOCK (server); <a name="l00962"></a>00962 result = <a class="code" href="group__DBusWatchInternals.html#gae9ab8cf14f4191191e94183be9a031d9" title="Sets the watch functions.">_dbus_watch_list_set_functions</a> (watches, <a name="l00963"></a>00963 add_function, <a name="l00964"></a>00964 remove_function, <a name="l00965"></a>00965 toggled_function, <a name="l00966"></a>00966 data, <a name="l00967"></a>00967 free_data_function); <a name="l00968"></a>00968 SERVER_LOCK (server); <a name="l00969"></a>00969 } <a name="l00970"></a>00970 <span class="keywordflow">else</span> <a name="l00971"></a>00971 { <a name="l00972"></a>00972 <a class="code" href="group__DBusInternalsUtils.html#ga63f2f8a068454b781f214ba596e313b4" title="Prints a &quot;critical&quot; warning to stderr when an assertion fails; differs from _dbus_warn primarily in t...">_dbus_warn_check_failed</a> (<span class="stringliteral">&quot;Re-entrant call to %s\n&quot;</span>, _DBUS_FUNCTION_NAME); <a name="l00973"></a>00973 result = <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l00974"></a>00974 } <a name="l00975"></a>00975 server-&gt;<a class="code" href="structDBusServer.html#a7955050967aeaf09679f8ba1f2941880" title="Our watches.">watches</a> = watches; <a name="l00976"></a>00976 SERVER_UNLOCK (server); <a name="l00977"></a>00977 <a name="l00978"></a>00978 <span class="keywordflow">return</span> result; <a name="l00979"></a>00979 } <a name="l00980"></a>00980 <a name="l00996"></a>00996 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l00997"></a><a class="code" href="group__DBusServer.html#gacafa42ffc063a7386db40a975c32d530">00997</a> <a class="code" href="group__DBusServer.html#gacafa42ffc063a7386db40a975c32d530" title="Sets the timeout functions for the server.">dbus_server_set_timeout_functions</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l00998"></a>00998 <a class="code" href="group__DBusConnection.html#ga01a45587090d82ee97b5042b49037a08" title="Called when libdbus needs a new timeout to be monitored by the main loop.">DBusAddTimeoutFunction</a> add_function, <a name="l00999"></a>00999 <a class="code" href="group__DBusConnection.html#ga13aae9d5981de45abca0db1717dc7daf" title="Called when libdbus no longer needs a timeout to be monitored by the main loop.">DBusRemoveTimeoutFunction</a> remove_function, <a name="l01000"></a>01000 <a class="code" href="group__DBusConnection.html#ga62eea9a2032ae15b6738534b93d18e86" title="Called when dbus_timeout_get_enabled() may return a different value than it did before.">DBusTimeoutToggledFunction</a> toggled_function, <a name="l01001"></a>01001 <span class="keywordtype">void</span> *data, <a name="l01002"></a>01002 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> free_data_function) <a name="l01003"></a>01003 { <a name="l01004"></a>01004 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> result; <a name="l01005"></a>01005 <a class="code" href="structDBusTimeoutList.html" title="DBusTimeoutList implementation details.">DBusTimeoutList</a> *timeouts; <a name="l01006"></a>01006 <a name="l01007"></a>01007 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l01008"></a>01008 <a name="l01009"></a>01009 SERVER_LOCK (server); <a name="l01010"></a>01010 timeouts = server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a>; <a name="l01011"></a>01011 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l01012"></a>01012 <span class="keywordflow">if</span> (timeouts) <a name="l01013"></a>01013 { <a name="l01014"></a>01014 SERVER_UNLOCK (server); <a name="l01015"></a>01015 result = <a class="code" href="group__DBusTimeoutInternals.html#ga6760d1963b870b45f855501e38b49fd9" title="Sets the timeout functions.">_dbus_timeout_list_set_functions</a> (timeouts, <a name="l01016"></a>01016 add_function, <a name="l01017"></a>01017 remove_function, <a name="l01018"></a>01018 toggled_function, <a name="l01019"></a>01019 data, <a name="l01020"></a>01020 free_data_function); <a name="l01021"></a>01021 SERVER_LOCK (server); <a name="l01022"></a>01022 } <a name="l01023"></a>01023 <span class="keywordflow">else</span> <a name="l01024"></a>01024 { <a name="l01025"></a>01025 <a class="code" href="group__DBusInternalsUtils.html#ga63f2f8a068454b781f214ba596e313b4" title="Prints a &quot;critical&quot; warning to stderr when an assertion fails; differs from _dbus_warn primarily in t...">_dbus_warn_check_failed</a> (<span class="stringliteral">&quot;Re-entrant call to %s\n&quot;</span>, _DBUS_FUNCTION_NAME); <a name="l01026"></a>01026 result = <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l01027"></a>01027 } <a name="l01028"></a>01028 server-&gt;<a class="code" href="structDBusServer.html#afcaccd00f2392a390616c47e425bae85" title="Our timeouts.">timeouts</a> = timeouts; <a name="l01029"></a>01029 SERVER_UNLOCK (server); <a name="l01030"></a>01030 <a name="l01031"></a>01031 <span class="keywordflow">return</span> result; <a name="l01032"></a>01032 } <a name="l01033"></a>01033 <a name="l01047"></a>01047 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l01048"></a><a class="code" href="group__DBusServer.html#ga309e5f1510c74c4b221d12d874d53341">01048</a> <a class="code" href="group__DBusServer.html#ga309e5f1510c74c4b221d12d874d53341" title="Sets the authentication mechanisms that this server offers to clients, as a NULL-terminated array of ...">dbus_server_set_auth_mechanisms</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l01049"></a>01049 <span class="keyword">const</span> <span class="keywordtype">char</span> **mechanisms) <a name="l01050"></a>01050 { <a name="l01051"></a>01051 <span class="keywordtype">char</span> **copy; <a name="l01052"></a>01052 <a name="l01053"></a>01053 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l01054"></a>01054 <a name="l01055"></a>01055 SERVER_LOCK (server); <a name="l01056"></a>01056 <a name="l01057"></a>01057 <span class="keywordflow">if</span> (mechanisms != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l01058"></a>01058 { <a name="l01059"></a>01059 copy = <a class="code" href="group__DBusInternalsUtils.html#ga53bbcbbd0b564c14c599813dde535443" title="Duplicates a string array.">_dbus_dup_string_array</a> (mechanisms); <a name="l01060"></a>01060 <span class="keywordflow">if</span> (copy == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l01061"></a>01061 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>; <a name="l01062"></a>01062 } <a name="l01063"></a>01063 <span class="keywordflow">else</span> <a name="l01064"></a>01064 copy = <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>; <a name="l01065"></a>01065 <a name="l01066"></a>01066 <a class="code" href="group__DBusMemory.html#gac200b2dbc8b3f6ecac4d42426fb97b40" title="Frees a NULL-terminated array of strings.">dbus_free_string_array</a> (server-&gt;<a class="code" href="structDBusServer.html#adc1032bbed41413e5d0e01578f2bfffc" title="Array of allowed authentication mechanisms.">auth_mechanisms</a>); <a name="l01067"></a>01067 server-&gt;<a class="code" href="structDBusServer.html#adc1032bbed41413e5d0e01578f2bfffc" title="Array of allowed authentication mechanisms.">auth_mechanisms</a> = copy; <a name="l01068"></a>01068 <a name="l01069"></a>01069 SERVER_UNLOCK (server); <a name="l01070"></a>01070 <a name="l01071"></a>01071 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l01072"></a>01072 } <a name="l01073"></a>01073 <a name="l01074"></a>01074 <a name="l01075"></a>01075 <span class="keyword">static</span> <a class="code" href="structDBusDataSlotAllocator.html" title="An allocator that tracks a set of slot IDs.">DBusDataSlotAllocator</a> slot_allocator; <a name="l01076"></a>01076 _DBUS_DEFINE_GLOBAL_LOCK (server_slots); <a name="l01077"></a>01077 <a name="l01092"></a>01092 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l01093"></a><a class="code" href="group__DBusServer.html#ga05d280cd92ea5bb0d49bbe5b1fb1d5c2">01093</a> <a class="code" href="group__DBusServer.html#ga05d280cd92ea5bb0d49bbe5b1fb1d5c2" title="Allocates an integer ID to be used for storing application-specific data on any DBusServer.">dbus_server_allocate_data_slot</a> (dbus_int32_t *slot_p) <a name="l01094"></a>01094 { <a name="l01095"></a>01095 <span class="keywordflow">return</span> <a class="code" href="group__DBusDataSlot.html#ga2c37c4cfe534973b4e6260aa5014564f" title="Allocates an integer ID to be used for storing data in a DBusDataSlotList.">_dbus_data_slot_allocator_alloc</a> (&amp;slot_allocator, <a name="l01096"></a>01096 (<a class="code" href="structDBusRMutex.html">DBusRMutex</a> **)&amp;_DBUS_LOCK_NAME (server_slots), <a name="l01097"></a>01097 slot_p); <a name="l01098"></a>01098 } <a name="l01099"></a>01099 <a name="l01111"></a>01111 <span class="keywordtype">void</span> <a name="l01112"></a><a class="code" href="group__DBusServer.html#gac6ebc6105e32ab38ef0ac60dec6d5bc8">01112</a> <a class="code" href="group__DBusServer.html#gac6ebc6105e32ab38ef0ac60dec6d5bc8" title="Deallocates a global ID for server data slots.">dbus_server_free_data_slot</a> (dbus_int32_t *slot_p) <a name="l01113"></a>01113 { <a name="l01114"></a>01114 _dbus_return_if_fail (*slot_p &gt;= 0); <a name="l01115"></a>01115 <a name="l01116"></a>01116 <a class="code" href="group__DBusDataSlot.html#ga059c50a24cd9fc984e918e6159841633" title="Deallocates an ID previously allocated with _dbus_data_slot_allocator_alloc().">_dbus_data_slot_allocator_free</a> (&amp;slot_allocator, slot_p); <a name="l01117"></a>01117 } <a name="l01118"></a>01118 <a name="l01132"></a>01132 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l01133"></a><a class="code" href="group__DBusServer.html#gab9ecb216dc9c40b0c7d370673fb9b269">01133</a> <a class="code" href="group__DBusServer.html#gab9ecb216dc9c40b0c7d370673fb9b269" title="Stores a pointer on a DBusServer, along with an optional function to be used for freeing the data whe...">dbus_server_set_data</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l01134"></a>01134 <span class="keywordtype">int</span> slot, <a name="l01135"></a>01135 <span class="keywordtype">void</span> *data, <a name="l01136"></a>01136 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> free_data_func) <a name="l01137"></a>01137 { <a name="l01138"></a>01138 <a class="code" href="group__DBusMemory.html#ga061bcded226d76c7d7de35beaa165cb5" title="The type of a function which frees a block of memory.">DBusFreeFunction</a> old_free_func; <a name="l01139"></a>01139 <span class="keywordtype">void</span> *old_data; <a name="l01140"></a>01140 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> retval; <a name="l01141"></a>01141 <a name="l01142"></a>01142 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#gaa93f0eb578d23995850d61f7d61c55c1" title="Expands to &quot;0&quot;.">FALSE</a>); <a name="l01143"></a>01143 <a name="l01144"></a>01144 SERVER_LOCK (server); <a name="l01145"></a>01145 <a name="l01146"></a>01146 retval = <a class="code" href="group__DBusDataSlot.html#gad2952f9f686d96e7114fc49ab7452e1a" title="Stores a pointer in the data slot list, along with an optional function to be used for freeing the da...">_dbus_data_slot_list_set</a> (&amp;slot_allocator, <a name="l01147"></a>01147 &amp;server-&gt;<a class="code" href="structDBusServer.html#a0601cca8307ba17d4a8bcebe48b08362" title="Data stored by allocated integer ID.">slot_list</a>, <a name="l01148"></a>01148 slot, data, free_data_func, <a name="l01149"></a>01149 &amp;old_free_func, &amp;old_data); <a name="l01150"></a>01150 <a name="l01151"></a>01151 <a name="l01152"></a>01152 SERVER_UNLOCK (server); <a name="l01153"></a>01153 <a name="l01154"></a>01154 <span class="keywordflow">if</span> (retval) <a name="l01155"></a>01155 { <a name="l01156"></a>01156 <span class="comment">/* Do the actual free outside the server lock */</span> <a name="l01157"></a>01157 <span class="keywordflow">if</span> (old_free_func) <a name="l01158"></a>01158 (* old_free_func) (old_data); <a name="l01159"></a>01159 } <a name="l01160"></a>01160 <a name="l01161"></a>01161 <span class="keywordflow">return</span> retval; <a name="l01162"></a>01162 } <a name="l01163"></a>01163 <a name="l01172"></a>01172 <span class="keywordtype">void</span>* <a name="l01173"></a><a class="code" href="group__DBusServer.html#gac2bfa9f2e06c4347fefe537b233660d3">01173</a> <a class="code" href="group__DBusServer.html#gac2bfa9f2e06c4347fefe537b233660d3" title="Retrieves data previously set with dbus_server_set_data().">dbus_server_get_data</a> (<a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server, <a name="l01174"></a>01174 <span class="keywordtype">int</span> slot) <a name="l01175"></a>01175 { <a name="l01176"></a>01176 <span class="keywordtype">void</span> *res; <a name="l01177"></a>01177 <a name="l01178"></a>01178 _dbus_return_val_if_fail (server != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>, <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l01179"></a>01179 <a name="l01180"></a>01180 SERVER_LOCK (server); <a name="l01181"></a>01181 <a name="l01182"></a>01182 res = <a class="code" href="group__DBusDataSlot.html#ga43f741229f0c38788442601e2750ec66" title="Retrieves data previously set with _dbus_data_slot_list_set_data().">_dbus_data_slot_list_get</a> (&amp;slot_allocator, <a name="l01183"></a>01183 &amp;server-&gt;<a class="code" href="structDBusServer.html#a0601cca8307ba17d4a8bcebe48b08362" title="Data stored by allocated integer ID.">slot_list</a>, <a name="l01184"></a>01184 slot); <a name="l01185"></a>01185 <a name="l01186"></a>01186 SERVER_UNLOCK (server); <a name="l01187"></a>01187 <a name="l01188"></a>01188 <span class="keywordflow">return</span> res; <a name="l01189"></a>01189 } <a name="l01190"></a>01190 <a name="l01193"></a>01193 <span class="preprocessor">#ifdef DBUS_BUILD_TESTS</span> <a name="l01194"></a>01194 <span class="preprocessor"></span><span class="preprocessor">#include &quot;dbus-test.h&quot;</span> <a name="l01195"></a>01195 <span class="preprocessor">#include &lt;string.h&gt;</span> <a name="l01196"></a>01196 <a name="l01197"></a>01197 <a class="code" href="group__DBusTypes.html#ga39c9cb0f3a2a8ad6f55cc4855d035349" title="A boolean, valid values are TRUE and FALSE.">dbus_bool_t</a> <a name="l01198"></a>01198 _dbus_server_test (<span class="keywordtype">void</span>) <a name="l01199"></a>01199 { <a name="l01200"></a>01200 <span class="keyword">const</span> <span class="keywordtype">char</span> *valid_addresses[] = { <a name="l01201"></a>01201 <span class="stringliteral">&quot;tcp:port=1234&quot;</span>, <a name="l01202"></a>01202 <span class="stringliteral">&quot;tcp:host=localhost,port=1234&quot;</span>, <a name="l01203"></a>01203 <span class="stringliteral">&quot;tcp:host=localhost,port=1234;tcp:port=5678&quot;</span>, <a name="l01204"></a>01204 <span class="preprocessor">#ifdef DBUS_UNIX</span> <a name="l01205"></a>01205 <span class="preprocessor"></span> <span class="stringliteral">&quot;unix:path=./boogie&quot;</span>, <a name="l01206"></a>01206 <span class="stringliteral">&quot;tcp:port=1234;unix:path=./boogie&quot;</span>, <a name="l01207"></a>01207 <span class="preprocessor">#endif</span> <a name="l01208"></a>01208 <span class="preprocessor"></span> }; <a name="l01209"></a>01209 <a name="l01210"></a>01210 <a class="code" href="structDBusServer.html" title="Internals of DBusServer object.">DBusServer</a> *server; <a name="l01211"></a>01211 <span class="keywordtype">int</span> i; <a name="l01212"></a>01212 <a name="l01213"></a>01213 <span class="keywordflow">for</span> (i = 0; i &lt; _DBUS_N_ELEMENTS (valid_addresses); i++) <a name="l01214"></a>01214 { <a name="l01215"></a>01215 <a class="code" href="structDBusError.html" title="Object representing an exception.">DBusError</a> error = <a class="code" href="group__DBusErrorInternals.html#ga961cc70e3891282a65205c4c8418d88e" title="Expands to a suitable initializer for a DBusError on the stack.">DBUS_ERROR_INIT</a>; <a name="l01216"></a>01216 <span class="keywordtype">char</span> *address; <a name="l01217"></a>01217 <span class="keywordtype">char</span> *id; <a name="l01218"></a>01218 <a name="l01219"></a>01219 server = <a class="code" href="group__DBusServer.html#ga4c83cf9f2c186afa97decdc25ac163d8" title="Listens for new connections on the given address.">dbus_server_listen</a> (valid_addresses[i], &amp;error); <a name="l01220"></a>01220 <span class="keywordflow">if</span> (server == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l01221"></a>01221 { <a name="l01222"></a>01222 <a class="code" href="group__DBusInternalsUtils.html#gabea2c16d6d3fe7c4eb5b9496fc877f84" title="Prints a warning message to stderr.">_dbus_warn</a> (<span class="stringliteral">&quot;server listen error: %s: %s\n&quot;</span>, error.<a class="code" href="structDBusError.html#a09a9614ff07fdf3ef163b232ff934581" title="public error name field">name</a>, error.<a class="code" href="structDBusError.html#afb559175326de5b6b340e26204e92d72" title="public error message field">message</a>); <a name="l01223"></a>01223 <a class="code" href="group__DBusErrors.html#gaac6c14ead14829ee4e090f39de6a7568" title="Frees an error that&#39;s been set (or just initialized), then reinitializes the error as in dbus_error_i...">dbus_error_free</a> (&amp;error); <a name="l01224"></a>01224 _dbus_assert_not_reached (<span class="stringliteral">&quot;Failed to listen for valid address.&quot;</span>); <a name="l01225"></a>01225 } <a name="l01226"></a>01226 <a name="l01227"></a>01227 <span class="keywordtype">id</span> = <a class="code" href="group__DBusServer.html#ga3b2920b3c65836113781d9dd00d1e139" title="Returns the unique ID of the server, as a newly-allocated string which must be freed by the caller...">dbus_server_get_id</a> (server); <a name="l01228"></a>01228 _dbus_assert (<span class="keywordtype">id</span> != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l01229"></a>01229 address = <a class="code" href="group__DBusServer.html#ga63a133dc2786afed48c87127baa96927" title="Returns the address of the server, as a newly-allocated string which must be freed by the caller...">dbus_server_get_address</a> (server); <a name="l01230"></a>01230 _dbus_assert (address != <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>); <a name="l01231"></a>01231 <a name="l01232"></a>01232 <span class="keywordflow">if</span> (strstr (address, <span class="keywordtype">id</span>) == <a class="code" href="group__DBusMacros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4" title="A null pointer, defined appropriately for C or C++.">NULL</a>) <a name="l01233"></a>01233 { <a name="l01234"></a>01234 <a class="code" href="group__DBusInternalsUtils.html#gabea2c16d6d3fe7c4eb5b9496fc877f84" title="Prints a warning message to stderr.">_dbus_warn</a> (<span class="stringliteral">&quot;server id &#39;%s&#39; is not in the server address &#39;%s&#39;\n&quot;</span>, <a name="l01235"></a>01235 <span class="keywordtype">id</span>, address); <a name="l01236"></a>01236 _dbus_assert_not_reached (<span class="stringliteral">&quot;bad server id or address&quot;</span>); <a name="l01237"></a>01237 } <a name="l01238"></a>01238 <a name="l01239"></a>01239 <a class="code" href="group__DBusMemory.html#ga34e666b19b015035a9a31e53da84b39a" title="Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().">dbus_free</a> (<span class="keywordtype">id</span>); <a name="l01240"></a>01240 <a class="code" href="group__DBusMemory.html#ga34e666b19b015035a9a31e53da84b39a" title="Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().">dbus_free</a> (address); <a name="l01241"></a>01241 <a name="l01242"></a>01242 <a class="code" href="group__DBusServer.html#ga1ff306fbaaa608306b0619ba5c0029a1" title="Releases the server&#39;s address and stops listening for new clients.">dbus_server_disconnect</a> (server); <a name="l01243"></a>01243 <a class="code" href="group__DBusServer.html#ga95d0b6cb9795b4919aa08f667807c555" title="Decrements the reference count of a DBusServer.">dbus_server_unref</a> (server); <a name="l01244"></a>01244 } <a name="l01245"></a>01245 <a name="l01246"></a>01246 <span class="keywordflow">return</span> <a class="code" href="group__DBusMacros.html#gaa8cecfc5c5c054d2875c03e77b7be15d" title="Expands to &quot;1&quot;.">TRUE</a>; <a name="l01247"></a>01247 } <a name="l01248"></a>01248 <a name="l01249"></a>01249 <span class="preprocessor">#endif </span><span class="comment">/* DBUS_BUILD_TESTS */</span> </pre></div></div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated on Fri Dec 21 2012 17:59:19 for D-Bus by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: use itertools::Itertools; use std::fmt; use std::fmt::Write as _; use crate::bitboard::Factory as BBFactory; use crate::{Bitboard, Color, Hand, Move, MoveError, Piece, PieceType, SfenError, Square}; /// MoveRecord stores information necessary to undo the move. #[derive(Debug)] pub enum MoveRecord { Normal { from: Square, to: Square, placed: Piece, captured: Option<Piece>, promoted: bool, }, Drop { to: Square, piece: Piece, }, } impl MoveRecord { /// Converts the move into SFEN formatted string. pub fn to_sfen(&self) -> String { match *self { MoveRecord::Normal { from, to, promoted, .. } => format!("{}{}{}", from, to, if promoted { "+" } else { "" }), MoveRecord::Drop { to, piece: Piece { piece_type, .. }, } => format!("{}*{}", piece_type.to_string().to_uppercase(), to), } } } impl PartialEq<Move> for MoveRecord { fn eq(&self, other: &Move) -> bool { match (self, other) { ( &MoveRecord::Normal { from: f1, to: t1, promoted, .. }, &Move::Normal { from: f2, to: t2, promote, }, ) => f1 == f2 && t1 == t2 && promote == promoted, (&MoveRecord::Drop { to: t1, piece, .. }, &Move::Drop { to: t2, piece_type }) => { t1 == t2 && piece.piece_type == piece_type } _ => false, } } } struct PieceGrid([Option<Piece>; 81]); impl PieceGrid { pub fn get(&self, sq: Square) -> &Option<Piece> { &self.0[sq.index()] } pub fn set(&mut self, sq: Square, pc: Option<Piece>) { self.0[sq.index()] = pc; } } impl fmt::Debug for PieceGrid { fn fmt(&self, fmt: &mut fmt: After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
3
use itertools::Itertools; use std::fmt; use std::fmt::Write as _; use crate::bitboard::Factory as BBFactory; use crate::{Bitboard, Color, Hand, Move, MoveError, Piece, PieceType, SfenError, Square}; /// MoveRecord stores information necessary to undo the move. #[derive(Debug)] pub enum MoveRecord { Normal { from: Square, to: Square, placed: Piece, captured: Option<Piece>, promoted: bool, }, Drop { to: Square, piece: Piece, }, } impl MoveRecord { /// Converts the move into SFEN formatted string. pub fn to_sfen(&self) -> String { match *self { MoveRecord::Normal { from, to, promoted, .. } => format!("{}{}{}", from, to, if promoted { "+" } else { "" }), MoveRecord::Drop { to, piece: Piece { piece_type, .. }, } => format!("{}*{}", piece_type.to_string().to_uppercase(), to), } } } impl PartialEq<Move> for MoveRecord { fn eq(&self, other: &Move) -> bool { match (self, other) { ( &MoveRecord::Normal { from: f1, to: t1, promoted, .. }, &Move::Normal { from: f2, to: t2, promote, }, ) => f1 == f2 && t1 == t2 && promote == promoted, (&MoveRecord::Drop { to: t1, piece, .. }, &Move::Drop { to: t2, piece_type }) => { t1 == t2 && piece.piece_type == piece_type } _ => false, } } } struct PieceGrid([Option<Piece>; 81]); impl PieceGrid { pub fn get(&self, sq: Square) -> &Option<Piece> { &self.0[sq.index()] } pub fn set(&mut self, sq: Square, pc: Option<Piece>) { self.0[sq.index()] = pc; } } impl fmt::Debug for PieceGrid { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(fmt, "PieceGrid {{ ")?; for pc in self.0.iter() { write!(fmt, "{pc:?} ")?; } write!(fmt, "}}") } } /// Represents a state of the game. /// /// # Examples /// /// ``` /// use shogi::{Move, Position}; /// use shogi::bitboard::Factory as BBFactory; /// use shogi::square::consts::*; /// /// BBFactory::init(); /// let mut pos = Position::new(); /// pos.set_sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1").unwrap(); /// /// let m = Move::Normal{from: SQ_7G, to: SQ_7F, promote: false}; /// pos.make_move(m).unwrap(); /// /// assert_eq!("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1 moves 7g7f", pos.to_sfen()); /// ``` #[derive(Debug)] pub struct Position { board: PieceGrid, hand: Hand, ply: u16, side_to_move: Color, move_history: Vec<MoveRecord>, sfen_history: Vec<(String, u16)>, occupied_bb: Bitboard, color_bb: [Bitboard; 2], type_bb: [Bitboard; 14], } ///////////////////////////////////////////////////////////////////////////// // Type implementation ///////////////////////////////////////////////////////////////////////////// impl Position { /// Creates a new instance of `Position` with an empty board. pub fn new() -> Position { Default::default() } ///////////////////////////////////////////////////////////////////////// // Accessors ///////////////////////////////////////////////////////////////////////// /// Returns a piece at the given square. pub fn piece_at(&self, sq: Square) -> &Option<Piece> { self.board.get(sq) } /// Returns a bitboard containing pieces of the given player. pub fn player_bb(&self, c: Color) -> &Bitboard { &self.color_bb[c.index()] } /// Returns the number of the given piece in hand. pub fn hand(&self, p: Piece) -> u8 { self.hand.get(p) } /// Returns the side to make a move next. pub fn side_to_move(&self) -> Color { self.side_to_move } /// Returns the number of plies already completed by the current state. pub fn ply(&self) -> u16 { self.ply } /// Returns a history of all moves made since the beginning of the game. pub fn move_history(&self) -> &[MoveRecord] { &self.move_history } /// Checks if a player with the given color can declare winning. /// /// See [the section 25 in 世界コンピュータ将棋選手権 大会ルール][csa] for more detail. /// /// [csa]: http://www2.computer-shogi.org/wcsc26/rule.pdf#page=9 pub fn try_declare_winning(&self, c: Color) -> bool { if c != self.side_to_move { return false; } let king_pos = self.find_king(c); if king_pos.is_none() { return false; } let king_pos = king_pos.unwrap(); if king_pos.relative_rank(c) >= 3 { return false; } let (mut point, count) = PieceType::iter() .filter(|&pt| pt != PieceType::King) .fold((0, 0), |accum, pt| { let unit = match pt { PieceType::Rook | PieceType::Bishop | PieceType::ProRook | PieceType::ProBishop => 5, _ => 1, }; let bb = &(&self.type_bb[pt.index()] & &self.color_bb[c.index()]) & &BBFactory::promote_zone(c); let count = bb.count() as u8; let point = count * unit; (accum.0 + point, accum.1 + count) }); if count < 10 { return false; } point += PieceType::iter() .filter(|pt| pt.is_hand_piece()) .fold(0, |acc, pt| { let num = self.hand.get(Piece { piece_type: pt, color: c, }); let pp = match pt { PieceType::Rook | PieceType::Bishop => 5, _ => 1, }; acc + num * pp }); let lowerbound = match c { Color::Black => 28, Color::White => 27, }; if point < lowerbound { return false; } if self.in_check(c) { return false; } true } /// Checks if the king with the given color is in check. pub fn in_check(&self, c: Color) -> bool { if let Some(king_sq) = self.find_king(c) { self.is_attacked_by(king_sq, c.flip()) } else { false } } /// Returns the position of the king with the given color. pub fn find_king(&self, c: Color) -> Option<Square> { let mut bb = &self.type_bb[PieceType::King.index()] & &self.color_bb[c.index()]; if bb.is_any() { Some(bb.pop()) } else { None } } /// Sets a piece at the given square. fn set_piece(&mut self, sq: Square, p: Option<Piece>) { self.board.set(sq, p); } fn is_attacked_by(&self, sq: Square, c: Color) -> bool { PieceType::iter().any(|pt| self.get_attackers_of_type(pt, sq, c).is_any()) } fn get_attackers_of_type(&self, pt: PieceType, sq: Square, c: Color) -> Bitboard { let bb = &self.type_bb[pt.index()] & &self.color_bb[c.index()]; if bb.is_empty() { return bb; } let attack_pc = Piece { piece_type: pt, color: c, }; &bb & &self.move_candidates(sq, attack_pc.flip()) } fn log_position(&mut self) { // TODO: SFEN string is used to represent a state of position, but any transformation which uniquely distinguish positions can be used here. // Consider light-weight option if generating SFEN string for each move is time-consuming. let sfen = self.generate_sfen().split(' ').take(3).join(" "); let in_check = self.in_check(self.side_to_move()); let continuous_check = if in_check { let past = if self.sfen_history.len() >= 2 { let record = self.sfen_history.get(self.sfen_history.len() - 2).unwrap(); record.1 } else { 0 }; past + 1 } else { 0 }; self.sfen_history.push((sfen, continuous_check)); } ///////////////////////////////////////////////////////////////////////// // Making a move ///////////////////////////////////////////////////////////////////////// /// Makes the given move. Returns `Err` if the move is invalid or any special condition is met. pub fn make_move(&mut self, m: Move) -> Result<(), MoveError> { let res = match m { Move::Normal { from, to, promote } => self.make_normal_move(from, to, promote)?, Move::Drop { to, piece_type } => self.make_drop_move(to, piece_type)?, }; self.move_history.push(res); Ok(()) } fn make_normal_move( &mut self, from: Square, to: Square, promoted: bool, ) -> Result<MoveRecord, MoveError> { let stm = self.side_to_move(); let opponent = stm.flip(); let moved = self .piece_at(from) .ok_or(MoveError::Inconsistent("No piece found"))?; let captured = *self.piece_at(to); if moved.color != stm { return Err(MoveError::Inconsistent( "The piece is not for the side to move", )); } if promoted && !from.in_promotion_zone(stm) && !to.in_promotion_zone(stm) { return Err(MoveError::Inconsistent("The piece cannot promote")); } if !self.move_candidates(from, moved).any(|sq| sq == to) { return Err(MoveError::Inconsistent("The piece cannot move to there")); } if !promoted && !moved.is_placeable_at(to) { return Err(MoveError::NonMovablePiece); } let placed = if promoted { match moved.promote() { Some(promoted) => promoted, None => return Err(MoveError::Inconsistent("This type of piece cannot promote")), } } else { moved }; self.set_piece(from, None); self.set_piece(to, Some(placed)); self.occupied_bb ^= from; self.occupied_bb ^= to; self.type_bb[moved.piece_type.index()] ^= from; self.type_bb[placed.piece_type.index()] ^= to; self.color_bb[moved.color.index()] ^= from; self.color_bb[placed.color.index()] ^= to; if let Some(ref cap) = captured { self.occupied_bb ^= to; self.type_bb[cap.piece_type.index()] ^= to; self.color_bb[cap.color.index()] ^= to; let pc = cap.flip(); let pc = match pc.unpromote() { Some(unpromoted) => unpromoted, None => pc, }; self.hand.increment(pc); } if self.in_check(stm) { // Undo-ing the move. self.set_piece(from, Some(moved)); self.set_piece(to, captured); self.occupied_bb ^= from; self.occupied_bb ^= to; self.type_bb[moved.piece_type.index()] ^= from; self.type_bb[placed.piece_type.index()] ^= to; self.color_bb[moved.color.index()] ^= from; self.color_bb[placed.color.index()] ^= to; if let Some(ref cap) = captured { self.occupied_bb ^= to; self.type_bb[cap.piece_type.index()] ^= to; self.color_bb[cap.color.index()] ^= to; let pc = cap.flip(); let pc = match pc.unpromote() { Some(unpromoted) => unpromoted, None => pc, }; self.hand.decrement(pc); } return Err(MoveError::InCheck); } self.side_to_move = opponent; self.ply += 1; self.log_position(); self.detect_repetition()?; Ok(MoveRecord::Normal { from, to, placed, captured, promoted, }) } fn make_drop_move(&mut self, to: Square, pt: PieceType) -> Result<MoveRecord, MoveError> { let stm = self.side_to_move(); let opponent = stm.flip(); if self.piece_at(to).is_some() { return Err(MoveError::Inconsistent("There is already a piece in `to`")); } let pc = Piece { piece_type: pt, color: stm, }; if self.hand(pc) == 0 { return Err(MoveError::Inconsistent("The piece is not in the hand")); } if !pc.is_placeable_at(to) { return Err(MoveError::NonMovablePiece); } if pc.piece_type == PieceType::Pawn { // Nifu check. for i in 0..9 { if let Some(fp) = *self.piece_at(Square::new(to.file(), i).unwrap()) { if fp == pc { return Err(MoveError::Nifu); } } } // Uchifuzume check. if let Some(king_sq) = to.shift(0, if stm == Color::Black { -1 } else { 1 }) { // Is the dropped pawn attacking the opponent's king? if let Some( pc @ Piece { piece_type: PieceType::King, .. }, ) = *self.piece_at(king_sq) { if pc.color == opponent { // can any opponent's piece attack the dropped pawn? let pinned = self.pinned_bb(opponent); let not_attacked = PieceType::iter() .filter(|&pt| pt != PieceType::King) .flat_map(|pt| self.get_attackers_of_type(pt, to, opponent)) .all(|sq| (&pinned & sq).is_any()); if not_attacked { // the dropped pawn may block bishop's moves self.occupied_bb ^= to; // can the opponent's king evade? let is_attacked = |sq| { if let Some(pc) = *self.piece_at(sq) { if pc.color == opponent { return true; } } self.is_attacked_by(sq, stm) }; let uchifuzume = self.move_candidates(king_sq, pc).all(is_attacked); self.occupied_bb ^= to; if uchifuzume { return Err(MoveError::Uchifuzume); } } } } } } self.set_piece(to, Some(pc)); self.occupied_bb ^= to; self.type_bb[pc.piece_type.index()] ^= to; self.color_bb[pc.color.index()] ^= to; if self.in_check(stm) { // Undo-ing the move. self.set_piece(to, None); self.occupied_bb ^= to; self.type_bb[pc.piece_type.index()] ^= to; self.color_bb[pc.color.index()] ^= to; return Err(MoveError::InCheck); } self.hand.decrement(pc); self.side_to_move = opponent; self.ply += 1; self.log_position(); self.detect_repetition()?; Ok(MoveRecord::Drop { to, piece: pc }) } /// Returns a list of squares at which a piece of the given color is pinned. pub fn pinned_bb(&self, c: Color) -> Bitboard { let ksq = self.find_king(c); if ksq.is_none() { return Bitboard::empty(); } let ksq = ksq.unwrap(); [ ( PieceType::Rook, BBFactory::rook_attack(ksq, &Bitboard::empty()), ), ( PieceType::ProRook, BBFactory::rook_attack(ksq, &Bitboard::empty()), ), ( PieceType::Bishop, BBFactory::bishop_attack(ksq, &Bitboard::empty()), ), ( PieceType::ProBishop, BBFactory::bishop_attack(ksq, &Bitboard::empty()), ), ( PieceType::Lance, BBFactory::lance_attack(c, ksq, &Bitboard::empty()), ), ] .iter() .fold(Bitboard::empty(), |mut accum, &(pt, ref mask)| { let bb = &(&self.type_bb[pt.index()] & &self.color_bb[c.flip().index()]) & mask; for psq in bb { let between = &BBFactory::between(ksq, psq) & &self.occupied_bb; if between.count() == 1 && (&between & &self.color_bb[c.index()]).is_any() { accum |= &between; } } accum }) } /// Undoes the last move. pub fn unmake_move(&mut self) -> Result<(), MoveError> { if self.move_history.is_empty() { // TODO: error? return Ok(()); } let last = self.move_history.pop().unwrap(); match last { MoveRecord::Normal { from, to, ref placed, ref captured, promoted, } => { if self.piece_at(from).is_some() { return Err(MoveError::Inconsistent( "`from` of the move is filled by another piece", )); } let moved = if promoted { match placed.unpromote() { Some(unpromoted) => unpromoted, None => return Err(MoveError::Inconsistent("Cannot unpromoted the piece")), } } else { *placed }; if *self.piece_at(to) != Some(*placed) { return Err(MoveError::Inconsistent( "Expected piece is not found in `to`", )); } self.set_piece(from, Some(moved)); self.set_piece(to, *captured); self.occupied_bb ^= from; self.occupied_bb ^= to; self.type_bb[moved.piece_type.index()] ^= from; self.type_bb[placed.piece_type.index()] ^= to; self.color_bb[moved.color.index()] ^= from; self.color_bb[placed.color.index()] ^= to; if let Some(ref cap) = *captured { self.occupied_bb ^= to; self.type_bb[cap.piece_type.index()] ^= to; self.color_bb[cap.color.index()] ^= to; let unpromoted_cap = cap.unpromote().unwrap_or(*cap); self.hand.decrement(unpromoted_cap.flip()); } } MoveRecord::Drop { to, piece } => { if *self.piece_at(to) != Some(piece) { return Err(MoveError::Inconsistent( "Expected piece is not found in `to`", )); } self.set_piece(to, None); self.occupied_bb ^= to; self.type_bb[piece.piece_type.index()] ^= to; self.color_bb[piece.color.index()] ^= to; self.hand.increment(piece); } }; self.side_to_move = self.side_to_move.flip(); self.ply -= 1; self.sfen_history.pop(); Ok(()) } /// Returns a list of squares to where the given piece at the given square can move. pub fn move_candidates(&self, sq: Square, p: Piece) -> Bitboard { let bb = match p.piece_type { PieceType::Rook => BBFactory::rook_attack(sq, &self.occupied_bb), PieceType::Bishop => BBFactory::bishop_attack(sq, &self.occupied_bb), PieceType::Lance => BBFactory::lance_attack(p.color, sq, &self.occupied_bb), PieceType::ProRook => { &BBFactory::rook_attack(sq, &self.occupied_bb) | &BBFactory::attacks_from(PieceType::King, p.color, sq) } PieceType::ProBishop => { &BBFactory::bishop_attack(sq, &self.occupied_bb) | &BBFactory::attacks_from(PieceType::King, p.color, sq) } PieceType::ProSilver | PieceType::ProKnight | PieceType::ProLance | PieceType::ProPawn => BBFactory::attacks_from(PieceType::Gold, p.color, sq), pt => BBFactory::attacks_from(pt, p.color, sq), }; &bb & &!&self.color_bb[p.color.index()] } fn detect_repetition(&self) -> Result<(), MoveError> { if self.sfen_history.len() < 9 { return Ok(()); } let cur = self.sfen_history.last().unwrap(); let mut cnt = 0; for (i, entry) in self.sfen_history.iter().rev().enumerate() { if entry.0 == cur.0 { cnt += 1; if cnt == 4 { let prev = self.sfen_history.get(self.sfen_history.len() - 2).unwrap(); if cur.1 * 2 >= (i as u16) { return Err(MoveError::PerpetualCheckLose); } else if prev.1 * 2 >= (i as u16) { return Err(MoveError::PerpetualCheckWin); } else { return Err(MoveError::Repetition); } } } } Ok(()) } ///////////////////////////////////////////////////////////////////////// // SFEN serialization / deserialization ///////////////////////////////////////////////////////////////////////// /// Parses the given SFEN string and updates the game state. pub fn set_sfen(&mut self, sfen_str: &str) -> Result<(), SfenError> { let mut parts = sfen_str.split_whitespace(); // Build the initial position, all parts are required. parts .next() .ok_or(SfenError::MissingDataFields) .and_then(|s| self.parse_sfen_board(s))?; parts .next() .ok_or(SfenError::MissingDataFields) .and_then(|s| self.parse_sfen_stm(s))?; parts .next() .ok_or(SfenError::MissingDataFields) .and_then(|s| self.parse_sfen_hand(s))?; parts .next() .ok_or(SfenError::MissingDataFields) .and_then(|s| self.parse_sfen_ply(s))?; self.sfen_history.clear(); self.log_position(); // Make moves following the initial position, optional. if let Some("moves") = parts.next() { for m in parts { if let Some(m) = Move::from_sfen(m) { // Stop if any error occurrs. match self.make_move(m) { Ok(_) => { self.log_position(); } Err(_) => break, } } else { return Err(SfenError::IllegalMove); } } } Ok(()) } /// Converts the current state into SFEN formatted string. pub fn to_sfen(&self) -> String { if self.sfen_history.is_empty() { return self.generate_sfen(); } if self.move_history.is_empty() { return format!("{} {}", self.sfen_history.first().unwrap().0, self.ply); } let mut sfen = format!( "{} {} moves", &self.sfen_history.first().unwrap().0, self.ply - self.move_history.len() as u16 ); for m in self.move_history.iter() { let _ = write!(sfen, " {}", &m.to_sfen()); } sfen } fn parse_sfen_board(&mut self, s: &str) -> Result<(), SfenError> { let rows = s.split('/'); self.occupied_bb = Bitboard::empty(); self.color_bb = Default::default(); self.type_bb = Default::default(); for (i, row) in rows.enumerate() { if i >= 9 { return Err(SfenError::IllegalBoardState); } let mut j = 0; let mut is_promoted = false; for c in row.chars() { match c { '+' => { is_promoted = true; } n if n.is_ascii_digit() => { if let Some(n) = n.to_digit(10) { for _ in 0..n { if j >= 9 { return Err(SfenError::IllegalBoardState); } let sq = Square::new(8 - j, i as u8).unwrap(); self.set_piece(sq, None); j += 1; } } } s => match Piece::from_sfen(s) { Some(mut piece) => { if j >= 9 { return Err(SfenError::IllegalBoardState); } if is_promoted { if let Some(promoted) = piece.piece_type.promote() { piece.piece_type = promoted; } else { return Err(SfenError::IllegalPieceType); } } let sq = Square::new(8 - j, i as u8).unwrap(); self.set_piece(sq, Some(piece)); self.occupied_bb |= sq; self.color_bb[piece.color.index()] |= sq; self.type_bb[piece.piece_type.index()] |= sq; j += 1; is_promoted = false; } None => return Err(SfenError::IllegalPieceType), }, } } } Ok(()) } fn parse_sfen_stm(&mut self, s: &str) -> Result<(), SfenError> { self.side_to_move = match s { "b" => Color::Black, "w" => Color::White, _ => return Err(SfenError::IllegalSideToMove), }; Ok(()) } fn parse_sfen_hand(&mut self, s: &str) -> Result<(), SfenError> { if s == "-" { self.hand.clear(); return Ok(()); } let mut num_pieces: u8 = 0; for c in s.chars() { match c { n if n.is_ascii_digit() => { if let Some(n) = n.to_digit(10) { num_pieces = num_pieces * 10 + (n as u8); } } s => { match Piece::from_sfen(s) { Some(p) => self .hand .set(p, if num_pieces == 0 { 1 } else { num_pieces }), None => return Err(SfenError::IllegalPieceType), }; num_pieces = 0; } } } Ok(()) } fn parse_sfen_ply(&mut self, s: &str) -> Result<(), SfenError> { self.ply = s.parse()?; Ok(()) } fn generate_sfen(&self) -> String { let board = (0..9) .map(|row| { let mut s = String::new(); let mut num_spaces = 0; for file in (0..9).rev() { match *self.piece_at(Square::new(file, row).unwrap()) { Some(pc) => { if num_spaces > 0 { s.push_str(&num_spaces.to_string()); num_spaces = 0; } s.push_str(&pc.to_string()); } None => num_spaces += 1, } } if num_spaces > 0 { s.push_str(&num_spaces.to_string()); } s }) .join("/"); let color = if self.side_to_move == Color::Black { "b" } else { "w" }; let mut hand = [Color::Black, Color::White] .iter() .map(|c| { PieceType::iter() .filter(|pt| pt.is_hand_piece()) .map(|pt| { let pc = Piece { piece_type: pt, color: *c, }; let n = self.hand.get(pc); if n == 0 { "".to_string() } else if n == 1 { format!("{pc}") } else { format!("{n}{pc}") } }) .join("") }) .join(""); if hand.is_empty() { hand = "-".to_string(); } format!("{} {} {} {}", board, color, hand, self.ply) } } ///////////////////////////////////////////////////////////////////////////// // Trait implementations ///////////////////////////////////////////////////////////////////////////// impl Default for Position { fn default() -> Position { Position { side_to_move: Color::Black, board: PieceGrid([None; 81]), hand: Default::default(), ply: 1, move_history: Default::default(), sfen_history: Default::default(), occupied_bb: Default::default(), color_bb: Default::default(), type_bb: Default::default(), } } } impl fmt::Display for Position { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, " 9 8 7 6 5 4 3 2 1")?; writeln!(f, "+---+---+---+---+---+---+---+---+---+")?; for row in 0..9 { write!(f, "|")?; for file in (0..9).rev() { if let Some(ref piece) = *self.piece_at(Square::new(file, row).unwrap()) { write!(f, "{:>3}|", piece.to_string())?; } else { write!(f, " |")?; } } writeln!(f, " {}", (('a' as usize + row as usize) as u8) as char)?; writeln!(f, "+---+---+---+---+---+---+---+---+---+")?; } writeln!( f, "Side to move: {}", if self.side_to_move == Color::Black { "Black" } else { "White" } )?; let fmt_hand = |color: Color, f: &mut fmt::Formatter| -> fmt::Result { for pt in PieceType::iter().filter(|pt| pt.is_hand_piece()) { let pc = Piece { piece_type: pt, color, }; let n = self.hand.get(pc); if n > 0 { write!(f, "{pc}{n} ")?; } } Ok(()) }; write!(f, "Hand (Black): ")?; fmt_hand(Color::Black, f)?; writeln!(f)?; write!(f, "Hand (White): ")?; fmt_hand(Color::White, f)?; writeln!(f)?; write!(f, "Ply: {}", self.ply)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::square::consts::*; fn setup() { BBFactory::init(); } #[test] fn new() { setup(); let pos = Position::new(); for i in 0..9 { for j in 0..9 { let sq = Square::new(i, j).unwrap(); assert_eq!(None, *pos.piece_at(sq)); } } } #[test] fn in_check() { setup(); let test_cases = [ ( "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1", false, false, ), ("9/3r5/9/9/6B2/9/9/9/3K5 b P 1", true, false), ( "ln2r1knl/2gb1+Rg2/4Pp1p1/p1pp1sp1p/1N2pN1P1/2P2PP2/PP1G1S2R/1SG6/LK6L w 2PSp 1", false, true, ), ( "lnsg1gsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSG1GSNL b - 1", false, false, ), ]; let mut pos = Position::new(); for case in test_cases.iter() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert_eq!(case.1, pos.in_check(Color::Black)); assert_eq!(case.2, pos.in_check(Color::White)); } } #[test] fn find_king() { setup(); let test_cases = [ ( "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1", Some(SQ_5I), Some(SQ_5A), ), ("9/3r5/9/9/6B2/9/9/9/3K5 b P 1", Some(SQ_6I), None), ( "ln2r1knl/2gb1+Rg2/4Pp1p1/p1pp1sp1p/1N2pN1P1/2P2PP2/PP1G1S2R/1SG6/LK6L w 2PSp 1", Some(SQ_8I), Some(SQ_3A), ), ( "lnsg1gsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSG1GSNL b - 1", None, None, ), ]; let mut pos = Position::new(); for case in test_cases.iter() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert_eq!(case.1, pos.find_king(Color::Black)); assert_eq!(case.2, pos.find_king(Color::White)); } } #[test] fn player_bb() { setup(); let cases: &[(&str, &[Square], &[Square])] = &[ ( "R6gk/9/8p/9/4p4/9/9/8L/B8 b - 1", &[SQ_9A, SQ_1H, SQ_9I], &[SQ_2A, SQ_1A, SQ_1C, SQ_5E], ), ("9/3r5/9/9/6B2/9/9/9/3K5 b P 1", &[SQ_3E, SQ_6I], &[SQ_6B]), ]; let mut pos = Position::new(); for case in cases { pos.set_sfen(case.0).expect("faled to parse SFEN string"); let black = pos.player_bb(Color::Black); let white = pos.player_bb(Color::White); assert_eq!(case.1.len(), black.count() as usize); for sq in case.1 { assert!((black & *sq).is_any()); } assert_eq!(case.2.len(), white.count() as usize); for sq in case.2 { assert!((white & *sq).is_any()); } } } #[test] fn pinned_bb() { setup(); let cases: &[(&str, &[Square], &[Square])] = &[( "R6gk/9/8p/9/4p4/9/9/8L/B8 b - 1", &[], &[SQ_2A, SQ_1C, SQ_5E], )]; let mut pos = Position::new(); for case in cases { pos.set_sfen(case.0).expect("faled to parse SFEN string"); let black = pos.pinned_bb(Color::Black); let white = pos.pinned_bb(Color::White); assert_eq!(case.1.len(), black.count()); for sq in case.1 { assert!((&black & *sq).is_any()); } assert_eq!(case.2.len(), white.count()); for sq in case.2 { assert!((&white & *sq).is_any()); } } } #[test] fn move_candidates() { setup(); let mut pos = Position::new(); pos.set_sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1") .expect("failed to parse SFEN string"); let mut sum = 0; for sq in Square::iter() { let pc = pos.piece_at(sq); if let Some(pc) = *pc { if pc.color == pos.side_to_move() { sum += pos.move_candidates(sq, pc).count(); } } } assert_eq!(30, sum); } #[test] fn make_normal_move() { setup(); let base_sfen = "l6nl/5+P1gk/2np1S3/p1p4Pp/3P2Sp1/1PPb2P1P/P5GS1/R8/LN4bKL w GR5pnsg 1"; let test_cases = [ (SQ_2B, SQ_2C, false, true), (SQ_7C, SQ_6E, false, true), (SQ_3I, SQ_4H, true, true), (SQ_6F, SQ_9I, true, true), (SQ_2B, SQ_2C, false, true), (SQ_9C, SQ_9D, false, false), (SQ_9B, SQ_8B, false, false), (SQ_9B, SQ_9D, false, false), (SQ_2B, SQ_2C, true, false), ]; let mut pos = Position::new(); for case in test_cases.iter() { pos.set_sfen(base_sfen) .expect("failed to parse SFEN string"); assert_eq!(case.3, pos.make_normal_move(case.0, case.1, case.2).is_ok()); } // Leaving the checked king is illegal. pos.set_sfen("9/3r5/9/9/6B2/9/9/9/3K5 b P 1") .expect("failed to parse SFEN string"); assert!(pos.make_normal_move(SQ_6I, SQ_6H, false).is_err()); pos.set_sfen("9/3r5/9/9/6B2/9/9/9/3K5 b P 1") .expect("failed to parse SFEN string"); assert!(pos.make_normal_move(SQ_6I, SQ_7I, false).is_ok()); } #[test] fn make_drop_move() { setup(); let base_sfen = "l6nl/5+P1gk/2np1S3/p1p4Pp/3P2Sp1/1PPb2P1P/P5GS1/R8/LN4bKL w GR5pnsg 1"; let test_cases = [ (SQ_5E, PieceType::Pawn, true), (SQ_5E, PieceType::Rook, false), (SQ_9A, PieceType::Pawn, false), (SQ_6F, PieceType::Pawn, false), (SQ_9B, PieceType::Pawn, false), (SQ_5I, PieceType::Pawn, false), ]; let mut pos = Position::new(); for case in test_cases.iter() { pos.set_sfen(base_sfen) .expect("failed to parse SFEN string"); assert_eq!( case.2, pos.make_move(Move::Drop { to: case.0, piece_type: case.1, }) .is_ok() ); } } #[test] fn nifu() { setup(); let ng_cases = [( "ln1g5/1ks1g3l/1p2p1n2/p1pGs2rp/1P1N1ppp1/P1SB1P2P/1S1p1bPP1/LKG6/4R2NL \ w 2Pp 91", SQ_6C, )]; let ok_cases = [( "ln1g5/1ks1g3l/1p2p1n2/p1pGs2rp/1P1N1ppp1/P1SB1P2P/1S1+p1bPP1/LKG6/4R2NL \ w 2Pp 91", SQ_6C, )]; let mut pos = Position::new(); for (i, case) in ng_cases.iter().enumerate() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert_eq!( Some(MoveError::Nifu), pos.make_move(Move::Drop { to: case.1, piece_type: PieceType::Pawn, }) .err(), "failed at #{i}" ); } for (i, case) in ok_cases.iter().enumerate() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert!( pos.make_move(Move::Drop { to: case.1, piece_type: PieceType::Pawn, }) .is_ok(), "failed at #{i}" ); } } #[test] fn uchifuzume() { setup(); let ng_cases = [ ("9/9/7sp/6ppk/9/7G1/9/9/9 b P 1", SQ_1E), ("7nk/9/7S1/6b2/9/9/9/9/9 b P 1", SQ_1B), ("7nk/7g1/6BS1/9/9/9/9/9/9 b P 1", SQ_1B), ("R6gk/9/7S1/9/9/9/9/9/9 b P 1", SQ_1B), ]; let ok_cases = [ ("9/9/7pp/6psk/9/7G1/7N1/9/9 b P 1", SQ_1E), ("7nk/9/7Sg/6b2/9/9/9/9/9 b P 1", SQ_1B), ( "9/8p/3pG1gp1/2p2kl1N/3P1p1s1/lPP6/2SGBP3/PK1S2+p2/LN7 w RSL3Prbg2n4p 1", SQ_8G, ), ("7k1/5G2l/6B2/9/9/9/9/9/9 b NP 1", SQ_2B), ]; let mut pos = Position::new(); for (i, case) in ng_cases.iter().enumerate() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert_eq!( Some(MoveError::Uchifuzume), pos.make_move(Move::Drop { to: case.1, piece_type: PieceType::Pawn, }) .err(), "failed at #{i}" ); } for (i, case) in ok_cases.iter().enumerate() { pos.set_sfen(case.0).expect("failed to parse SFEN string"); assert!( pos.make_move(Move::Drop { to: case.1, piece_type: PieceType::Pawn, }) .is_ok(), "failed at #{i}" ); } } #[test] fn repetition() { setup(); let mut pos = Position::new(); pos.set_sfen("ln7/ks+R6/pp7/9/9/9/9/9/9 b Ss 1") .expect("failed to parse SFEN string"); for _ in 0..2 { assert!(pos.make_drop_move(SQ_7A, PieceType::Silver).is_ok()); assert!(pos.make_drop_move(SQ_7C, PieceType::Silver).is_ok()); assert!(pos.make_normal_move(SQ_7A, SQ_8B, true).is_ok()); assert!(pos.make_normal_move(SQ_7C, SQ_8B, false).is_ok()); } assert!(pos.make_drop_move(SQ_7A, PieceType::Silver).is_ok()); assert!(pos.make_drop_move(SQ_7C, PieceType::Silver).is_ok()); assert!(pos.make_normal_move(SQ_7A, SQ_8B, true).is_ok()); assert_eq!( Some(MoveError::Repetition), pos.make_normal_move(SQ_7C, SQ_8B, false).err() ); } #[test] fn percetual_check() { setup(); // Case 1. Starting from a check move. let mut pos = Position::new(); pos.set_sfen("8l/6+P2/6+Rpk/8p/9/7S1/9/9/9 b - 1") .expect("failed to parse SFEN string"); for _ in 0..2 { assert!(pos.make_normal_move(SQ_3C, SQ_2B, false).is_ok()); assert!(pos.make_normal_move(SQ_1C, SQ_2D, false).is_ok()); assert!(pos.make_normal_move(SQ_2B, SQ_3C, false).is_ok()); assert!(pos.make_normal_move(SQ_2D, SQ_1C, false).is_ok()); } assert!(pos.make_normal_move(SQ_3C, SQ_2B, false).is_ok()); assert!(pos.make_normal_move(SQ_1C, SQ_2D, false).is_ok()); assert!(pos.make_normal_move(SQ_2B, SQ_3C, false).is_ok()); assert_eq!( Some(MoveError::PerpetualCheckWin), pos.make_normal_move(SQ_2D, SQ_1C, false).err() ); // Case 2. Starting from an escape move. pos.set_sfen("6p1k/9/8+R/9/9/9/9/9/9 w - 1") .expect("failed to parse SFEN string"); for _ in 0..2 { assert!(pos.make_normal_move(SQ_1A, SQ_2A, false).is_ok()); assert!(pos.make_normal_move(SQ_1C, SQ_2C, false).is_ok()); assert!(pos.make_normal_move(SQ_2A, SQ_1A, false).is_ok()); assert!(pos.make_normal_move(SQ_2C, SQ_1C, false).is_ok()); } assert!(pos.make_normal_move(SQ_1A, SQ_2A, false).is_ok()); assert!(pos.make_normal_move(SQ_1C, SQ_2C, false).is_ok()); assert!(pos.make_normal_move(SQ_2A, SQ_1A, false).is_ok()); assert_eq!( Some(MoveError::PerpetualCheckLose), pos.make_normal_move(SQ_2C, SQ_1C, false).err() ); } #[test] fn unmake_move() { setup(); let mut pos = Position::new(); let base_sfen = "l6nl/4+p+P1gk/2n2S3/p1p4Pp/3P2Sp1/1PPb2P1P/4+P1GS1/R8/LN4bKL w RG5gsnp 1"; pos.set_sfen(base_sfen) .expect("failed to parse SFEN string"); let base_state = format!("{pos}"); println!("{base_state}"); let test_cases = [ Move::Drop { to: SQ_5E, piece_type: PieceType::Pawn, }, // No capture by unpromoted piece Move::Normal { from: SQ_6F, to: SQ_7G, promote: false, }, // No capture by promoting piece Move::Normal { from: SQ_6F, to: SQ_7G, promote: true, }, // No capture by promoted piece Move::Normal { from: SQ_5B, to: SQ_5A, promote: false, }, // Capture of unpromoted piece by unpromoted piece Move::Normal { from: SQ_6F, to: SQ_9I, promote: false, }, // Capture of unpromoted piece by promoting piece Move::Normal { from: SQ_6F, to: SQ_9I, promote: true, }, // Capture of unpromoted piece by promoted piece Move::Normal { from: SQ_5B, to: SQ_4C, promote: false, }, // Capture of promoted piece by unpromoted piece Move::Normal { from: SQ_6F, to: SQ_5G, promote: false, }, // Capture of promoted piece by promoting piece Move::Normal { from: SQ_6F, to: SQ_5G, promote: true, }, // Capture of promoted piece by promoted piece Move::Normal { from: SQ_5B, to: SQ_4B, promote: false, }, ]; for case in test_cases.iter() { pos.set_sfen(base_sfen) .expect("failed to parse SFEN string"); pos.make_move(*case) .unwrap_or_else(|_| panic!("failed to make a move: {case}")); pos.unmake_move() .unwrap_or_else(|_| panic!("failed to unmake a move: {case}")); assert_eq!( base_sfen, pos.to_sfen(), "{}", format!("sfen unmatch for {case}").as_str() ); assert_eq!( base_state, format!("{pos}"), "{}", format!("state unmatch for {case}").as_str() ); } } #[test] fn try_declare_winning() { setup(); let mut pos = Position::new(); pos.set_sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1") .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen("1K7/+NG+N+NGG3/P+S+P+P+PS3/9/7s1/9/+b+rppp+p+s1+p/3+p1+bk2/9 b R4L7Pgnp 1") .expect("failed to parse SFEN string"); assert!(pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen( "1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/3+b4P/4+p+p+bs1/+r1s4+lk/1g1g3+r1 w \ Gns2l11p 1", ) .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(pos.try_declare_winning(Color::White)); pos.set_sfen( "1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/3+b4P/4+p+p+bs1/+r1s4+lk/1g1g3+r1 b \ Gns2l11p 1", ) .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen( "1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/3+b4P/4+p+p+bs1/+r1s4+l1/1g1g3+r1 b \ Gns2l11p 1", ) .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen( "1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/1k1+b4P/4+p+p+bs1/+r1s4+l1/1g1g3+r1 b \ Gns2l11p 1", ) .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen( "1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/3+b4P/4+p+p+bs1/+r1s4+lk/1g1g3+rG w \ ns2l11p 1", ) .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); pos.set_sfen("1K6l/1+N7/+PG2+Ns1p1/2+N5p/6p2/3+b4P/5+p+bs1/+r1s4+lk/1g1g3+rG w ns2l12p 1") .expect("failed to parse SFEN string"); assert!(!pos.try_declare_winning(Color::Black)); assert!(!pos.try_declare_winning(Color::White)); } #[test] fn set_sfen_normal() { setup(); let mut pos = Position::new(); pos.set_sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1") .expect("failed to parse SFEN string"); let filled_squares = [ (0, 0, PieceType::Lance, Color::White), (1, 0, PieceType::Knight, Color::White), (2, 0, PieceType::Silver, Color::White), (3, 0, PieceType::Gold, Color::White), (4, 0, PieceType::King, Color::White), (5, 0, PieceType::Gold, Color::White), (6, 0, PieceType::Silver, Color::White), (7, 0, PieceType::Knight, Color::White), (8, 0, PieceType::Lance, Color::White), (7, 1, PieceType::Rook, Color::White), (1, 1, PieceType::Bishop, Color::White), (0, 2, PieceType::Pawn, Color::White), (1, 2, PieceType::Pawn, Color::White), (2, 2, PieceType::Pawn, Color::White), (3, 2, PieceType::Pawn, Color::White), (4, 2, PieceType::Pawn, Color::White), (5, 2, PieceType::Pawn, Color::White), (6, 2, PieceType::Pawn, Color::White), (7, 2, PieceType::Pawn, Color::White), (8, 2, PieceType::Pawn, Color::White), (0, 6, PieceType::Pawn, Color::Black), (1, 6, PieceType::Pawn, Color::Black), (2, 6, PieceType::Pawn, Color::Black), (3, 6, PieceType::Pawn, Color::Black), (4, 6, PieceType::Pawn, Color::Black), (5, 6, PieceType::Pawn, Color::Black), (6, 6, PieceType::Pawn, Color::Black), (7, 6, PieceType::Pawn, Color::Black), (8, 6, PieceType::Pawn, Color::Black), (7, 7, PieceType::Bishop, Color::Black), (1, 7, PieceType::Rook, Color::Black), (0, 8, PieceType::Lance, Color::Black), (1, 8, PieceType::Knight, Color::Black), (2, 8, PieceType::Silver, Color::Black), (3, 8, PieceType::Gold, Color::Black), (4, 8, PieceType::King, Color::Black), (5, 8, PieceType::Gold, Color::Black), (6, 8, PieceType::Silver, Color::Black), (7, 8, PieceType::Knight, Color::Black), (8, 8, PieceType::Lance, Color::Black), ]; let empty_squares = [ (0, 1, 1), (2, 1, 5), (8, 1, 1), (0, 3, 9), (0, 4, 9), (0, 5, 9), (0, 7, 1), (2, 7, 5), (8, 7, 1), ]; let hand_pieces = [ (PieceType::Pawn, 0), (PieceType::Lance, 0), (PieceType::Knight, 0), (PieceType::Silver, 0), (PieceType::Gold, 0), (PieceType::Rook, 0), (PieceType::Bishop, 0), ]; for case in filled_squares.iter() { let (file, row, pt, c) = *case; assert_eq!( Some(Piece { piece_type: pt, color: c, }), *pos.piece_at(Square::new(file, row).unwrap()) ); } for case in empty_squares.iter() { let (file, row, len) = *case; for i in file..(file + len) { assert_eq!(None, *pos.piece_at(Square::new(i, row).unwrap())); } } for case in hand_pieces.iter() { let (pt, n) = *case; assert_eq!( n, pos.hand(Piece { piece_type: pt, color: Color::Black, }) ); assert_eq!( n, pos.hand(Piece { piece_type: pt, color: Color::White, }) ); } assert_eq!(Color::Black, pos.side_to_move()); assert_eq!(1, pos.ply()); } #[test] fn to_sfen() { setup(); let test_cases = [ "7k1/9/7P1/9/9/9/9/9/9 b G2r2b3g4s4n4l17p 1", "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1", "lnsgk+Lpnl/1p5+B1/p1+Pps1ppp/9/9/9/P+r1PPpPPP/1R7/LNSGKGSN1 w BGP2p \ 1024", ]; let mut pos = Position::new(); for case in test_cases.iter() { pos.set_sfen(case).expect("failed to parse SFEN string"); assert_eq!(*case, pos.to_sfen()); } } #[test] fn set_sfen_custom() { setup(); let mut pos = Position::new(); pos.set_sfen("lnsgk+Lpnl/1p5+B1/p1+Pps1ppp/9/9/9/P+r1PPpPPP/1R7/LNSGKGSN1 w BGP2p 1024") .expect("failed to parse SFEN string"); let filled_squares = [ (8, 0, PieceType::Lance, Color::White), (7, 0, PieceType::Knight, Color::White), (6, 0, PieceType::Silver, Color::White), (5, 0, PieceType::Gold, Color::White), (4, 0, PieceType::King, Color::White), (3, 0, PieceType::ProLance, Color::Black), (2, 0, PieceType::Pawn, Color::White), (1, 0, PieceType::Knight, Color::White), (0, 0, PieceType::Lance, Color::White), (7, 1, PieceType::Pawn, Color::White), (1, 1, PieceType::ProBishop, Color::Black), (8, 2, PieceType::Pawn, Color::White), (6, 2, PieceType::ProPawn, Color::Black), (5, 2, PieceType::Pawn, Color::White), (4, 2, PieceType::Silver, Color::White), (2, 2, PieceType::Pawn, Color::White), (1, 2, PieceType::Pawn, Color::White), (0, 2, PieceType::Pawn, Color::White), (8, 6, PieceType::Pawn, Color::Black), (7, 6, PieceType::ProRook, Color::White), (5, 6, PieceType::Pawn, Color::Black), (4, 6, PieceType::Pawn, Color::Black), (3, 6, PieceType::Pawn, Color::White), (2, 6, PieceType::Pawn, Color::Black), (1, 6, PieceType::Pawn, Color::Black), (0, 6, PieceType::Pawn, Color::Black), (7, 7, PieceType::Rook, Color::Black), (8, 8, PieceType::Lance, Color::Black), (7, 8, PieceType::Knight, Color::Black), (6, 8, PieceType::Silver, Color::Black), (5, 8, PieceType::Gold, Color::Black), (4, 8, PieceType::King, Color::Black), (3, 8, PieceType::Gold, Color::Black), (2, 8, PieceType::Silver, Color::Black), (1, 8, PieceType::Knight, Color::Black), ]; let empty_squares = [ (0, 1, 1), (2, 1, 5), (8, 1, 1), (3, 2, 1), (7, 2, 1), (0, 3, 9), (0, 4, 9), (0, 5, 9), (6, 6, 1), (0, 7, 7), (8, 7, 1), (0, 8, 1), ]; let hand_pieces = [ ( Piece { piece_type: PieceType::Pawn, color: Color::Black, }, 1, ), ( Piece { piece_type: PieceType::Gold, color: Color::Black, }, 1, ), ( Piece { piece_type: PieceType::Bishop, color: Color::Black, }, 1, ), ( Piece { piece_type: PieceType::Pawn, color: Color::White, }, 2, ), ]; for case in filled_squares.iter() { let (file, row, pt, c) = *case; assert_eq!( Some(Piece { piece_type: pt, color: c, }), *pos.piece_at(Square::new(file, row).unwrap()) ); } for case in empty_squares.iter() { let (file, row, len) = *case; for i in file..(file + len) { assert_eq!(None, *pos.piece_at(Square::new(i, row).unwrap())); } } for case in hand_pieces.iter() { let (p, n) = *case; assert_eq!(n, pos.hand(p)); } assert_eq!(Color::White, pos.side_to_move()); assert_eq!(1024, pos.ply()); } }
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations. - Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments. - Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments. - Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design. - Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code. The extract: -- phpMyAdmin SQL Dump -- version 4.4.14 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Jul 05, 2018 at 04:28 PM -- Server version: 5.6.26 -- PHP Version: 5.6.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `cement` -- -- -------------------------------------------------------- -- -- Table structure for table `rmc` -- CREATE TABLE IF NOT EXISTS `rmc` ( `SL_NO` int(11) NOT NULL, `Category` varchar(250) NOT NULL, `Name_of_com` varchar(250) NOT NULL, `PO_UP` varchar(250) NOT NULL, `Name_of_des_maker` varchar(250) NOT NULL, `Position` varchar(250) NOT NULL, `Address` varchar(250) NOT NULL, `Mob_phn` varchar(250) NOT NULL, `Pro_Per` varchar(250) NOT NULL, `Mobile_Phn` varchar(250) NOT NULL, `district` varchar(250) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `rmc` -- INSERT INTO `rmc` (`SL_NO`, `Category`, `Name_of_com`, `PO_UP`, `Name_of_des_maker`, `Position`, `Address`, `Mob_phn`, `Pro_Per`, `Mobile_Phn`, `district`) VALUES (1, '9', 'uniliver', 'rin', 'Tanup', '6', 'Barisal', '01743647423', 'mim', '019xxxxxxx', 'barisal'), (2, '9', 'uniliver', 'rin', 'a', '6', 'c', 'z', 'mim', '5', 'barisal'), (3, 'jhfd', 'ghkm', 'nbas', 'm,vd,f', 'rhwie', 'iuyr4', 'klfjgk', 'trwe', 'uiteir', 'hwegj'), (4, 'd', 'gh', 'hg', 'a', 'y', 'c', '01743647423', 'mim', '5', 'barisal'); -- -- Indexes for dumped tables -- -- -- Indexes for table `rmc` -- ALTER TABLE `rmc` ADD PRIMARY KEY (`SL_NO`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `rmc` -- ALTER TABLE `rmc` MODIFY `SL_NO` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
sql
1
-- phpMyAdmin SQL Dump -- version 4.4.14 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Jul 05, 2018 at 04:28 PM -- Server version: 5.6.26 -- PHP Version: 5.6.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `cement` -- -- -------------------------------------------------------- -- -- Table structure for table `rmc` -- CREATE TABLE IF NOT EXISTS `rmc` ( `SL_NO` int(11) NOT NULL, `Category` varchar(250) NOT NULL, `Name_of_com` varchar(250) NOT NULL, `PO_UP` varchar(250) NOT NULL, `Name_of_des_maker` varchar(250) NOT NULL, `Position` varchar(250) NOT NULL, `Address` varchar(250) NOT NULL, `Mob_phn` varchar(250) NOT NULL, `Pro_Per` varchar(250) NOT NULL, `Mobile_Phn` varchar(250) NOT NULL, `district` varchar(250) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `rmc` -- INSERT INTO `rmc` (`SL_NO`, `Category`, `Name_of_com`, `PO_UP`, `Name_of_des_maker`, `Position`, `Address`, `Mob_phn`, `Pro_Per`, `Mobile_Phn`, `district`) VALUES (1, '9', 'uniliver', 'rin', 'Tanup', '6', 'Barisal', '01743647423', 'mim', '019xxxxxxx', 'barisal'), (2, '9', 'uniliver', 'rin', 'a', '6', 'c', 'z', 'mim', '5', 'barisal'), (3, 'jhfd', 'ghkm', 'nbas', 'm,vd,f', 'rhwie', 'iuyr4', 'klfjgk', 'trwe', 'uiteir', 'hwegj'), (4, 'd', 'gh', 'hg', 'a', 'y', 'c', '01743647423', 'mim', '5', 'barisal'); -- -- Indexes for dumped tables -- -- -- Indexes for table `rmc` -- ALTER TABLE `rmc` ADD PRIMARY KEY (`SL_NO`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `rmc` -- ALTER TABLE `rmc` MODIFY `SL_NO` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: const other = (s = '') => console.log(s + ' this comes from the other.js file'); const sumMe = (a, b) => { let result = a + b; return result; } export { other, sumMe } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
2
const other = (s = '') => console.log(s + ' this comes from the other.js file'); const sumMe = (a, b) => { let result = a + b; return result; } export { other, sumMe }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: class Player < ApplicationRecord attr_accessor :remember_token has_many :assignments has_many :boxes, through: :assignments, dependent: :destroy has_secure_password before_save { self.email = email.downcase } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :first_name, presence: true validates :password, presence: true, length: { minimum: 6 }, on: :create scope :active, -> { where(active: true) } scope :inactive, -> { where(active: false) } def self.new_token SecureRandom.urlsafe_base64 end # returns hash digest of given string def self.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def full_name "#{first_name} #{last_name}" end def remember self.remember_token = Player.new_token update_attribute(:remember_digest, Player.digest(remember_token)) end def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end def forget update_attribute(:remember_digest, nil) end def active? active end end After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
2
class Player < ApplicationRecord attr_accessor :remember_token has_many :assignments has_many :boxes, through: :assignments, dependent: :destroy has_secure_password before_save { self.email = email.downcase } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :first_name, presence: true validates :password, presence: true, length: { minimum: 6 }, on: :create scope :active, -> { where(active: true) } scope :inactive, -> { where(active: false) } def self.new_token SecureRandom.urlsafe_base64 end # returns hash digest of given string def self.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def full_name "#{first_name} #{last_name}" end def remember self.remember_token = Player.new_token update_attribute(:remember_digest, Player.digest(remember_token)) end def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end def forget update_attribute(:remember_digest, nil) end def active? active end end
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: //: Playground - noun: a place where people can play import UIKit import XCPlayground let swift_bg: [String] = ["すごい", "あつい", "いけてる", "ビビット", "くーる", "やばい", "なう", "おしゃんてぃ", "つよい", "ふが", "夏", "hoge", "きたー", "すいふと", "つよい", "すいふてぃ", "サマー", "祭り", "フェス", "hoge", "つよい", "つばめ", "たのしい"] class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .whiteColor() view.frame = CGRectMake(0, 0, 100, 80) } } extension ViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "Switビギナーズ倶楽部 \(swift_bg[indexPath.row])" return cell } } XCPlaygroundPage.currentPage.liveView = ViewController() After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
4
//: Playground - noun: a place where people can play import UIKit import XCPlayground let swift_bg: [String] = ["すごい", "あつい", "いけてる", "ビビット", "くーる", "やばい", "なう", "おしゃんてぃ", "つよい", "ふが", "夏", "hoge", "きたー", "すいふと", "つよい", "すいふてぃ", "サマー", "祭り", "フェス", "hoge", "つよい", "つばめ", "たのしい"] class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .whiteColor() view.frame = CGRectMake(0, 0, 100, 80) } } extension ViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "Switビギナーズ倶楽部 \(swift_bg[indexPath.row])" return cell } } XCPlaygroundPage.currentPage.liveView = ViewController()
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: /*------------------Server-Side------------------*/ /* - Catch the sent Input - generate UUID (This is the primary Key of the JSON) - save the UUID, Loc_ID & timestamp to GlobalDatabase.json - respond the key of the JSON (UUID) back to the client */ /*------------------Set-Up Server------------------*/ import {opine, serveStatic} from "./deps.ts"; import { opineCors } from "./deps.ts"; import {processData} from "./utils/manageDatabase.ts"; import {setStatus} from "./utils/manageStatus.ts"; import {checkRisk, updateRisk} from "./utils/manageRisk.ts"; const router = opine(); router.use(opineCors()) router.use(serveStatic(`${Deno.cwd()}/server/src/`)); //Forwards to a sample html site for debug purposes router.get('/', function (req, res) { updateRisk() const homeScreen = `${Deno.cwd()}/server/src/client.html` console.log(`Connected.`) res.sendFile(homeScreen) }); //Frontend sends data via localhost:3000/Tracer/:data → backend stores the date in MySql db → responds with TracerID and time router.get('/Tracer/:data', function (req, res) { //updateRisk(client) const scanData = JSON.parse(req.params.data); const storedScanData = processData(scanData); console.log(storedScanData); res.setStatus(201) res.json({"key": storedScanData.key, "time": storedScanData.data.time}); }); //receive list of ids, changes their status to 1 and changes all occurrences to risk = 1 router.get('/Report/:ids', function (req, res) { updateRisk() const riskIDs = JSON.parse(req.params.ids); console.log(riskIDs.id) setStatus(riskIDs.id) res.setStatus(201) res.json({"status": "success"}); }); //receive list of ids, check their risk value router.get('/RiskCheck/:ids', async function (req, res) { await updateRisk() const checkIDs = JSON.parse(req.params.ids); const riskStatus = await checkRisk(checkIDs.id) res.setStatus(201) res.json({"status": "success", "risk": riskStatus}); }); //deploy r After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
2
/*------------------Server-Side------------------*/ /* - Catch the sent Input - generate UUID (This is the primary Key of the JSON) - save the UUID, Loc_ID & timestamp to GlobalDatabase.json - respond the key of the JSON (UUID) back to the client */ /*------------------Set-Up Server------------------*/ import {opine, serveStatic} from "./deps.ts"; import { opineCors } from "./deps.ts"; import {processData} from "./utils/manageDatabase.ts"; import {setStatus} from "./utils/manageStatus.ts"; import {checkRisk, updateRisk} from "./utils/manageRisk.ts"; const router = opine(); router.use(opineCors()) router.use(serveStatic(`${Deno.cwd()}/server/src/`)); //Forwards to a sample html site for debug purposes router.get('/', function (req, res) { updateRisk() const homeScreen = `${Deno.cwd()}/server/src/client.html` console.log(`Connected.`) res.sendFile(homeScreen) }); //Frontend sends data via localhost:3000/Tracer/:data → backend stores the date in MySql db → responds with TracerID and time router.get('/Tracer/:data', function (req, res) { //updateRisk(client) const scanData = JSON.parse(req.params.data); const storedScanData = processData(scanData); console.log(storedScanData); res.setStatus(201) res.json({"key": storedScanData.key, "time": storedScanData.data.time}); }); //receive list of ids, changes their status to 1 and changes all occurrences to risk = 1 router.get('/Report/:ids', function (req, res) { updateRisk() const riskIDs = JSON.parse(req.params.ids); console.log(riskIDs.id) setStatus(riskIDs.id) res.setStatus(201) res.json({"status": "success"}); }); //receive list of ids, check their risk value router.get('/RiskCheck/:ids', async function (req, res) { await updateRisk() const checkIDs = JSON.parse(req.params.ids); const riskStatus = await checkRisk(checkIDs.id) res.setStatus(201) res.json({"status": "success", "risk": riskStatus}); }); //deploy router.listen(3000, function () { updateRisk() console.log('Tracer Server is listening on Port 3000!') });
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: use legion::*; use prefab_format::{EntityUuid, ComponentTypeUuid}; use std::collections::HashMap; use std::collections::HashSet; use legion_prefab::{ComponentRegistration, DiffSingleResult}; use crate::component_diffs::{ComponentDiff, EntityDiff, EntityDiffOp, WorldDiff}; use legion_prefab::CopyCloneImpl; use std::hash::BuildHasher; struct TransactionBuilderEntityInfo { entity_uuid: EntityUuid, entity: Entity, } #[derive(Default)] pub struct TransactionBuilder { entities: Vec<TransactionBuilderEntityInfo>, } impl TransactionBuilder { pub fn new() -> Self { Self::default() } pub fn add_entity( mut self, entity: Entity, entity_uuid: EntityUuid, ) -> Self { self.entities.push(TransactionBuilderEntityInfo { entity, entity_uuid, }); self } pub fn begin<S: BuildHasher>( self, src_world: &World, mut clone_impl: CopyCloneImpl<S>, ) -> Transaction { let mut before_world = World::default(); let mut after_world = World::default(); let mut uuid_to_entities = HashMap::new(); for entity_info in self.entities { let before_entity = before_world.clone_from_single(&src_world, entity_info.entity, &mut clone_impl); let after_entity = after_world.clone_from_single(&src_world, entity_info.entity, &mut clone_impl); uuid_to_entities.insert( entity_info.entity_uuid, TransactionEntityInfo { before_entity: Some(before_entity), after_entity: Some(after_entity), }, ); } Transaction { before_world, after_world, uuid_to_entities, } } } //TODO: Remove this if possible pub struct TransactionEntityInfo { before_entity: Option<Entity>, after_entity: Option<Entity>, } impl Transacti After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
2
use legion::*; use prefab_format::{EntityUuid, ComponentTypeUuid}; use std::collections::HashMap; use std::collections::HashSet; use legion_prefab::{ComponentRegistration, DiffSingleResult}; use crate::component_diffs::{ComponentDiff, EntityDiff, EntityDiffOp, WorldDiff}; use legion_prefab::CopyCloneImpl; use std::hash::BuildHasher; struct TransactionBuilderEntityInfo { entity_uuid: EntityUuid, entity: Entity, } #[derive(Default)] pub struct TransactionBuilder { entities: Vec<TransactionBuilderEntityInfo>, } impl TransactionBuilder { pub fn new() -> Self { Self::default() } pub fn add_entity( mut self, entity: Entity, entity_uuid: EntityUuid, ) -> Self { self.entities.push(TransactionBuilderEntityInfo { entity, entity_uuid, }); self } pub fn begin<S: BuildHasher>( self, src_world: &World, mut clone_impl: CopyCloneImpl<S>, ) -> Transaction { let mut before_world = World::default(); let mut after_world = World::default(); let mut uuid_to_entities = HashMap::new(); for entity_info in self.entities { let before_entity = before_world.clone_from_single(&src_world, entity_info.entity, &mut clone_impl); let after_entity = after_world.clone_from_single(&src_world, entity_info.entity, &mut clone_impl); uuid_to_entities.insert( entity_info.entity_uuid, TransactionEntityInfo { before_entity: Some(before_entity), after_entity: Some(after_entity), }, ); } Transaction { before_world, after_world, uuid_to_entities, } } } //TODO: Remove this if possible pub struct TransactionEntityInfo { before_entity: Option<Entity>, after_entity: Option<Entity>, } impl TransactionEntityInfo { pub fn new( before_entity: Option<Entity>, after_entity: Option<Entity>, ) -> Self { TransactionEntityInfo { before_entity, after_entity, } } pub fn before_entity(&self) -> Option<Entity> { self.before_entity } pub fn after_entity(&self) -> Option<Entity> { self.after_entity } } pub struct Transaction { // This is the snapshot of the world when the transaction starts before_world: legion::world::World, // This is the world that a downstream caller can manipulate. We will diff the data here against // the before_world to produce diffs after_world: legion::world::World, // All known entities throughout the transaction uuid_to_entities: HashMap<EntityUuid, TransactionEntityInfo>, } #[derive(Clone)] pub struct TransactionDiffs { apply_diff: WorldDiff, revert_diff: WorldDiff, } impl TransactionDiffs { pub fn new( apply_diff: WorldDiff, revert_diff: WorldDiff, ) -> Self { TransactionDiffs { apply_diff, revert_diff, } } pub fn apply_diff(&self) -> &WorldDiff { &self.apply_diff } pub fn revert_diff(&self) -> &WorldDiff { &self.revert_diff } pub fn reverse(&mut self) { std::mem::swap(&mut self.apply_diff, &mut self.revert_diff); } } impl Transaction { pub fn world(&self) -> &World { &self.after_world } pub fn world_mut(&mut self) -> &mut World { &mut self.after_world } pub fn uuid_to_entity( &self, uuid: EntityUuid, ) -> Option<Entity> { self.uuid_to_entities[&uuid].after_entity() } pub fn create_transaction_diffs<S: BuildHasher>( &mut self, registered_components: &HashMap<ComponentTypeUuid, ComponentRegistration, S>, ) -> TransactionDiffs { log::trace!("create diffs for {} entities", self.uuid_to_entities.len()); // These will contain the instructions to add/remove entities let mut apply_entity_diffs = vec![]; let mut revert_entity_diffs = vec![]; // Find the entities that have been deleted let mut preexisting_after_entities = HashSet::new(); let mut removed_entity_uuids = HashSet::new(); for (entity_uuid, entity_info) in &self.uuid_to_entities { if let Some(after_entity) = entity_info.after_entity { if !self.after_world.contains(after_entity) { removed_entity_uuids.insert(*entity_uuid); revert_entity_diffs.push(EntityDiff::new(*entity_uuid, EntityDiffOp::Add)); apply_entity_diffs.push(EntityDiff::new(*entity_uuid, EntityDiffOp::Remove)); } preexisting_after_entities.insert(after_entity); } } let mut all = Entity::query(); for after_entity in all.iter(&self.after_world) { if !preexisting_after_entities.contains(&after_entity) { let new_entity_uuid = uuid::Uuid::new_v4(); apply_entity_diffs.push(EntityDiff::new( *new_entity_uuid.as_bytes(), EntityDiffOp::Add, )); revert_entity_diffs.push(EntityDiff::new( *new_entity_uuid.as_bytes(), EntityDiffOp::Remove, )); // Add new entities now so that the component diffing code will pick the new entity // and capture component data for it self.uuid_to_entities.insert( *new_entity_uuid.as_bytes(), TransactionEntityInfo::new(None, Some(*after_entity)), ); } } // We detect which entities are new and old: // - Deleted entities we could skip in the below code since the component delete diffs are // redundant, but we need to generate component adds in the undo world diff // - New entities also go through the below code to create component diffs. However this is // suboptimal since adding the diffs could require multiple entity moves between // archetypes. // - Modified entities can feed into the below code to generate component add/remove/change // diffs. This is still a little suboptimal if multiple components are added, but it's // likely not the common case and something we can try to do something about later let mut apply_component_diffs = vec![]; let mut revert_component_diffs = vec![]; // Iterate the entities in the selection world and prefab world and genereate diffs for // each component type. for (entity_uuid, entity_info) in &self.uuid_to_entities { // Do diffs for each component type for (component_type, registration) in registered_components { let mut apply_data = vec![]; let mut apply_ser = bincode::Serializer::new( &mut apply_data, bincode::config::DefaultOptions::new(), ); let mut apply_ser_erased = erased_serde::Serializer::erase(&mut apply_ser); let apply_result = registration.diff_single( &mut apply_ser_erased, &self.before_world, entity_info.before_entity, &self.after_world, entity_info.after_entity, ); if apply_result != DiffSingleResult::NoChange { let mut revert_data = vec![]; let mut revert_ser = bincode::Serializer::new( &mut revert_data, bincode::config::DefaultOptions::new(), ); let mut revert_ser_erased = erased_serde::Serializer::erase(&mut revert_ser); let revert_result = registration.diff_single( &mut revert_ser_erased, &self.after_world, entity_info.after_entity, &self.before_world, entity_info.before_entity, ); apply_component_diffs.push( ComponentDiff::new_from_diff_single_result( *entity_uuid, *component_type, apply_result, apply_data, ) .unwrap(), ); revert_component_diffs.push( ComponentDiff::new_from_diff_single_result( *entity_uuid, *component_type, revert_result, revert_data, ) .unwrap(), ); } } } // We delayed removing entities from uuid_to_entities because we still want to generate add // entries for the undo step for removed_entity_uuid in &removed_entity_uuids { self.uuid_to_entities.remove(removed_entity_uuid); } let apply_diff = WorldDiff::new(apply_entity_diffs, apply_component_diffs); let revert_diff = WorldDiff::new(revert_entity_diffs, revert_component_diffs); TransactionDiffs::new(apply_diff, revert_diff) } }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: class SLViewController < UIViewController attr_accessor :textNoteOrLink attr_accessor :buttonLoginLogout def viewDidLoad super @textNoteOrLink = UILabel.alloc.initWithFrame([[0, 50], [view.frame.size.width, 150]]) view.addSubview(@textNoteOrLink) @buttonLoginLogout = UIButton.buttonWithType(UIButtonTypeRoundedRect) @buttonLoginLogout.setTitle('Log in', forState:UIControlStateNormal) @buttonLoginLogout.addTarget(self, action:'buttonClickHandler', forControlEvents:UIControlEventTouchUpInside) @buttonLoginLogout.frame = [[view.frame.size.width / 2 - 40, 220], [80, 40]] view.addSubview(@buttonLoginLogout) appDelegate = UIApplication.sharedApplication.delegate if appDelegate.session.nil? # create a fresh session object appDelegate.session = FBSession.alloc.init end self.updateView if !appDelegate.session.isOpen # if we don't have a cached token, a call to open here would cause UX for login to # occur; we don't want that to happen unless the user clicks the login button, and so # we check here to make sure we have a token before calling open if appDelegate.session.state == FBSessionStateCreatedTokenLoaded # even though we had a cached token, we need to login to make the session usable appDelegate.session.openWithCompletionHandler(lambda { |session, status, error| # we recurse here, in order to update buttons and labels self.updateView }) end end self end def updateView # get the app delegate, so that we can reference the session property appDelegate = UIApplication.sharedApplication.delegate if appDelegate.session.isOpen # valid account UI is shown whenever the session is open self.buttonLoginLogout.setTitle("Log out", forState:UIControlStateNormal) self.textNoteOrLink.setText("https://graph.facebook.com/me/friends?access_token=#{appDelegate.session.accessTokenData.accessToken}") After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
0
class SLViewController < UIViewController attr_accessor :textNoteOrLink attr_accessor :buttonLoginLogout def viewDidLoad super @textNoteOrLink = UILabel.alloc.initWithFrame([[0, 50], [view.frame.size.width, 150]]) view.addSubview(@textNoteOrLink) @buttonLoginLogout = UIButton.buttonWithType(UIButtonTypeRoundedRect) @buttonLoginLogout.setTitle('Log in', forState:UIControlStateNormal) @buttonLoginLogout.addTarget(self, action:'buttonClickHandler', forControlEvents:UIControlEventTouchUpInside) @buttonLoginLogout.frame = [[view.frame.size.width / 2 - 40, 220], [80, 40]] view.addSubview(@buttonLoginLogout) appDelegate = UIApplication.sharedApplication.delegate if appDelegate.session.nil? # create a fresh session object appDelegate.session = FBSession.alloc.init end self.updateView if !appDelegate.session.isOpen # if we don't have a cached token, a call to open here would cause UX for login to # occur; we don't want that to happen unless the user clicks the login button, and so # we check here to make sure we have a token before calling open if appDelegate.session.state == FBSessionStateCreatedTokenLoaded # even though we had a cached token, we need to login to make the session usable appDelegate.session.openWithCompletionHandler(lambda { |session, status, error| # we recurse here, in order to update buttons and labels self.updateView }) end end self end def updateView # get the app delegate, so that we can reference the session property appDelegate = UIApplication.sharedApplication.delegate if appDelegate.session.isOpen # valid account UI is shown whenever the session is open self.buttonLoginLogout.setTitle("Log out", forState:UIControlStateNormal) self.textNoteOrLink.setText("https://graph.facebook.com/me/friends?access_token=#{appDelegate.session.accessTokenData.accessToken}") else # login-needed account UI is shown whenever the session is closed self.buttonLoginLogout.setTitle("Log in", forState:UIControlStateNormal) self.textNoteOrLink.setText("Login to create a link to fetch account data") end end def buttonClickHandler # get the app delegate so that we can access the session property appDelegate = UIApplication.sharedApplication.delegate # this button's job is to flip-flop the session from open to closed if appDelegate.session.isOpen # if a user logs out explicitly, we delete any cached token information, and next # time they run the applicaiton they will be presented with log in UX again; most # users will simply close the app or switch away, without logging out; this will # cause the implicit cached-token login to occur on next launch of the application appDelegate.session.closeAndClearTokenInformation else if appDelegate.session.state != FBSessionStateCreated # Create a new, logged out session. appDelegate.session = FBSession.alloc.init else # if the session isn't open, let's open it now and present the login UX to the user appDelegate.session.openWithCompletionHandler(lambda { |session, status, error| # and here we make sure to update our UX according to the new session state self.updateView }) end end end end
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: declare module "usuals" { export const numberFunctions: any; export const stringFunctions: any; export const objectFunctions: any; export const linkedListFunctions: any; export const arrayFunctions: any; } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
1
declare module "usuals" { export const numberFunctions: any; export const stringFunctions: any; export const objectFunctions: any; export const linkedListFunctions: any; export const arrayFunctions: any; }
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: # CProjectsCollection A collection of my c practices and projects After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
2
# CProjectsCollection A collection of my c practices and projects
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: use hyper::{header::CONTENT_TYPE, Body, Request, Response, Server, StatusCode}; // Import the routerify prelude traits. use routerify::prelude::*; // Import routerify types. use routerify::{Middleware, Router, RouterService}; use std::{convert::Infallible, net::SocketAddr}; // Import the multer types. use multer::Multipart; // A handler to handle file upload at `/upload` path. async fn file_upload_handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { // Extract the `multipart/form-data` boundary from the headers. let boundary = req .headers() .get(CONTENT_TYPE) .and_then(|ct| ct.to_str().ok()) .and_then(|ct| multer::parse_boundary(ct).ok()); // Send `BAD_REQUEST` status if the content-type is not multipart/form-data. if boundary.is_none() { return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) .body(Body::from("BAD REQUEST")) .unwrap()); } // Process the multipart e.g. you can store them in files. if let Err(err) = process_multipart(req.into_body(), boundary.unwrap()).await { return Ok(Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(Body::from(format!("INTERNAL SERVER ERROR: {}", err))) .unwrap()); } Ok(Response::new(Body::from("Success"))) } // Process the request body as multipart/form-data. async fn process_multipart(body: Body, boundary: String) -> multer::Result<()> { // Create a Multipart instance from the request body. let mut multipart = Multipart::new(body, boundary); // Iterate over the fields, `next_field` method will return the next field if available. while let Some(mut field) = multipart.next_field().await? { // Get the field name. let name = field.name(); // Get the field's filename if provided in "Content-Disposition" header. let file_name = field.file_name(); // Get the "Content-Type" heade After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
4
use hyper::{header::CONTENT_TYPE, Body, Request, Response, Server, StatusCode}; // Import the routerify prelude traits. use routerify::prelude::*; // Import routerify types. use routerify::{Middleware, Router, RouterService}; use std::{convert::Infallible, net::SocketAddr}; // Import the multer types. use multer::Multipart; // A handler to handle file upload at `/upload` path. async fn file_upload_handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { // Extract the `multipart/form-data` boundary from the headers. let boundary = req .headers() .get(CONTENT_TYPE) .and_then(|ct| ct.to_str().ok()) .and_then(|ct| multer::parse_boundary(ct).ok()); // Send `BAD_REQUEST` status if the content-type is not multipart/form-data. if boundary.is_none() { return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) .body(Body::from("BAD REQUEST")) .unwrap()); } // Process the multipart e.g. you can store them in files. if let Err(err) = process_multipart(req.into_body(), boundary.unwrap()).await { return Ok(Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(Body::from(format!("INTERNAL SERVER ERROR: {}", err))) .unwrap()); } Ok(Response::new(Body::from("Success"))) } // Process the request body as multipart/form-data. async fn process_multipart(body: Body, boundary: String) -> multer::Result<()> { // Create a Multipart instance from the request body. let mut multipart = Multipart::new(body, boundary); // Iterate over the fields, `next_field` method will return the next field if available. while let Some(mut field) = multipart.next_field().await? { // Get the field name. let name = field.name(); // Get the field's filename if provided in "Content-Disposition" header. let file_name = field.file_name(); // Get the "Content-Type" header as `mime::Mime` type. let content_type = field.content_type(); println!( "Name: {:?}, FileName: {:?}, Content-Type: {:?}", name, file_name, content_type ); // Process the field data chunks e.g. store them in a file. let mut field_bytes_len = 0; while let Some(field_chunk) = field.chunk().await? { // Do something with field chunk. field_bytes_len += field_chunk.len(); } println!("Field Bytes Length: {:?}", field_bytes_len); } Ok(()) } // A routerify middleware which logs an http request. async fn logger(req: Request<Body>) -> Result<Request<Body>, Infallible> { println!("{} {} {}", req.remote_addr(), req.method(), req.uri().path()); Ok(req) } // Create a `Router<Body, Infallible>` for response body type `hyper::Body` and for handler error type `Infallible`. fn router() -> Router<Body, Infallible> { // Create a router and specify the logger middleware and the handlers. // Here, "Middleware::pre" means we're adding a pre middleware which will be executed // before any route handlers. Router::builder() .middleware(Middleware::pre(logger)) .post("/upload", file_upload_handler) .build() .unwrap() } #[tokio::main] async fn main() { let router = router(); // Create a Service from the router above to handle incoming requests. let service = RouterService::new(router).unwrap(); // The address on which the server will be listening. let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); // Create a server by passing the created service to `.serve` method. let server = Server::bind(&addr).serve(service); println!("App is running on: {}", addr); if let Err(err) = server.await { eprintln!("Server error: {}", err); } }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: class Chkbox < ActiveRecord::Base end After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
1
class Chkbox < ActiveRecord::Base end
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package org.wit.nurse.activities import android.content.Intent import android.media.Image import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.textfield.TextInputEditText import kotlinx.android.synthetic.main.activity_nurse.* import kotlinx.android.synthetic.main.card_nurse.* import kotlinx.android.synthetic.main.activity_nurse.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.jetbrains.anko.intentFor import org.jetbrains.anko.toast import org.wit.nurse.models.NurseModel import org.wit.nurse.R import org.wit.nurse.helpers.readImage import org.wit.nurse.helpers.readImageFromPath import org.wit.nurse.helpers.showImagePicker import org.wit.nurse.main.MainApp class NurseActivity : AppCompatActivity(), AnkoLogger { var nurse = NurseModel() lateinit var app : MainApp val IMAGE_REQUEST = 1 val LOCATION_REQUEST = 2 var edit = false private lateinit var toolbarAdd: Toolbar private lateinit var nurseNameEditText: TextInputEditText private lateinit var descriptionEditText: TextInputEditText private lateinit var salaryEditText: TextInputEditText private lateinit var chooseImageButton: Button private lateinit var nurseImageView: ImageView private lateinit var nurseSalaryButton: Button private lateinit var addButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nurse) app = application as MainApp nurseNameEditText = findViewById(R.id.nurseNameEditText) descriptionEditText = findViewById(R.id.descriptionEditText) salaryEditText = findViewById(R.id.salaryEditText) chooseImageButton = findViewById( After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
2
package org.wit.nurse.activities import android.content.Intent import android.media.Image import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.textfield.TextInputEditText import kotlinx.android.synthetic.main.activity_nurse.* import kotlinx.android.synthetic.main.card_nurse.* import kotlinx.android.synthetic.main.activity_nurse.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.jetbrains.anko.intentFor import org.jetbrains.anko.toast import org.wit.nurse.models.NurseModel import org.wit.nurse.R import org.wit.nurse.helpers.readImage import org.wit.nurse.helpers.readImageFromPath import org.wit.nurse.helpers.showImagePicker import org.wit.nurse.main.MainApp class NurseActivity : AppCompatActivity(), AnkoLogger { var nurse = NurseModel() lateinit var app : MainApp val IMAGE_REQUEST = 1 val LOCATION_REQUEST = 2 var edit = false private lateinit var toolbarAdd: Toolbar private lateinit var nurseNameEditText: TextInputEditText private lateinit var descriptionEditText: TextInputEditText private lateinit var salaryEditText: TextInputEditText private lateinit var chooseImageButton: Button private lateinit var nurseImageView: ImageView private lateinit var nurseSalaryButton: Button private lateinit var addButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nurse) app = application as MainApp nurseNameEditText = findViewById(R.id.nurseNameEditText) descriptionEditText = findViewById(R.id.descriptionEditText) salaryEditText = findViewById(R.id.salaryEditText) chooseImageButton = findViewById(R.id.chooseImageButton) nurseImageView = findViewById(R.id.nurseImageView) nurseSalaryButton = findViewById(R.id.nurseSalaryButton) addButton = findViewById(R.id.addButton) toolbarAdd = findViewById(R.id.toolbarAdd) setSupportActionBar(toolbarAdd) if (intent.hasExtra("nurse_edit")) { edit = true nurse = intent.extras.getParcelable<NurseModel>("nurse_edit") nurseNameEditText.setText(nurse.name) salaryEditText.setText(nurse.salary.toString()) if(nurse.imageName.isNotEmpty()) { nurseImageView.setImageBitmap(readImageFromPath(this, nurse.imageName)) } else { chooseImageButton.setText(R.string.change_nurse_image) } addButton.setText(R.string.save_nurse) } addButton.setOnClickListener() { nurse.name = nurseName.text.toString() nurse.salary = salaryEditText.text.toString().toInt() if (nurse.name.isEmpty()) { toast(R.string.enter_nurse_name) } else { if (edit) { app.nurses.update(nurse.copy()) } else { app.nurses.create(nurse.copy()) } } info("add Button Pressed: $nurseName") setResult(AppCompatActivity.RESULT_OK) finish() } chooseImageButton.setOnClickListener { showImagePicker(this, IMAGE_REQUEST) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_nurse, menu) if (edit && menu != null) menu.getItem(0).setVisible(true) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.item_delete -> { app.nurses.delete(nurse) finish() } R.id.item_cancel -> { finish() } } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { IMAGE_REQUEST -> { if (data != null) { // nurse.image = data.getData().toString() // placemarkImage.setImageBitmap(readImage(this, resultCode, data)) chooseImageButton.setText(R.string.change_nurse_image) } } } } }
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php namespace Echoyl\Sa\Services\dev\utils; use Illuminate\Support\Arr; class FormItem { var $data = false; var $config; var $schema; var $relation; var $model; var $readonly = false; var $menus; var $form_type; var $models; var $props;//config中的props; 属性集中到这个字段中 public function __construct($config,$model,$menus,$models) { $this->config = $config; $this->menus = $menus; $this->models = $models; $this->model = $model; $key = $config['key']; $props = $config['props']??''; $this->props = $props; if(isset($props['dataIndex']) && $props['dataIndex']) { $key = $props['dataIndex']; } if(in_array($key,['id','parent_id','created_at_s','displayorder'])) { $this->data = $key; return; } $columns = json_decode($model['columns'],true); $columns[] = [ 'name'=>'created_at', 'title'=>'创建时间', 'form_type'=>'datetime' ]; $columns[] = [ 'name'=>'updated_at', 'title'=>'更新时间', 'form_type'=>'datetime' ]; $schema = Utils::arrGet($columns,'name',$key); $this->schema = $schema; $relation = Utils::arrGet($model['relations'],$schema?'local_key':'name',Utils::uncamelize($key)); $this->relation = $relation; if(!$schema && !$relation) { return; } $p_title = $props['title']??''; $title = $config['title']??''; $title = $p_title?:$title; $fieldProps = $props['fieldProps']??''; $formItemProps = $props['formItemProps']??''; //$title = $config['title']??''; $readonly = $config['readonly']??''; $hidden = $config['hidden']??'';//是否隐藏 $set_label = $config['label']??''; $required = $config['required']??''; $placeholder = $config['placeholder']??''; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php namespace Echoyl\Sa\Services\dev\utils; use Illuminate\Support\Arr; class FormItem { var $data = false; var $config; var $schema; var $relation; var $model; var $readonly = false; var $menus; var $form_type; var $models; var $props;//config中的props; 属性集中到这个字段中 public function __construct($config,$model,$menus,$models) { $this->config = $config; $this->menus = $menus; $this->models = $models; $this->model = $model; $key = $config['key']; $props = $config['props']??''; $this->props = $props; if(isset($props['dataIndex']) && $props['dataIndex']) { $key = $props['dataIndex']; } if(in_array($key,['id','parent_id','created_at_s','displayorder'])) { $this->data = $key; return; } $columns = json_decode($model['columns'],true); $columns[] = [ 'name'=>'created_at', 'title'=>'创建时间', 'form_type'=>'datetime' ]; $columns[] = [ 'name'=>'updated_at', 'title'=>'更新时间', 'form_type'=>'datetime' ]; $schema = Utils::arrGet($columns,'name',$key); $this->schema = $schema; $relation = Utils::arrGet($model['relations'],$schema?'local_key':'name',Utils::uncamelize($key)); $this->relation = $relation; if(!$schema && !$relation) { return; } $p_title = $props['title']??''; $title = $config['title']??''; $title = $p_title?:$title; $fieldProps = $props['fieldProps']??''; $formItemProps = $props['formItemProps']??''; //$title = $config['title']??''; $readonly = $config['readonly']??''; $hidden = $config['hidden']??'';//是否隐藏 $set_label = $config['label']??''; $required = $config['required']??''; $placeholder = $config['placeholder']??''; //$extra = $config['name']??''; $d = ['dataIndex'=>$key,'title'=>$title?:($schema?$schema['title']:$relation['title'])]; if($readonly) { $d['readonly'] = true; } $this->readonly = $readonly; $form_type = $config['type']??''; if($form_type) { $d['valueType'] = $form_type; $this->form_type = $form_type; }else { $form_type = $schema['form_type']??''; $this->form_type = $form_type; if(isset(Utils::$value_type_map[$form_type])) { $form_type = Utils::$value_type_map[$form_type]; $d['valueType'] = $form_type; } } if($relation && $set_label) { //如果有关联数据 并且设置了读取lable字段名称 $key = [Utils::uncamelize($relation['name'])]; $key = array_merge($key,explode('.',$set_label)); $d['dataIndex'] = $key; } $_formItemProps = []; if($required) { $_formItemProps['rules'] = [ [ "required"=>true, ] ]; } if($hidden) { $_formItemProps['hidden'] = true; } if(!empty($_formItemProps)) { $d['formItemProps'] = $_formItemProps; } $this->data = $d; if($form_type && method_exists(self::class,$form_type)) { $this->$form_type(); } if($placeholder) { if(isset($this->data['fieldProps'])) { $this->data['fieldProps']['placeholder'] = $placeholder; }else { $this->data['fieldProps'] = ['placeholder'=>$placeholder]; } } if($fieldProps && !is_string($fieldProps)) { if(isset($this->data['fieldProps'])) { $this->data['fieldProps'] = array_merge($fieldProps,$this->data['fieldProps']); }else { $this->data['fieldProps'] = $fieldProps; } } if($formItemProps && !is_string($formItemProps)) { if(isset($this->data['formItemProps'])) { $this->data['formItemProps'] = array_merge($formItemProps,$this->data['formItemProps']); }else { $this->data['formItemProps'] = $formItemProps; } } if(isset($props['tooltip'])) { $this->data['tooltip'] = $props['tooltip']; } if(isset($props['outside'])) { $this->data = array_merge($this->data,$props['outside']); } return; } /** * 自定义列 * 将items 的值传入fieldProps * * @return void */ public function customerColumn() { $props = $this->props; if(!$props || !isset($props['items']) || !$props['items'])return; $items = $props['items']; //检测是否有modalTable 有的话通过关联数据设置属性值 foreach($items as $key=>$item) { $action = Arr::get($item,'action'); if($action == 'modalTable') { $fieldProps = []; $model = Arr::get($item,'modal.model'); $relation = Utils::arrGet($this->model['relations'],'name',Utils::uncamelize($model)); if($relation['foreign_model']['menu']) { $path = array_reverse(Utils::getPath($relation['foreign_model']['menu'],$this->menus,'path')); $fieldProps['path'] = implode('/',$path); $fieldProps['foreign_key'] = $relation['foreign_key']; $fieldProps['local_key'] = $relation['local_key']; $fieldProps['name'] = $relation['title']; $item['fieldProps'] = $fieldProps; } $items[$key] = $item; } } $this->data['readonly'] = true; $this->data['fieldProps'] = ['items'=>$items]; return; } public function saFormTable() { $fieldProps = []; $d = $this->data; $relation = $this->relation; $d['readonly'] = true; if($this->readonly) { $fieldProps['readonly'] = true; } //如果是saFormTable 表单中的table 需要读取该关联模型所对应的第一个菜单的所形成的地址,这样组件可以在页面中根据这个path获取该页面的配置参数信息 if($relation && $relation['foreign_model'] && $relation['foreign_model']['menu']) { $path = array_reverse(Utils::getPath($relation['foreign_model']['menu'],$this->menus,'path')); $fieldProps['path'] = implode('/',$path); $fieldProps['foreign_key'] = $relation['foreign_key']; $fieldProps['local_key'] = $relation['local_key']; $fieldProps['name'] = $d['title']; unset($d['title']); } if(!empty($fieldProps)) { $d['fieldProps'] = $fieldProps; } $this->data = $d; return; } /** * 弹出层table选择器 * 多选数据结构必须是1对多 * 单选 1对1 * @return void */ public function modalSelect() { $d = $this->data; $relation = $this->relation; if($this->readonly) { //unset($d['valueType']); //$d['dataIndex'] = [$relation['name'],$label]; }else { $d['fieldProps'] = []; $fieldProps = $this->props['fieldProps']??''; $set_url = $fieldProps['url']??''; //如果没有自定义url 才自动查找菜单路径 if($relation && $relation['foreign_model']) { //需要找到该关联所关联到哪个菜单下面 读取出后台路由地址 $d['fieldProps']['name'] = $relation['name']; if($relation['foreign_model']['menu'] && !$set_url) { //如果关联模型 也关联了菜单 直接使用第一个匹配的这个菜单的url地址 $path = array_reverse(Utils::getPath($relation['foreign_model']['menu'],$this->menus,'path')); $d['fieldProps']['url'] = implode('/',$path); } //如果没有绑定菜单,直接在配置页面中手动设置 url 地址 } } $this->data = $d; return; } public function select() { $d = $this->data; $setting = $this->schema['setting']??[]; $table_menu = $this->schema['table_menu']??''; $d['fieldProps'] = []; if($this->relation) { $d['requestDataName'] = $this->schema['name'].'s'; $label = $value = ''; if(isset($setting['label']) && isset($setting['value'])) { $label = $setting['label']; $value = $setting['value']; }else { if($this->schema['form_type'] == 'select') { $label = 'title'; $value = 'id'; } } if(!$table_menu && $label) { $d['fieldProps'] = ['fieldNames'=>[ 'label'=>$label,'value'=>$value ]]; } if($this->schema['form_type'] == 'selects') { $d['fieldProps']['mode'] = 'multiple'; } }else { if(isset($setting['json'])) { $d['fieldProps']['options'] = json_decode($setting['json'],true); if($this->form_type == 'selects') { $d['fieldProps']['mode'] = 'tags'; } } } if($this->readonly) { //只读的话 删除valueType 直接显示数据了 //unset($d['valueType']); //$d['dataIndex'] = [$relation['name'],$label]; } $this->data = $d; } public function debounceSelect() { $d = $this->data; $relation = $this->relation; $setting = $this->schema['setting']??[]; $label = $setting['label']??''; $value = $setting['value']??''; //输入搜索select if($this->readonly) { //unset($d['valueType']); //$d['dataIndex'] = [$relation['name'],$label]; }else { $d['fieldProps'] = []; if($relation && $relation['foreign_model']) { //需要找到该关联所关联到哪个菜单下面 读取出后台路由地址 if($relation['foreign_model']['menu']) { $path = array_reverse(Utils::getPath($relation['foreign_model']['menu'],$this->menus,'path')); $d['fieldProps'] = [ 'fetchOptions'=>implode('/',$path) ]; } } if($label && $value) { $d['fieldProps'] = array_merge($d['fieldProps'],['fieldNames'=>['label'=>$label,'value'=>$value]]); } } $this->data = $d; return; } public function uploader() { $setting = $this->schema['setting']??[]; if(isset($setting['image_count'])) { $this->data['fieldProps'] = ['max'=>intval($setting['image_count'])]; } return; } public function switch() { $setting = $this->schema['setting']??[]; $open = $setting['open']??''; $close = $setting['close']??''; //switch开关 if($open && $close) { $default = $this->schema['default']??1; $this->data['fieldProps'] = [ "checkedChildren"=>$open, "unCheckedChildren"=>$close, "defaultChecked"=>$default?true:false ]; } //$this->data['initialValue'] = true;//switch 默认设置为选中状态 return; } public function cascader() { //多选分类 $this->data['requestDataName'] = $this->schema['name'].'s'; $this->data['fieldProps'] = [ 'placeholder'=>'请选择'.$this->schema['title'], 'showCheckedStrategy'=>'SHOW_CHILD' ]; if($this->schema['form_type'] == 'cascaders') { $this->data['fieldProps']['multiple'] = true; } return; } public function pca() { //省市区选择 $setting = $this->schema['setting']??[]; if(isset($setting['pca_level'])) { $this->data['fieldProps'] = [ 'level'=>intval($setting['pca_level']) ]; } } public function datetime() { } public function permGroup() { $this->data['fieldProps'] = [ 'requestNames'=>['perms'] ]; } }
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: namespace PryUserDoradoWM.Models { using System; using System.ComponentModel.DataAnnotations; public class EmailAdress { } public enum SuiteType { } public class CityName { } public class Location { } public class Direction { } public class User { public int UserId { get; set; } [Required] [StringLength(100,ErrorMessage ="El nombre debe contener de 5 a 100 caracteres", MinimumLength =5)] public String Name { get; set; } public EmailAdress Email { get; set; } public Direction Street { get; set; } [Range (1,1000,ErrorMessage ="Las habitaciones son entre 1 y 1000")] public SuiteType Suite { get; set; } public CityName City { get; set; } [Range (-90,90,ErrorMessage ="La latitud es entre -90 y 90")] [Range (-180,180,ErrorMessage ="La longitud es estre -180 y 180")] public double Geo { get; set; } public PhoneAttribute Phone { get; set; } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
2
namespace PryUserDoradoWM.Models { using System; using System.ComponentModel.DataAnnotations; public class EmailAdress { } public enum SuiteType { } public class CityName { } public class Location { } public class Direction { } public class User { public int UserId { get; set; } [Required] [StringLength(100,ErrorMessage ="El nombre debe contener de 5 a 100 caracteres", MinimumLength =5)] public String Name { get; set; } public EmailAdress Email { get; set; } public Direction Street { get; set; } [Range (1,1000,ErrorMessage ="Las habitaciones son entre 1 y 1000")] public SuiteType Suite { get; set; } public CityName City { get; set; } [Range (-90,90,ErrorMessage ="La latitud es entre -90 y 90")] [Range (-180,180,ErrorMessage ="La longitud es estre -180 y 180")] public double Geo { get; set; } public PhoneAttribute Phone { get; set; } } }
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Java concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import java.io.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Created by RENT on 2017-08-12. */ public enum Database { INSTANCE; public void saveToDatabase(DatabaseType dbType, Object obj) { saveToDatabase(dbType.getFilename(), obj); } public void saveToDatabase(DatabaseType dbType, Request req) { saveToDatabase(dbType.getFilename(), req); } public void saveToDatabase(String dbName, Object obj) { try (PrintWriter writer = new PrintWriter(new FileOutputStream(dbName, true))) { writer.println(obj); } catch (FileNotFoundException fnfe) { System.err.println("Error reading file."); } } public void appendServiceRequest(String dbName, Request obj) { String userName = obj.getUsername(); String content = obj.getContent(); // read from file Map<String, List<String>> fileContent = readFile(dbName); // handle adding to collection List<String> list; if (fileContent.containsKey(userName)) { list = fileContent.get(userName); list.add(content); } else { list = new LinkedList<>(); list.add(content); } fileContent.put(userName, list); System.out.println("Service record added to list."); // save back to file saveRecordsToFile(dbName, fileContent); } private void saveRecordsToFile(String dbName, Map<String, List<String>> fileContent) { try (PrintWriter writer = new PrintWriter(new FileOutputStream(dbName, true))) { for (Map.Entry<String, List<String>> entry : fileContent.entrySet()) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append(";"); for (String content : entry.getValue()) { sb.append(content); sb.append(": After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
java
3
import java.io.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Created by RENT on 2017-08-12. */ public enum Database { INSTANCE; public void saveToDatabase(DatabaseType dbType, Object obj) { saveToDatabase(dbType.getFilename(), obj); } public void saveToDatabase(DatabaseType dbType, Request req) { saveToDatabase(dbType.getFilename(), req); } public void saveToDatabase(String dbName, Object obj) { try (PrintWriter writer = new PrintWriter(new FileOutputStream(dbName, true))) { writer.println(obj); } catch (FileNotFoundException fnfe) { System.err.println("Error reading file."); } } public void appendServiceRequest(String dbName, Request obj) { String userName = obj.getUsername(); String content = obj.getContent(); // read from file Map<String, List<String>> fileContent = readFile(dbName); // handle adding to collection List<String> list; if (fileContent.containsKey(userName)) { list = fileContent.get(userName); list.add(content); } else { list = new LinkedList<>(); list.add(content); } fileContent.put(userName, list); System.out.println("Service record added to list."); // save back to file saveRecordsToFile(dbName, fileContent); } private void saveRecordsToFile(String dbName, Map<String, List<String>> fileContent) { try (PrintWriter writer = new PrintWriter(new FileOutputStream(dbName, true))) { for (Map.Entry<String, List<String>> entry : fileContent.entrySet()) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append(";"); for (String content : entry.getValue()) { sb.append(content); sb.append(":"); } writer.println(sb.substring(0, sb.length() - 1)); } } catch (FileNotFoundException fnfe) { System.err.println("Error reading file."); } System.out.println("File " + dbName + " has been saved."); } private Map<String, List<String>> readFile(String dbName) { Map<String, List<String>> map = new HashMap<>(); try (BufferedReader reader = new BufferedReader(new FileReader(dbName))) { String line = null; while ((line = reader.readLine()) != null) { // line splitted to username and contents String[] splits = line.split(";"); String userName = splits[0]; // contents splitted more String[] contents = splits[1].split(":"); // rewrite list into array List<String> list = new LinkedList<>(); for(String content : contents){ list.add(content); } // put everything into map map.put(userName, list); } } catch (FileNotFoundException fnfe) { System.err.println("File not found."); } catch (IOException ioe) { System.err.println("IOException."); } return map; } }
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // // SwiftUIView.swift // MarketCap // // Created by Denis on 24.07.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CurrencyRow: View { var currency: Currency var body: some View { HStack { CurrencyLogo (icon: currency.image) .aspectRatio (1.0, contentMode: .fit) .frame (width: 32, height: 32) .fixedSize (horizontal: true, vertical: false) VStack (alignment: .leading) { Text (currency.symbol) .fontWeight (.bold) .truncationMode (.tail) .frame (minWidth: 20) Text (currency.name) .font (.caption) .opacity (0.625) .truncationMode (.middle) } Spacer() if currency.rank != nil { Text ("$\(String (currency.price!))") .font (.caption) .foregroundColor (.yellow) .padding (.trailing, 8) } } } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { CurrencyRow (currency: Currency ( id: "test_id", name: "Test", symbol: "TST", rank: 1, image: "coins/images/1/thumb/bitcoin.png" )) } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
3
// // SwiftUIView.swift // MarketCap // // Created by Denis on 24.07.2020. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CurrencyRow: View { var currency: Currency var body: some View { HStack { CurrencyLogo (icon: currency.image) .aspectRatio (1.0, contentMode: .fit) .frame (width: 32, height: 32) .fixedSize (horizontal: true, vertical: false) VStack (alignment: .leading) { Text (currency.symbol) .fontWeight (.bold) .truncationMode (.tail) .frame (minWidth: 20) Text (currency.name) .font (.caption) .opacity (0.625) .truncationMode (.middle) } Spacer() if currency.rank != nil { Text ("$\(String (currency.price!))") .font (.caption) .foregroundColor (.yellow) .padding (.trailing, 8) } } } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { CurrencyRow (currency: Currency ( id: "test_id", name: "Test", symbol: "TST", rank: 1, image: "coins/images/1/thumb/bitcoin.png" )) } }
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // // DataLayer.swift // WeatherApp // // Created by <NAME> on 9.07.2021. // import Foundation import Combine import CoreLocation class DataLayer { private var network: Network = Network.shared private let apiService = APIService() private let fileService = FileService() private let locationService = LocationService() private(set) var weatherModel: WeatherModel? = nil private var cancellables = Set<AnyCancellable>() init(network: Network = Network.shared, weatherModel: WeatherModel? = nil) { self.network = network self.weatherModel = weatherModel } } // MARK: - Public extension DataLayer { func reset() { self.weatherModel = nil } func listItems(from selectedDate: Date) -> [List] { guard let model = weatherModel, let listArr = model.list else { return [] } let selectedDayIdentifier = selectedDate.dateUniqueIdentifier return listArr.compactMap { item -> List? in guard item.date().dateUniqueIdentifier == selectedDayIdentifier else { return nil } return item } } func listItem(from selectedTime: Date) -> List? { guard let model = weatherModel, let listArr = model.list else { return nil } let selectedDateIdentifier = selectedTime.fullDateUniqueIdentifier return listArr.first { item -> Bool in let identifer = item.date().fullDateUniqueIdentifier return identifer == selectedDateIdentifier } ?? listArr.first } func dailyWeatherListItems() -> [List] { guard let model = weatherModel, let listArr = model.list else { return [] } var currentIdentifiers: [String] = [] var tempListArr: [List] = [] var listOfMidDayWeathers: [List] = [] listArr.forEach { item in let uniqueIdentifier = item.date().dateUniqueIdentifier if !currentIdentifiers.contains(uniqueIdentifier) { After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
-1
// // DataLayer.swift // WeatherApp // // Created by <NAME> on 9.07.2021. // import Foundation import Combine import CoreLocation class DataLayer { private var network: Network = Network.shared private let apiService = APIService() private let fileService = FileService() private let locationService = LocationService() private(set) var weatherModel: WeatherModel? = nil private var cancellables = Set<AnyCancellable>() init(network: Network = Network.shared, weatherModel: WeatherModel? = nil) { self.network = network self.weatherModel = weatherModel } } // MARK: - Public extension DataLayer { func reset() { self.weatherModel = nil } func listItems(from selectedDate: Date) -> [List] { guard let model = weatherModel, let listArr = model.list else { return [] } let selectedDayIdentifier = selectedDate.dateUniqueIdentifier return listArr.compactMap { item -> List? in guard item.date().dateUniqueIdentifier == selectedDayIdentifier else { return nil } return item } } func listItem(from selectedTime: Date) -> List? { guard let model = weatherModel, let listArr = model.list else { return nil } let selectedDateIdentifier = selectedTime.fullDateUniqueIdentifier return listArr.first { item -> Bool in let identifer = item.date().fullDateUniqueIdentifier return identifer == selectedDateIdentifier } ?? listArr.first } func dailyWeatherListItems() -> [List] { guard let model = weatherModel, let listArr = model.list else { return [] } var currentIdentifiers: [String] = [] var tempListArr: [List] = [] var listOfMidDayWeathers: [List] = [] listArr.forEach { item in let uniqueIdentifier = item.date().dateUniqueIdentifier if !currentIdentifiers.contains(uniqueIdentifier) { if tempListArr.count > 0 { let midDayWeather = tempListArr[tempListArr.count / 2] listOfMidDayWeathers.append(midDayWeather) } currentIdentifiers.append(uniqueIdentifier) tempListArr = [] } tempListArr.append(item) } if tempListArr.count > 0 { let midDayWeather = tempListArr[tempListArr.count / 2] listOfMidDayWeathers.append(midDayWeather) } return listOfMidDayWeathers } func initialize() -> AnyPublisher<WeatherAppError?, Never> { // Network Check if Network.shared.networkStatus.value == .offline { return self.fileService.readWeatherData().flatMap { data -> AnyPublisher<WeatherModelResponse, Never> in guard let data = data else { let response = WeatherModelResponse(model: nil, error: nil) return Just(response).eraseToAnyPublisher() } return self.convertToDataModel(from: data) }.flatMap { response -> AnyPublisher<WeatherAppError?, Never> in self.weatherModel = response.model return Just(WeatherAppError.noInternetConnection).eraseToAnyPublisher() }.eraseToAnyPublisher() } var apiResponseData: Data? = nil let publisher = self.locationService.requestUserLocation().flatMap { response -> AnyPublisher<WeatherDataResponse, Never> in guard let coordinates = response.coordinates, response.error == nil else { let response = WeatherDataResponse(data: nil, error: .locationNotFound) return Just(response).eraseToAnyPublisher() } return self.requestWeatherData(from: coordinates).eraseToAnyPublisher() }.flatMap { response -> AnyPublisher<WeatherModelResponse, Never> in guard response.error == nil, let data = response.data else { let response = WeatherModelResponse(model: nil, error: .apiServiceError) return Just(response).eraseToAnyPublisher() } apiResponseData = data return self.convertToDataModel(from: data) }.flatMap { modelResponse -> AnyPublisher<WeatherModelResponse, Never> in guard modelResponse.error == nil, let model = modelResponse.model else { let response = WeatherModelResponse(model: nil, error: .apiServiceError) return Just(response).eraseToAnyPublisher() } return self.checkResponseModel(weatherModel: model) }.flatMap { modelResponse -> AnyPublisher<WeatherDataResponse, Never> in guard modelResponse.error == nil, let model = modelResponse.model, let data = apiResponseData else { let response = WeatherDataResponse(data: nil, error: .apiServiceError) return Just(response).eraseToAnyPublisher() } self.weatherModel = model return self.fileService.writeWeatherData(json: data) }.flatMap { response -> AnyPublisher<WeatherAppError?, Never> in guard let _ = response.data else { return Just(WeatherAppError.apiServiceError).eraseToAnyPublisher() } return Just(response.error).eraseToAnyPublisher() } return publisher.eraseToAnyPublisher() } } // MARK: - Request extension DataLayer { private func convertToDataModel(from data: Data) -> AnyPublisher<WeatherModelResponse, Never> { return Future {promise in self.convertToDataModel(from: data) { response in promise(.success(response)) } }.eraseToAnyPublisher() } fileprivate func convertToDataModel(from data: Data, callback: @escaping (WeatherModelResponse) -> ()) { DispatchQueue.global().async { do { let json = try JSONDecoder().decode(WeatherModel.self, from: data) let response = WeatherModelResponse(model: json, error: nil) callback(response) } catch let error { let response = WeatherModelResponse(model: nil, error: WeatherAppError.apiServiceError) callback(response) } } } private func checkResponseModel(weatherModel: WeatherModel) -> AnyPublisher<WeatherModelResponse, Never> { return Future {promise in DispatchQueue.global().async { self.checkResponseModel(weatherModel: weatherModel) { response in promise(.success(response)) } } }.eraseToAnyPublisher() } fileprivate func checkResponseModel(weatherModel: WeatherModel, callback: @escaping (WeatherModelResponse) -> ()) { guard let _ = weatherModel.city, let listArr = weatherModel.list, listArr.count > 0 else { let response = WeatherModelResponse(model: nil, error: .fileProcessingError) callback(response) return } guard listArr.first { listItem -> Bool in guard let _ = listItem.dt, let _ = listItem.main else { return true } return false } == nil else { let response = WeatherModelResponse(model: nil, error: .fileProcessingError) callback(response) return } callback(WeatherModelResponse(model: weatherModel, error: nil)) } private func requestWeatherData(from coordinates: CLLocationCoordinate2D) -> AnyPublisher<WeatherDataResponse, Never> { return apiService.requestRx(service: .cityLocation(coordinates)).flatMap { response -> AnyPublisher<WeatherDataResponse, Never> in if let error = response.error { let response = WeatherDataResponse(data: nil, error: .apiServiceError) return Just(response).eraseToAnyPublisher() } guard let data = response.data else { let response = WeatherDataResponse(data: nil, error: .apiServiceError) return Just(response).eraseToAnyPublisher() } let response = WeatherDataResponse(data: data, error: nil) return Just(response).eraseToAnyPublisher() }.eraseToAnyPublisher() } } // MARK: - Mock class DataLayerMock: DataLayer { override init(network: Network = Network.shared, weatherModel : WeatherModel? = nil) { super.init(network: network,weatherModel: weatherModel) } func convertToDataModelMock(from data: Data, callback: @escaping (WeatherModelResponse) -> ()) { super.convertToDataModel(from: data, callback: callback) } func checkResponseModelMock(weatherModel: WeatherModel, callback: @escaping (WeatherModelResponse) -> ()) { super.checkResponseModel(weatherModel: weatherModel, callback: callback) } func listItemsMock(from selectedDate: Date) -> [List]{ super.listItems(from: selectedDate) } func listItemMock(from selectedTime: Date) -> List? { super.listItem(from: selectedTime) } func dailyWeatherListItemsMock() -> [List] { super.dailyWeatherListItems() } }
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import './index.css'; import liff from '@line/liff' document.addEventListener("DOMContentLoaded", function() { const panel = document.getElementById('panel'); // Launch the panel setTimeout(() => { panel.classList.add('active'); }, 500); liff .init({ liffId: process.env.LIFF_ID || '' }) .then(() => { console.log("Success! you can do something with LIFF API here.") }) .catch((error) => { console.log(error) }) }); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
3
import './index.css'; import liff from '@line/liff' document.addEventListener("DOMContentLoaded", function() { const panel = document.getElementById('panel'); // Launch the panel setTimeout(() => { panel.classList.add('active'); }, 500); liff .init({ liffId: process.env.LIFF_ID || '' }) .then(() => { console.log("Success! you can do something with LIFF API here.") }) .catch((error) => { console.log(error) }) });
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: {% load cache %} {% load i18n %} {% if user.is_authenticated %} <form id="logoutForm" action="/logout" method="post" class="navbar-right"> {% csrf_token %} {% cache 600 usersidebar %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">{{ user.social_auth.get.extra_data.player.personaname }}</span></li> <li><a href="/myposts">{% trans "Мои объявления" %}</a></li> <li><a href="javascript:document.getElementById('logoutForm').submit()">{% trans "Выйти" %}</a></li> </ul> {% endcache %} </form> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="{% url "social:begin" "steam" %}">{% trans "Войти через SteamID" %}</a></li> </ul> {% endif %} After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
{% load cache %} {% load i18n %} {% if user.is_authenticated %} <form id="logoutForm" action="/logout" method="post" class="navbar-right"> {% csrf_token %} {% cache 600 usersidebar %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">{{ user.social_auth.get.extra_data.player.personaname }}</span></li> <li><a href="/myposts">{% trans "Мои объявления" %}</a></li> <li><a href="javascript:document.getElementById('logoutForm').submit()">{% trans "Выйти" %}</a></li> </ul> {% endcache %} </form> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="{% url "social:begin" "steam" %}">{% trans "Войти через SteamID" %}</a></li> </ul> {% endif %}
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract:  using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace GateBoys.Models { public class OrderSupply { [Key] public int orderId { get; set; } [Display(Name = "Order Number")] public string OrderNum { get; set; } [Display(Name = "supplier Name")] public string supplier { get; set; } [Display(Name = "supplier Email")] public string supplierEmail { get; set; } [Display(Name = "Supplier Phone")] public string suplyNum { get; set; } [Display(Name = "Number of items ordered")] public int itemQty { get; set; } [Display(Name = "Products ordered")] public string ProductsList { get; set; } [Display(Name = "Number Of Prod Ordered")] public int NumOfProdOrdered { get; set; } [Display(Name = "Ordered By")] public string orderedBy { get; set; } [Display(Name = "Total Order Cost")] public decimal totalOrder { get; set; } [Display(Name = "Date ordered")] public string dateOrdered { get; set; } [Display(Name = "Status Order")] public string status { get; set; } [Display(Name = "Is Ordered")] public bool isOrdered { get; set; } //public int ProuctsId { get; set; } //public virtual InventoryProduct InventoryProducts { get; set; } //public int SupplierId { get; set; } //public virtual Supplier Suppliers { get; set; } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
2
 using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace GateBoys.Models { public class OrderSupply { [Key] public int orderId { get; set; } [Display(Name = "Order Number")] public string OrderNum { get; set; } [Display(Name = "supplier Name")] public string supplier { get; set; } [Display(Name = "supplier Email")] public string supplierEmail { get; set; } [Display(Name = "Supplier Phone")] public string suplyNum { get; set; } [Display(Name = "Number of items ordered")] public int itemQty { get; set; } [Display(Name = "Products ordered")] public string ProductsList { get; set; } [Display(Name = "Number Of Prod Ordered")] public int NumOfProdOrdered { get; set; } [Display(Name = "Ordered By")] public string orderedBy { get; set; } [Display(Name = "Total Order Cost")] public decimal totalOrder { get; set; } [Display(Name = "Date ordered")] public string dateOrdered { get; set; } [Display(Name = "Status Order")] public string status { get; set; } [Display(Name = "Is Ordered")] public bool isOrdered { get; set; } //public int ProuctsId { get; set; } //public virtual InventoryProduct InventoryProducts { get; set; } //public int SupplierId { get; set; } //public virtual Supplier Suppliers { get; set; } } }
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: using System.Collections; using System.Collections.Generic; using UnityEngine; // [RequireComponent(typeof(SpearControl))] public class UnitMovement : MonoBehaviour { Camera myCam; UnityEngine.AI.NavMeshAgent myAgent; public LayerMask ground ; Animator animation; public float radius = Mathf.Infinity; [Header("Attribute")] public Transform focus; public float attackRange ; [Header("Instruction")] public bool hasInstruction = false; public Vector3 InstructionPosition; // SpearControl spearControl; void Start() { myCam = Camera.main; myAgent = GetComponent<UnityEngine.AI.NavMeshAgent>(); animation = GetComponent<Animator>(); // spearControl = GetComponent<SpearControl>(); } // Update is called once per frame void Update() { // if(animation.GetBool("IsDead")) return ; // if(myAgent.remainingDistance< 0.1f) // { // animation.SetBool("IsRuning", false); // } if(Input.GetMouseButtonDown(1)) { RaycastHit hit; Ray ray = myCam.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray, out hit , Mathf.Infinity, ground)) { // hasInstruction = true; if( hit.collider.tag !="Untagged") { // print(hit.collider.tag); focus = hit.transform; // float radius = Mathf.Infinity; //判断是人还是建筑 if(hit.collider.GetComponent<CapsuleCollider>() != null ) { //走到敌人边界 radius = hit.collider.GetComponent<CapsuleCollider>().radius; } //if(是建筑) // //如果离目标过远,会先走过去 if (Vector3.Distance(transform.position, hit.transform.position) > radius) { After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
3
using System.Collections; using System.Collections.Generic; using UnityEngine; // [RequireComponent(typeof(SpearControl))] public class UnitMovement : MonoBehaviour { Camera myCam; UnityEngine.AI.NavMeshAgent myAgent; public LayerMask ground ; Animator animation; public float radius = Mathf.Infinity; [Header("Attribute")] public Transform focus; public float attackRange ; [Header("Instruction")] public bool hasInstruction = false; public Vector3 InstructionPosition; // SpearControl spearControl; void Start() { myCam = Camera.main; myAgent = GetComponent<UnityEngine.AI.NavMeshAgent>(); animation = GetComponent<Animator>(); // spearControl = GetComponent<SpearControl>(); } // Update is called once per frame void Update() { // if(animation.GetBool("IsDead")) return ; // if(myAgent.remainingDistance< 0.1f) // { // animation.SetBool("IsRuning", false); // } if(Input.GetMouseButtonDown(1)) { RaycastHit hit; Ray ray = myCam.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray, out hit , Mathf.Infinity, ground)) { // hasInstruction = true; if( hit.collider.tag !="Untagged") { // print(hit.collider.tag); focus = hit.transform; // float radius = Mathf.Infinity; //判断是人还是建筑 if(hit.collider.GetComponent<CapsuleCollider>() != null ) { //走到敌人边界 radius = hit.collider.GetComponent<CapsuleCollider>().radius; } //if(是建筑) // //如果离目标过远,会先走过去 if (Vector3.Distance(transform.position, hit.transform.position) > radius) { // animation.SetBool("IsRuning", true); // Vector3 border = hit.transform.position + (transform.position - hit.transform.position).normalized * (radius + attackRange) ; // Debug.Log(border+" "+hit.transform.position); MoveToBorder(hit.transform.position, radius, attackRange ); hasInstruction = true; InstructionPosition = hit.transform.position + (transform.position - hit.transform.position).normalized * (radius + attackRange); } } else { DeFocus(); myAgent.SetDestination(hit.point); print("移动指令"); hasInstruction = true; InstructionPosition = hit.point; // animation.SetBool("IsRuning", true); } } } } public void MoveToBorder(Vector3 _target, float _radius, float _attackRange) { Vector3 border = _target + (transform.position - _target).normalized * (_radius + _attackRange); //如果自身与目标的距离 大于 border与目标的距离,则动 if(Vector3.Distance(border,_target)< Vector3.Distance(transform.position, _target)) { myAgent.SetDestination(border); } } public bool ArriveBorder(Vector3 targetPosition) { Vector3 border = targetPosition + (transform.position - targetPosition).normalized * (radius + attackRange); bool outside = Vector3.Distance(transform.position, border) < 0.1f; bool inside = Vector3.Distance(transform.position, targetPosition) < Vector3.Distance(border, targetPosition); return outside || inside; } // void SetFocus(Transform _focus) // { // focus = _focus; // i // } public void DeFocus() { focus = null; } }
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations. - Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments. - Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments. - Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design. - Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code. The extract: drop database if exists FLIGHT; create database FLIGHT; use FLIGHT; set STORAGE_ENGINE=InnoDB; set NAMES 'utf8'; create table FLIGHT.AERONAVE ( ID integer not null auto_increment, NOME varchar(40) not null, CODIGO varchar(40) not null, QTD_ASSENTO smallint not null, IMAGEM mediumblob not null, MAPA tinyint not null, primary key (ID), unique key(CODIGO) )Engine=InnoDB; create table FLIGHT.VOO ( ID integer not null auto_increment, AERONAVE_ID integer not null, CODIGO varchar(40) not null, ORIGEM varchar(40) not null, DESTINO varchar(40) not null, ESCALA varchar(40) null, DATA_PARTIDA datetime not null, DATA_CHEGADA datetime not null, OBSERVACAO varchar(100) null, STATUS tinyint not null, ASSENTO_LIVRE integer not null, PRECO double not null, primary key (ID), unique key (CODIGO), constraint foreign key FK_AERONAVE_ID (AERONAVE_ID) references FLIGHT.AERONAVE (ID) )Engine=InnoDB; create table FLIGHT.PESSOAFISICA( ID integer not null auto_increment, NOME varchar(30) not null, SOBRENOME varchar(80) not null, DATA_NASCIMENTO date not null, CPF bigint not null, RG varchar(15) not null, ENDERECO varchar(100) not null, TEL_RESIDENCIAL integer not null, TEL_CELULAR integer null, EMAIL varchar(100) null, primary key (ID), unique key(CPF) )Engine=InnoDB; create table FLIGHT.USUARIO ( ID integer not null auto_increment, PESSOAFISICA_ID integer not null, CODIGO varchar(40) not null, PERFIL tinyint not null, LOGIN varchar(50) not null, SENHA varchar(50) not null, primary key (ID), unique key(CODIGO), unique key(PESSOAFISICA_ID), unique key(LOGIN, SENHA), constraint foreign key FK_PESSOAFISICA_USUARIO (PESSOAFISICA_ID) references FLIGHT.PESSOAFISICA (ID) )Engine=InnoDB; create table FLIGHT.PASSAGEM( ID integer not null auto_increment, VOO_ID integer null, PESSOAFISICA_ID integer not null, COD_BILHETE varchar(11) not null, ASSENTO varchar(5) null, primary key(ID), unique key(COD_BILHETE), unique key(VOO_ID, PESSOAFISICA_ID), constraint foreign key FK_VOO_PASSA After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
sql
4
drop database if exists FLIGHT; create database FLIGHT; use FLIGHT; set STORAGE_ENGINE=InnoDB; set NAMES 'utf8'; create table FLIGHT.AERONAVE ( ID integer not null auto_increment, NOME varchar(40) not null, CODIGO varchar(40) not null, QTD_ASSENTO smallint not null, IMAGEM mediumblob not null, MAPA tinyint not null, primary key (ID), unique key(CODIGO) )Engine=InnoDB; create table FLIGHT.VOO ( ID integer not null auto_increment, AERONAVE_ID integer not null, CODIGO varchar(40) not null, ORIGEM varchar(40) not null, DESTINO varchar(40) not null, ESCALA varchar(40) null, DATA_PARTIDA datetime not null, DATA_CHEGADA datetime not null, OBSERVACAO varchar(100) null, STATUS tinyint not null, ASSENTO_LIVRE integer not null, PRECO double not null, primary key (ID), unique key (CODIGO), constraint foreign key FK_AERONAVE_ID (AERONAVE_ID) references FLIGHT.AERONAVE (ID) )Engine=InnoDB; create table FLIGHT.PESSOAFISICA( ID integer not null auto_increment, NOME varchar(30) not null, SOBRENOME varchar(80) not null, DATA_NASCIMENTO date not null, CPF bigint not null, RG varchar(15) not null, ENDERECO varchar(100) not null, TEL_RESIDENCIAL integer not null, TEL_CELULAR integer null, EMAIL varchar(100) null, primary key (ID), unique key(CPF) )Engine=InnoDB; create table FLIGHT.USUARIO ( ID integer not null auto_increment, PESSOAFISICA_ID integer not null, CODIGO varchar(40) not null, PERFIL tinyint not null, LOGIN varchar(50) not null, SENHA varchar(50) not null, primary key (ID), unique key(CODIGO), unique key(PESSOAFISICA_ID), unique key(LOGIN, SENHA), constraint foreign key FK_PESSOAFISICA_USUARIO (PESSOAFISICA_ID) references FLIGHT.PESSOAFISICA (ID) )Engine=InnoDB; create table FLIGHT.PASSAGEM( ID integer not null auto_increment, VOO_ID integer null, PESSOAFISICA_ID integer not null, COD_BILHETE varchar(11) not null, ASSENTO varchar(5) null, primary key(ID), unique key(COD_BILHETE), unique key(VOO_ID, PESSOAFISICA_ID), constraint foreign key FK_VOO_PASSAGEM (VOO_ID) references FLIGHT.VOO (ID), constraint foreign key FK_PESSOAFISICA_PASSAGEM (PESSOAFISICA_ID) references FLIGHT.PESSOAFISICA (ID) )Engine=InnoDB; create table FLIGHT.REEMBOLSO ( ID integer not null auto_increment, PASSAGEM_ID integer not null, TITULAR varchar(80) not null, CPF bigint not null, BANCO integer not null, AGENCIA integer not null, CONTA integer not null, VALOR double(10,2) not null, primary key(ID), unique key(PASSAGEM_ID), constraint foreign key FK_PASSAGEM_REEMBOLSO (PASSAGEM_ID) references FLIGHT.PASSAGEM (ID) )Engine=InnoDB; CREATE USER 'usjt'@'localhost' IDENTIFIED BY 'usjt'; GRANT ALL PRIVILEGES ON FLIGHT.* TO 'usjt'@'localhost' WITH GRANT OPTION; set foreign_key_checks=0; drop table if exists FLIGHT.AERONAVE; create table FLIGHT.AERONAVE ( ID integer not null auto_increment, NOME varchar(40) not null, CODIGO varchar(40) not null, QTD_ASSENTO smallint not null, IMAGEM mediumblob not null, MAPA tinyint not null, primary key (ID), unique key(CODIGO) )Engine=InnoDB; set foreign_key_checks=0; drop table if exists FLIGHT.VOO; create table FLIGHT.VOO ( ID integer not null auto_increment, AERONAVE_ID integer not null, CODIGO varchar(40) not null, ORIGEM varchar(40) not null, DESTINO varchar(40) not null, ESCALA varchar(40) null, DATA_PARTIDA datetime not null, DATA_CHEGADA datetime not null, OBSERVACAO varchar(100) null, STATUS tinyint not null, ASSENTO_LIVRE integer not null, PRECO double not null, primary key (ID), unique key (CODIGO), constraint foreign key FK_AERONAVE_ID (AERONAVE_ID) references FLIGHT.AERONAVE (ID) )Engine=InnoDB; set foreign_key_checks=0; drop table if exists FLIGHT.PESSOAFISICA; create table FLIGHT.PESSOAFISICA( ID integer not null auto_increment, NOME varchar(30) not null, SOBRENOME varchar(80) not null, DATA_NASCIMENTO date not null, CPF bigint not null, RG varchar(15) not null, ENDERECO varchar(100) not null, TEL_RESIDENCIAL integer not null, TEL_CELULAR integer null, EMAIL varchar(100) null, primary key (ID), unique key(CPF) )Engine=InnoDB; set foreign_key_checks=0; drop table if exists FLIGHT.USUARIO; create table FLIGHT.USUARIO ( ID integer not null auto_increment, PESSOAFISICA_ID integer not null, CODIGO varchar(40) not null, PERFIL tinyint not null, LOGIN varchar(50) not null, SENHA varchar(50) not null, primary key (ID), unique key(CODIGO), unique key(PESSOAFISICA_ID), unique key(LOGIN, SENHA), constraint foreign key FK_PESSOAFISICA_USUARIO (PESSOAFISICA_ID) references FLIGHT.PESSOAFISICA (ID) )Engine=InnoDB; set foreign_key_checks=0; drop table if exists FLIGHT.PASSAGEM; create table FLIGHT.PASSAGEM( ID integer not null auto_increment, VOO_ID integer null, PESSOAFISICA_ID integer not null, COD_BILHETE varchar(11) not null, ASSENTO varchar(5) null, primary key(ID), unique key(COD_BILHETE), unique key(VOO_ID, PESSOAFISICA_ID), constraint foreign key FK_VOO_PASSAGEM (VOO_ID) references FLIGHT.VOO (ID), constraint foreign key FK_PESSOAFISICA_PASSAGEM (PESSOAFISICA_ID) references FLIGHT.PESSOAFISICA (ID) )Engine=InnoDB; set foreign_key_checks=0; drop table if exists FLIGHT.REEMBOLSO; create table FLIGHT.REEMBOLSO ( ID integer not null auto_increment, PASSAGEM_ID integer not null, TITULAR varchar(80) not null, CPF bigint not null, BANCO integer not null, AGENCIA integer not null, CONTA integer not null, VALOR double(10,2) not null, primary key(ID), unique key(PASSAGEM_ID), constraint foreign key FK_PASSAGEM_REEMBOLSO (PASSAGEM_ID) references FLIGHT.PASSAGEM (ID) )Engine=InnoDB;
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: /* Types */ export type CSSClass = string; export type CSSClassMap = { [key: string]: boolean }; export type CSSSelector = string; export type Dataset = { [key: string]: string }; export type Elements = Element[]; export type EventType = string; export type Insertable = string | Node | NodeList; type EventOptions = { bubbles?: boolean, cancelable?: boolean, detail?: any }; type Predicate = (element: Element) => boolean; /* Aliases */ export const body: Element; export const html: Element; /* CSS */ export function addClass(element: Element, cssClass: CSSClass): boolean; export function addClass(element: Element, ...cssClasses: CSSClass[]): boolean; export function hasClass(element: Element, cssClass: CSSClass): boolean; export function removeClass(element: Element, cssClass: CSSClass): boolean; export function removeClasses(element: Element, ...cssClasses: CSSClass[]): boolean; export function toggleClass(element: Element, cssClass: CSSClass, state?: boolean): boolean; export function toggleClasses(element: Element, ...cssClasses: (CSSClass | CSSClassMap)[]): boolean; /* Data */ export function dataset(element: HTMLElement): Dataset; /* Events */ export function dispatch(target: EventTarget, eventType: EventType, detail?: any, options?: EventOptions): boolean; export function on(target: EventTarget, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; export function once(target: EventTarget, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; export function delegate(target: EventTarget, selector: CSSSelector, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; /* Manipulation */ export function after(element: Element, ...insertable: Insertable[]): void; export function append(element: Element, ...insertable: Insertable[]): void; export function before(element: Element, ...insertable: Insertable[]): void; export function prepend(element: Element, ...insertable: Inse After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
4
/* Types */ export type CSSClass = string; export type CSSClassMap = { [key: string]: boolean }; export type CSSSelector = string; export type Dataset = { [key: string]: string }; export type Elements = Element[]; export type EventType = string; export type Insertable = string | Node | NodeList; type EventOptions = { bubbles?: boolean, cancelable?: boolean, detail?: any }; type Predicate = (element: Element) => boolean; /* Aliases */ export const body: Element; export const html: Element; /* CSS */ export function addClass(element: Element, cssClass: CSSClass): boolean; export function addClass(element: Element, ...cssClasses: CSSClass[]): boolean; export function hasClass(element: Element, cssClass: CSSClass): boolean; export function removeClass(element: Element, cssClass: CSSClass): boolean; export function removeClasses(element: Element, ...cssClasses: CSSClass[]): boolean; export function toggleClass(element: Element, cssClass: CSSClass, state?: boolean): boolean; export function toggleClasses(element: Element, ...cssClasses: (CSSClass | CSSClassMap)[]): boolean; /* Data */ export function dataset(element: HTMLElement): Dataset; /* Events */ export function dispatch(target: EventTarget, eventType: EventType, detail?: any, options?: EventOptions): boolean; export function on(target: EventTarget, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; export function once(target: EventTarget, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; export function delegate(target: EventTarget, selector: CSSSelector, eventType: EventType, listener: EventListener, useCapture?: boolean): () => void; /* Manipulation */ export function after(element: Element, ...insertable: Insertable[]): void; export function append(element: Element, ...insertable: Insertable[]): void; export function before(element: Element, ...insertable: Insertable[]): void; export function prepend(element: Element, ...insertable: Insertable[]): void; export function removeAttr(element: Element, attribute: string): void; export function remove(element: Element): boolean; export function setAttr(element: Element, attribute: string, value: any): void; export function setHtml(element: Element, html: string): void; export function setText(element: Element, text: string): void; /* Quering */ export function query(element: Element, selector: CSSSelector): Element | null; export function queryAll(element: Element, selector: CSSSelector): Elements; /* Traversing */ export function closest(element: Element, condition: CSSSelector | Predicate): Element | null; export function getAttr(element: Element, attribute: string, defaultValue: string | null): string | null; export function getHtml(element: Element): string; export function getText(element: Element): string; export function hasAttr(element: Element, attribute: string): boolean; export function matches(element: Element, selector: CSSSelector): boolean; export function parent(element: Element): Element | null; export function parentBy(element: Element, condition: CSSSelector | Predicate): Element | null; export function parents(element: Element): Elements; export function parentsBy(element: Element, condition: CSSSelector | Predicate): Elements;
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package com.think4software.smtfusioncalculator.dao.mapper import com.think4software.smtfusioncalculator.factory.DemonFactory.getDemonEntity import kotlin.test.Test import kotlin.test.assertEquals class DemonEvolutionMapperTest { private val mapper = DemonEvolutionMapper() @Test fun toDomain_whenThereIsEvolution_convertsSuccessfully() { val demonEntity = getDemonEntity() val demonEvolution = mapper.toDomain(demonEntity, 5) assertEquals(demonEvolution!!.demonId, demonEntity.demonId) assertEquals(demonEvolution.level, 5) assertEquals(demonEvolution.name, demonEntity.name) } @Test fun toDomain_whenThereIsNoEvolution_convertsToNull() { val demonEvolution = mapper.toDomain(null, 0) assertEquals(demonEvolution, null) } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
2
package com.think4software.smtfusioncalculator.dao.mapper import com.think4software.smtfusioncalculator.factory.DemonFactory.getDemonEntity import kotlin.test.Test import kotlin.test.assertEquals class DemonEvolutionMapperTest { private val mapper = DemonEvolutionMapper() @Test fun toDomain_whenThereIsEvolution_convertsSuccessfully() { val demonEntity = getDemonEntity() val demonEvolution = mapper.toDomain(demonEntity, 5) assertEquals(demonEvolution!!.demonId, demonEntity.demonId) assertEquals(demonEvolution.level, 5) assertEquals(demonEvolution.name, demonEntity.name) } @Test fun toDomain_whenThereIsNoEvolution_convertsToNull() { val demonEvolution = mapper.toDomain(null, 0) assertEquals(demonEvolution, null) } }
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: # [Магический шар 8](https://stepik.org/lesson/349846/step/1?unit=333701) **Описание проекта**: магический шар 8 (шар судьбы) — шуточный способ предсказывать будущее. Программа должна просить пользователя задать некий вопрос, чтобы случайным образом на него ответить. **Составляющие проекта:** - Целые числа (тип `int`); - Переменные; - Ввод / вывод данных (функции `input()` и `print()`); - Условный оператор (`if/elif/else`); - Цикл `while`; - Бесконечный цикл; - Операторы `break, continue`; - Работа с модулем `random` для генерации случайных чисел. ### Варианты ответов Традиционно шар имеет 2020 ответов, которые можно разделить на четыре группы. | Положительные | Нерешительно положительные | Нейтральные | Отрицательные | | ------------------------- | -------------------------- | ------------------------------ | ---------------------------- | | Бесспорно | Мне кажется - да | Пока неясно, попробуй снова | Даже не думай | | Предрешено | Вероятнее всего | Спроси позже | Мой ответ - нет | | Никаких сомнений | Хорошие перспективы | Лучше не рассказывать | По моим данным - нет | | Определённо да | Знаки говорят - да | Сейчас нельзя предсказать | Перспективы не очень хорошие | | Можешь быть уверен в этом | Да | Сконцентрируйся и спроси опять | Весьма сомнительно | ```python import random answers = ["Бесспорно", "Предрешено", "Никаких сомнений", "Определённо да", "Можешь быть уверен в этом", "Мне кажется - да", "Вероятнее всего", "Хорошие перспективы", "Знаки говорят - да", "Да", "Пока неясно, попробуй снова", "Спроси позже", "Лучше не рассказывать", "Сейчас нельзя предсказать", "Сконцентрируйся и спроси опять", "Даже не думай", "Мой ответ - нет", "По моим данным - нет", "Перспективы не очень хороши After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
4
# [Магический шар 8](https://stepik.org/lesson/349846/step/1?unit=333701) **Описание проекта**: магический шар 8 (шар судьбы) — шуточный способ предсказывать будущее. Программа должна просить пользователя задать некий вопрос, чтобы случайным образом на него ответить. **Составляющие проекта:** - Целые числа (тип `int`); - Переменные; - Ввод / вывод данных (функции `input()` и `print()`); - Условный оператор (`if/elif/else`); - Цикл `while`; - Бесконечный цикл; - Операторы `break, continue`; - Работа с модулем `random` для генерации случайных чисел. ### Варианты ответов Традиционно шар имеет 2020 ответов, которые можно разделить на четыре группы. | Положительные | Нерешительно положительные | Нейтральные | Отрицательные | | ------------------------- | -------------------------- | ------------------------------ | ---------------------------- | | Бесспорно | Мне кажется - да | Пока неясно, попробуй снова | Даже не думай | | Предрешено | Вероятнее всего | Спроси позже | Мой ответ - нет | | Никаких сомнений | Хорошие перспективы | Лучше не рассказывать | По моим данным - нет | | Определённо да | Знаки говорят - да | Сейчас нельзя предсказать | Перспективы не очень хорошие | | Можешь быть уверен в этом | Да | Сконцентрируйся и спроси опять | Весьма сомнительно | ```python import random answers = ["Бесспорно", "Предрешено", "Никаких сомнений", "Определённо да", "Можешь быть уверен в этом", "Мне кажется - да", "Вероятнее всего", "Хорошие перспективы", "Знаки говорят - да", "Да", "Пока неясно, попробуй снова", "Спроси позже", "Лучше не рассказывать", "Сейчас нельзя предсказать", "Сконцентрируйся и спроси опять", "Даже не думай", "Мой ответ - нет", "По моим данным - нет", "Перспективы не очень хорошие", "Весьма сомнительно"] print("Привет Мир, я магический шар, и я знаю ответ на любой твой вопрос.") name = input("Введите своё имя: ") print("Привет,", name) while(True): req = input("Введите вопрос: ") print(random.choice(answers)) another = input("Ещё вопросы? Y/N: ") if (another.lower() == "n"): break print("Возвращайся если возникнут вопросы!") ```
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: It always helps to have some targets to replicate, or ideas of things to do yourself. Small examples can motivate a lot of learnign for bigger projects. After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
1
It always helps to have some targets to replicate, or ideas of things to do yourself. Small examples can motivate a lot of learnign for bigger projects.
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: <div class="well"> <address> <strong>{{addressModel.client.name || addressModel.supplier.name || addressModel.societe.name || addressModel.name}}</strong><br> <span editable-textarea="addressModel.address" e-name="address" e-rows="4" e-cols="400" e-required e-class="form-control"><pre>{{ addressModel.address || "Non defini" }}</pre></span> <span editable-text="addressModel.zip" e-class="form-control" e-name="zip" e-placeholder="@(companies:Zip)" e-title="@(companies:Zip)">{{addressModel.zip}}</span> <span editable-text="addressModel.town" e-class="form-control" e-name="town" e-placeholder="@(companies:Town)" e-title="@(companies:Town)">{{addressModel.town}}</span> </address> </div> After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
3
<div class="well"> <address> <strong>{{addressModel.client.name || addressModel.supplier.name || addressModel.societe.name || addressModel.name}}</strong><br> <span editable-textarea="addressModel.address" e-name="address" e-rows="4" e-cols="400" e-required e-class="form-control"><pre>{{ addressModel.address || "Non defini" }}</pre></span> <span editable-text="addressModel.zip" e-class="form-control" e-name="zip" e-placeholder="@(companies:Zip)" e-title="@(companies:Zip)">{{addressModel.zip}}</span> <span editable-text="addressModel.town" e-class="form-control" e-name="town" e-placeholder="@(companies:Town)" e-title="@(companies:Town)">{{addressModel.town}}</span> </address> </div>
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: # This shell script executes Slurm jobs for running predictions # with convolutional neural network with # adaptive threshold and mixture of experts side channel # on BirdVox-70k with PCEN input. # Trial ID: 8. # Augmentation kind: all. sbatch 057_aug-all_test-unit01_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit01_trial-8_predict-unit10.sbatch sbatch 057_aug-all_test-unit01_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit10.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit10.sbatch After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
2
# This shell script executes Slurm jobs for running predictions # with convolutional neural network with # adaptive threshold and mixture of experts side channel # on BirdVox-70k with PCEN input. # Trial ID: 8. # Augmentation kind: all. sbatch 057_aug-all_test-unit01_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit01_trial-8_predict-unit10.sbatch sbatch 057_aug-all_test-unit01_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit10.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit02_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit01.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit03_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit02.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit05_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit03.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit07_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit05.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit07.sbatch sbatch 057_aug-all_test-unit10_trial-8_predict-unit10.sbatch
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package window import ( "github.com/matthewmueller/joy/dom/htmlallcollection" "github.com/matthewmueller/joy/dom/location" "github.com/matthewmueller/joy/dom/visibilitystate" "github.com/matthewmueller/joy/dom/xpathnsresolver" ) // Document interface // js:"Document" type Document interface { Node // QuerySelector // js:"querySelector" // jsrewrite:"$_.querySelector($1)" QuerySelector(selectors string) (e Element) // QuerySelectorAll // js:"querySelectorAll" // jsrewrite:"$_.querySelectorAll($1)" QuerySelectorAll(selectors string) (n *NodeList) // CreateEvent // js:"createEvent" // jsrewrite:"$_.createEvent($1)" CreateEvent(eventInterface string) (e Event) // AdoptNode // js:"adoptNode" // jsrewrite:"$_.adoptNode($1)" AdoptNode(source Node) (n Node) // CaptureEvents // js:"captureEvents" // jsrewrite:"$_.captureEvents()" CaptureEvents() // CaretRangeFromPoint // js:"caretRangeFromPoint" // jsrewrite:"$_.caretRangeFromPoint($1, $2)" CaretRangeFromPoint(x float32, y float32) (r *Range) // Clear // js:"clear" // jsrewrite:"$_.clear()" Clear() // Close Closes an output stream and forces the sent data to display. // js:"close" // jsrewrite:"$_.close()" Close() // CreateAttribute Creates an attribute object with a specified name. // * @param name String that sets the attribute object's name. // js:"createAttribute" // jsrewrite:"$_.createAttribute($1)" CreateAttribute(name string) (a *Attr) // CreateAttributeNS // js:"createAttributeNS" // jsrewrite:"$_.createAttributeNS($1, $2)" CreateAttributeNS(namespaceURI string, qualifiedName string) (a *Attr) // CreateCDATASection // js:"createCDATASection" // jsrewrite:"$_.createCDATASection($1)" CreateCDATASection(data string) (c *CDATASection) // CreateComment Creates a comment object with the specified data. // * @param data Sets the comment object's data. // js:"createComment" // jsrewrite:"$_.createComment($1)" CreateComment(data string) (c *Comment) After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
4
package window import ( "github.com/matthewmueller/joy/dom/htmlallcollection" "github.com/matthewmueller/joy/dom/location" "github.com/matthewmueller/joy/dom/visibilitystate" "github.com/matthewmueller/joy/dom/xpathnsresolver" ) // Document interface // js:"Document" type Document interface { Node // QuerySelector // js:"querySelector" // jsrewrite:"$_.querySelector($1)" QuerySelector(selectors string) (e Element) // QuerySelectorAll // js:"querySelectorAll" // jsrewrite:"$_.querySelectorAll($1)" QuerySelectorAll(selectors string) (n *NodeList) // CreateEvent // js:"createEvent" // jsrewrite:"$_.createEvent($1)" CreateEvent(eventInterface string) (e Event) // AdoptNode // js:"adoptNode" // jsrewrite:"$_.adoptNode($1)" AdoptNode(source Node) (n Node) // CaptureEvents // js:"captureEvents" // jsrewrite:"$_.captureEvents()" CaptureEvents() // CaretRangeFromPoint // js:"caretRangeFromPoint" // jsrewrite:"$_.caretRangeFromPoint($1, $2)" CaretRangeFromPoint(x float32, y float32) (r *Range) // Clear // js:"clear" // jsrewrite:"$_.clear()" Clear() // Close Closes an output stream and forces the sent data to display. // js:"close" // jsrewrite:"$_.close()" Close() // CreateAttribute Creates an attribute object with a specified name. // * @param name String that sets the attribute object's name. // js:"createAttribute" // jsrewrite:"$_.createAttribute($1)" CreateAttribute(name string) (a *Attr) // CreateAttributeNS // js:"createAttributeNS" // jsrewrite:"$_.createAttributeNS($1, $2)" CreateAttributeNS(namespaceURI string, qualifiedName string) (a *Attr) // CreateCDATASection // js:"createCDATASection" // jsrewrite:"$_.createCDATASection($1)" CreateCDATASection(data string) (c *CDATASection) // CreateComment Creates a comment object with the specified data. // * @param data Sets the comment object's data. // js:"createComment" // jsrewrite:"$_.createComment($1)" CreateComment(data string) (c *Comment) // CreateDocumentFragment Creates a new document. // js:"createDocumentFragment" // jsrewrite:"$_.createDocumentFragment()" CreateDocumentFragment() (d *DocumentFragment) // CreateElement Creates an instance of the element for the specified tag. // * @param tagName The name of an element. // js:"createElement" // jsrewrite:"$_.createElement($1)" CreateElement(tagName string) (e Element) // CreateElementNS // js:"createElementNS" // jsrewrite:"$_.createElementNS($1, $2)" CreateElementNS(namespaceURI string, qualifiedName string) (e Element) // CreateExpression // js:"createExpression" // jsrewrite:"$_.createExpression($1, $2)" CreateExpression(expression string, resolver *xpathnsresolver.XPathNSResolver) (x *XPathExpression) // CreateNodeIterator Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. // * @param root The root element or node to start traversing on. // * @param whatToShow The type of nodes or elements to appear in the node list // * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. // * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. // js:"createNodeIterator" // jsrewrite:"$_.createNodeIterator($1, $2, $3, $4)" CreateNodeIterator(root Node, whatToShow *uint, filter *NodeFilter, entityReferenceExpansion *bool) (n *NodeIterator) // CreateNSResolver // js:"createNSResolver" // jsrewrite:"$_.createNSResolver($1)" CreateNSResolver(nodeResolver Node) (x *xpathnsresolver.XPathNSResolver) // CreateProcessingInstruction // js:"createProcessingInstruction" // jsrewrite:"$_.createProcessingInstruction($1, $2)" CreateProcessingInstruction(target string, data string) (p *ProcessingInstruction) // CreateRange Returns an empty range object that has both of its boundary points positioned at the beginning of the document. // js:"createRange" // jsrewrite:"$_.createRange()" CreateRange() (r *Range) // CreateTextNode Creates a text string from the specified value. // * @param data String that specifies the nodeValue property of the text node. // js:"createTextNode" // jsrewrite:"$_.createTextNode($1)" CreateTextNode(data string) (t Text) // CreateTouch // js:"createTouch" // jsrewrite:"$_.createTouch($1, $2, $3, $4, $5, $6, $7)" CreateTouch(view *Window, target EventTarget, identifier int, pageX int, pageY int, screenX int, screenY int) (t *Touch) // CreateTouchList // js:"createTouchList" // jsrewrite:"$_.createTouchList($1)" CreateTouchList(touches *Touch) (t *TouchList) // CreateTreeWalker Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. // * @param root The root element or node to start traversing on. // * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. // * @param filter A custom NodeFilter function to use. // * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. // js:"createTreeWalker" // jsrewrite:"$_.createTreeWalker($1, $2, $3, $4)" CreateTreeWalker(root Node, whatToShow *uint, filter *NodeFilter, entityReferenceExpansion *bool) (t *TreeWalker) // ElementFromPoint Returns the element for the specified x coordinate and the specified y coordinate. // * @param x The x-offset // * @param y The y-offset // js:"elementFromPoint" // jsrewrite:"$_.elementFromPoint($1, $2)" ElementFromPoint(x int, y int) (e Element) // Evaluate // js:"evaluate" // jsrewrite:"$_.evaluate($1, $2, $3, $4, $5)" Evaluate(expression string, contextNode Node, resolver *xpathnsresolver.XPathNSResolver, kind uint8, result *XPathResult) (x *XPathResult) // ExecCommand Executes a command on the current document, current selection, or the given range. // * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. // * @param showUI Display the user interface, defaults to false. // * @param value Value to assign. // js:"execCommand" // jsrewrite:"$_.execCommand($1, $2, $3)" ExecCommand(commandId string, showUI *bool, value *interface{}) (b bool) // ExecCommandShowHelp Displays help information for the given command identifier. // * @param commandId Displays help information for the given command identifier. // js:"execCommandShowHelp" // jsrewrite:"$_.execCommandShowHelp($1)" ExecCommandShowHelp(commandId string) (b bool) // ExitFullscreen // js:"exitFullscreen" // jsrewrite:"$_.exitFullscreen()" ExitFullscreen() // ExitPointerLock // js:"exitPointerLock" // jsrewrite:"$_.exitPointerLock()" ExitPointerLock() // Focus Causes the element to receive the focus and executes the code specified by the onfocus event. // js:"focus" // jsrewrite:"$_.focus()" Focus() // GetElementByID Returns a reference to the first object with the specified value of the ID or NAME attribute. // * @param elementId String that specifies the ID value. Case-insensitive. // js:"getElementById" // jsrewrite:"$_.getElementById($1)" GetElementByID(elementId string) (e Element) // GetElementsByClassName // js:"getElementsByClassName" // jsrewrite:"$_.getElementsByClassName($1)" GetElementsByClassName(classNames string) (n *NodeList) // GetElementsByName Gets a collection of objects based on the value of the NAME or ID attribute. // * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. // js:"getElementsByName" // jsrewrite:"$_.getElementsByName($1)" GetElementsByName(elementName string) (n *NodeList) // GetElementsByTagName Retrieves a collection of objects based on the specified element name. // * @param name Specifies the name of an element. // js:"getElementsByTagName" // jsrewrite:"$_.getElementsByTagName($1)" GetElementsByTagName(tagname string) (n *NodeList) // GetElementsByTagNameNS // js:"getElementsByTagNameNS" // jsrewrite:"$_.getElementsByTagNameNS($1, $2)" GetElementsByTagNameNS(namespaceURI string, localName string) (n *NodeList) // GetSelection Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. // js:"getSelection" // jsrewrite:"$_.getSelection()" GetSelection() (s *Selection) // HasFocus Gets a value indicating whether the object currently has focus. // js:"hasFocus" // jsrewrite:"$_.hasFocus()" HasFocus() (b bool) // ImportNode // js:"importNode" // jsrewrite:"$_.importNode($1, $2)" ImportNode(importedNode Node, deep bool) (n Node) // MsElementsFromPoint // js:"msElementsFromPoint" // jsrewrite:"$_.msElementsFromPoint($1, $2)" MsElementsFromPoint(x float32, y float32) (n *NodeList) // MsElementsFromRect // js:"msElementsFromRect" // jsrewrite:"$_.msElementsFromRect($1, $2, $3, $4)" MsElementsFromRect(left float32, top float32, width float32, height float32) (n *NodeList) // Open Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. // * @param url Specifies a MIME type for the document. // * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. // * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. // * @param replace Specifies whether the existing entry for the document is replaced in the history list. // js:"open" // jsrewrite:"$_.open($1, $2, $3, $4)" Open(url *string, name *string, features *string, replace *bool) (i interface{}) // QueryCommandEnabled Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. // * @param commandId Specifies a command identifier. // js:"queryCommandEnabled" // jsrewrite:"$_.queryCommandEnabled($1)" QueryCommandEnabled(commandId string) (b bool) // QueryCommandIndeterm Returns a Boolean value that indicates whether the specified command is in the indeterminate state. // * @param commandId String that specifies a command identifier. // js:"queryCommandIndeterm" // jsrewrite:"$_.queryCommandIndeterm($1)" QueryCommandIndeterm(commandId string) (b bool) // QueryCommandState Returns a Boolean value that indicates the current state of the command. // * @param commandId String that specifies a command identifier. // js:"queryCommandState" // jsrewrite:"$_.queryCommandState($1)" QueryCommandState(commandId string) (b bool) // QueryCommandSupported Returns a Boolean value that indicates whether the current command is supported on the current range. // * @param commandId Specifies a command identifier. // js:"queryCommandSupported" // jsrewrite:"$_.queryCommandSupported($1)" QueryCommandSupported(commandId string) (b bool) // QueryCommandText Retrieves the string associated with a command. // * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. // js:"queryCommandText" // jsrewrite:"$_.queryCommandText($1)" QueryCommandText(commandId string) (s string) // QueryCommandValue Returns the current value of the document, range, or current selection for the given command. // * @param commandId String that specifies a command identifier. // js:"queryCommandValue" // jsrewrite:"$_.queryCommandValue($1)" QueryCommandValue(commandId string) (s string) // ReleaseEvents // js:"releaseEvents" // jsrewrite:"$_.releaseEvents()" ReleaseEvents() // UpdateSettings Allows updating the print settings for the page. // js:"updateSettings" // jsrewrite:"$_.updateSettings()" UpdateSettings() // WebkitCancelFullScreen // js:"webkitCancelFullScreen" // jsrewrite:"$_.webkitCancelFullScreen()" WebkitCancelFullScreen() // WebkitExitFullscreen // js:"webkitExitFullscreen" // jsrewrite:"$_.webkitExitFullscreen()" WebkitExitFullscreen() // Write Writes one or more HTML expressions to a document in the specified window. // * @param content Specifies the text and HTML tags to write. // js:"write" // jsrewrite:"$_.write($1)" Write(content string) // Writeln Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. // * @param content The text and HTML tags to write. // js:"writeln" // jsrewrite:"$_.writeln($1)" Writeln(content string) // Onpointercancel prop // js:"onpointercancel" // jsrewrite:"$_.onpointercancel" Onpointercancel() (onpointercancel func(Event)) // SetOnpointercancel prop // js:"onpointercancel" // jsrewrite:"$_.onpointercancel = $1" SetOnpointercancel(onpointercancel func(Event)) // Onpointerdown prop // js:"onpointerdown" // jsrewrite:"$_.onpointerdown" Onpointerdown() (onpointerdown func(Event)) // SetOnpointerdown prop // js:"onpointerdown" // jsrewrite:"$_.onpointerdown = $1" SetOnpointerdown(onpointerdown func(Event)) // Onpointerenter prop // js:"onpointerenter" // jsrewrite:"$_.onpointerenter" Onpointerenter() (onpointerenter func(Event)) // SetOnpointerenter prop // js:"onpointerenter" // jsrewrite:"$_.onpointerenter = $1" SetOnpointerenter(onpointerenter func(Event)) // Onpointerleave prop // js:"onpointerleave" // jsrewrite:"$_.onpointerleave" Onpointerleave() (onpointerleave func(Event)) // SetOnpointerleave prop // js:"onpointerleave" // jsrewrite:"$_.onpointerleave = $1" SetOnpointerleave(onpointerleave func(Event)) // Onpointermove prop // js:"onpointermove" // jsrewrite:"$_.onpointermove" Onpointermove() (onpointermove func(Event)) // SetOnpointermove prop // js:"onpointermove" // jsrewrite:"$_.onpointermove = $1" SetOnpointermove(onpointermove func(Event)) // Onpointerout prop // js:"onpointerout" // jsrewrite:"$_.onpointerout" Onpointerout() (onpointerout func(Event)) // SetOnpointerout prop // js:"onpointerout" // jsrewrite:"$_.onpointerout = $1" SetOnpointerout(onpointerout func(Event)) // Onpointerover prop // js:"onpointerover" // jsrewrite:"$_.onpointerover" Onpointerover() (onpointerover func(Event)) // SetOnpointerover prop // js:"onpointerover" // jsrewrite:"$_.onpointerover = $1" SetOnpointerover(onpointerover func(Event)) // Onpointerup prop // js:"onpointerup" // jsrewrite:"$_.onpointerup" Onpointerup() (onpointerup func(Event)) // SetOnpointerup prop // js:"onpointerup" // jsrewrite:"$_.onpointerup = $1" SetOnpointerup(onpointerup func(Event)) // Onwheel prop // js:"onwheel" // jsrewrite:"$_.onwheel" Onwheel() (onwheel func(Event)) // SetOnwheel prop // js:"onwheel" // jsrewrite:"$_.onwheel = $1" SetOnwheel(onwheel func(Event)) // ActiveElement prop Gets the object that has the focus when the parent document has focus. // js:"activeElement" // jsrewrite:"$_.activeElement" ActiveElement() (activeElement Element) // AlinkColor prop Sets or gets the color of all active links in the document. // js:"alinkColor" // jsrewrite:"$_.alinkColor" AlinkColor() (alinkColor string) // SetAlinkColor prop Sets or gets the color of all active links in the document. // js:"alinkColor" // jsrewrite:"$_.alinkColor = $1" SetAlinkColor(alinkColor string) // All prop Returns a reference to the collection of elements contained by the object. // js:"all" // jsrewrite:"$_.all" All() (all *htmlallcollection.HTMLAllCollection) // Anchors prop Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. // js:"anchors" // jsrewrite:"$_.anchors" Anchors() (anchors HTMLCollection) // Applets prop Retrieves a collection of all applet objects in the document. // js:"applets" // jsrewrite:"$_.applets" Applets() (applets HTMLCollection) // BgColor prop Deprecated. Sets or retrieves a value that indicates the background color behind the object. // js:"bgColor" // jsrewrite:"$_.bgColor" BgColor() (bgColor string) // SetBgColor prop Deprecated. Sets or retrieves a value that indicates the background color behind the object. // js:"bgColor" // jsrewrite:"$_.bgColor = $1" SetBgColor(bgColor string) // Body prop Specifies the beginning and end of the document body. // js:"body" // jsrewrite:"$_.body" Body() (body HTMLElement) // SetBody prop Specifies the beginning and end of the document body. // js:"body" // jsrewrite:"$_.body = $1" SetBody(body HTMLElement) // CharacterSet prop // js:"characterSet" // jsrewrite:"$_.characterSet" CharacterSet() (characterSet string) // Charset prop Gets or sets the character set used to encode the object. // js:"charset" // jsrewrite:"$_.charset" Charset() (charset string) // SetCharset prop Gets or sets the character set used to encode the object. // js:"charset" // jsrewrite:"$_.charset = $1" SetCharset(charset string) // CompatMode prop Gets a value that indicates whether standards-compliant mode is switched on for the object. // js:"compatMode" // jsrewrite:"$_.compatMode" CompatMode() (compatMode string) // Cookie prop // js:"cookie" // jsrewrite:"$_.cookie" Cookie() (cookie string) // SetCookie prop // js:"cookie" // jsrewrite:"$_.cookie = $1" SetCookie(cookie string) // CurrentScript prop // js:"currentScript" // jsrewrite:"$_.currentScript" CurrentScript() (currentScript interface{}) // DefaultView prop // js:"defaultView" // jsrewrite:"$_.defaultView" DefaultView() (defaultView *Window) // DesignMode prop Sets or gets a value that indicates whether the document can be edited. // js:"designMode" // jsrewrite:"$_.designMode" DesignMode() (designMode string) // SetDesignMode prop Sets or gets a value that indicates whether the document can be edited. // js:"designMode" // jsrewrite:"$_.designMode = $1" SetDesignMode(designMode string) // Dir prop Sets or retrieves a value that indicates the reading order of the object. // js:"dir" // jsrewrite:"$_.dir" Dir() (dir string) // SetDir prop Sets or retrieves a value that indicates the reading order of the object. // js:"dir" // jsrewrite:"$_.dir = $1" SetDir(dir string) // Doctype prop Gets an object representing the document type declaration associated with the current document. // js:"doctype" // jsrewrite:"$_.doctype" Doctype() (doctype *DocumentType) // DocumentElement prop Gets a reference to the root node of the document. // js:"documentElement" // jsrewrite:"$_.documentElement" DocumentElement() (documentElement Element) // Domain prop Sets or gets the security domain of the document. // js:"domain" // jsrewrite:"$_.domain" Domain() (domain string) // SetDomain prop Sets or gets the security domain of the document. // js:"domain" // jsrewrite:"$_.domain = $1" SetDomain(domain string) // Embeds prop Retrieves a collection of all embed objects in the document. // js:"embeds" // jsrewrite:"$_.embeds" Embeds() (embeds HTMLCollection) // FgColor prop Sets or gets the foreground (text) color of the document. // js:"fgColor" // jsrewrite:"$_.fgColor" FgColor() (fgColor string) // SetFgColor prop Sets or gets the foreground (text) color of the document. // js:"fgColor" // jsrewrite:"$_.fgColor = $1" SetFgColor(fgColor string) // Forms prop Retrieves a collection, in source order, of all form objects in the document. // js:"forms" // jsrewrite:"$_.forms" Forms() (forms HTMLCollection) // FullscreenElement prop // js:"fullscreenElement" // jsrewrite:"$_.fullscreenElement" FullscreenElement() (fullscreenElement Element) // FullscreenEnabled prop // js:"fullscreenEnabled" // jsrewrite:"$_.fullscreenEnabled" FullscreenEnabled() (fullscreenEnabled bool) // Head prop // js:"head" // jsrewrite:"$_.head" Head() (head *HTMLHeadElement) // Hidden prop // js:"hidden" // jsrewrite:"$_.hidden" Hidden() (hidden bool) // Images prop Retrieves a collection, in source order, of img objects in the document. // js:"images" // jsrewrite:"$_.images" Images() (images HTMLCollection) // Implementation prop Gets the implementation object of the current document. // js:"implementation" // jsrewrite:"$_.implementation" Implementation() (implementation *DOMImplementation) // InputEncoding prop Returns the character encoding used to create the webpage that is loaded into the document object. // js:"inputEncoding" // jsrewrite:"$_.inputEncoding" InputEncoding() (inputEncoding string) // LastModified prop Gets the date that the page was last modified, if the page supplies one. // js:"lastModified" // jsrewrite:"$_.lastModified" LastModified() (lastModified string) // LinkColor prop Sets or gets the color of the document links. // js:"linkColor" // jsrewrite:"$_.linkColor" LinkColor() (linkColor string) // SetLinkColor prop Sets or gets the color of the document links. // js:"linkColor" // jsrewrite:"$_.linkColor = $1" SetLinkColor(linkColor string) // Links prop Retrieves a collection of all a objects that specify the href property and all area objects in the document. // js:"links" // jsrewrite:"$_.links" Links() (links HTMLCollection) // Location prop Contains information about the current URL. // js:"location" // jsrewrite:"$_.location" Location() (location *location.Location) // MsCapsLockWarningOff prop // js:"msCapsLockWarningOff" // jsrewrite:"$_.msCapsLockWarningOff" MsCapsLockWarningOff() (msCapsLockWarningOff bool) // SetMsCapsLockWarningOff prop // js:"msCapsLockWarningOff" // jsrewrite:"$_.msCapsLockWarningOff = $1" SetMsCapsLockWarningOff(msCapsLockWarningOff bool) // MsCSSOMElementFloatMetrics prop // js:"msCSSOMElementFloatMetrics" // jsrewrite:"$_.msCSSOMElementFloatMetrics" MsCSSOMElementFloatMetrics() (msCSSOMElementFloatMetrics bool) // SetMsCSSOMElementFloatMetrics prop // js:"msCSSOMElementFloatMetrics" // jsrewrite:"$_.msCSSOMElementFloatMetrics = $1" SetMsCSSOMElementFloatMetrics(msCSSOMElementFloatMetrics bool) // Onabort prop Fires when the user aborts the download. // * @param ev The event. // js:"onabort" // jsrewrite:"$_.onabort" Onabort() (onabort func(Event)) // SetOnabort prop Fires when the user aborts the download. // * @param ev The event. // js:"onabort" // jsrewrite:"$_.onabort = $1" SetOnabort(onabort func(Event)) // Onactivate prop Fires when the object is set as the active element. // * @param ev The event. // js:"onactivate" // jsrewrite:"$_.onactivate" Onactivate() (onactivate func(Event)) // SetOnactivate prop Fires when the object is set as the active element. // * @param ev The event. // js:"onactivate" // jsrewrite:"$_.onactivate = $1" SetOnactivate(onactivate func(Event)) // Onbeforeactivate prop Fires immediately before the object is set as the active element. // * @param ev The event. // js:"onbeforeactivate" // jsrewrite:"$_.onbeforeactivate" Onbeforeactivate() (onbeforeactivate func(Event)) // SetOnbeforeactivate prop Fires immediately before the object is set as the active element. // * @param ev The event. // js:"onbeforeactivate" // jsrewrite:"$_.onbeforeactivate = $1" SetOnbeforeactivate(onbeforeactivate func(Event)) // Onbeforedeactivate prop Fires immediately before the activeElement is changed from the current object to another object in the parent document. // * @param ev The event. // js:"onbeforedeactivate" // jsrewrite:"$_.onbeforedeactivate" Onbeforedeactivate() (onbeforedeactivate func(Event)) // SetOnbeforedeactivate prop Fires immediately before the activeElement is changed from the current object to another object in the parent document. // * @param ev The event. // js:"onbeforedeactivate" // jsrewrite:"$_.onbeforedeactivate = $1" SetOnbeforedeactivate(onbeforedeactivate func(Event)) // Onblur prop Fires when the object loses the input focus. // * @param ev The focus event. // js:"onblur" // jsrewrite:"$_.onblur" Onblur() (onblur func(Event)) // SetOnblur prop Fires when the object loses the input focus. // * @param ev The focus event. // js:"onblur" // jsrewrite:"$_.onblur = $1" SetOnblur(onblur func(Event)) // Oncanplay prop Occurs when playback is possible, but would require further buffering. // * @param ev The event. // js:"oncanplay" // jsrewrite:"$_.oncanplay" Oncanplay() (oncanplay func(Event)) // SetOncanplay prop Occurs when playback is possible, but would require further buffering. // * @param ev The event. // js:"oncanplay" // jsrewrite:"$_.oncanplay = $1" SetOncanplay(oncanplay func(Event)) // Oncanplaythrough prop // js:"oncanplaythrough" // jsrewrite:"$_.oncanplaythrough" Oncanplaythrough() (oncanplaythrough func(Event)) // SetOncanplaythrough prop // js:"oncanplaythrough" // jsrewrite:"$_.oncanplaythrough = $1" SetOncanplaythrough(oncanplaythrough func(Event)) // Onchange prop Fires when the contents of the object or selection have changed. // * @param ev The event. // js:"onchange" // jsrewrite:"$_.onchange" Onchange() (onchange func(Event)) // SetOnchange prop Fires when the contents of the object or selection have changed. // * @param ev The event. // js:"onchange" // jsrewrite:"$_.onchange = $1" SetOnchange(onchange func(Event)) // Onclick prop Fires when the user clicks the left mouse button on the object // * @param ev The mouse event. // js:"onclick" // jsrewrite:"$_.onclick" Onclick() (onclick func(Event)) // SetOnclick prop Fires when the user clicks the left mouse button on the object // * @param ev The mouse event. // js:"onclick" // jsrewrite:"$_.onclick = $1" SetOnclick(onclick func(Event)) // Oncontextmenu prop Fires when the user clicks the right mouse button in the client area, opening the context menu. // * @param ev The mouse event. // js:"oncontextmenu" // jsrewrite:"$_.oncontextmenu" Oncontextmenu() (oncontextmenu func(Event)) // SetOncontextmenu prop Fires when the user clicks the right mouse button in the client area, opening the context menu. // * @param ev The mouse event. // js:"oncontextmenu" // jsrewrite:"$_.oncontextmenu = $1" SetOncontextmenu(oncontextmenu func(Event)) // Ondblclick prop Fires when the user double-clicks the object. // * @param ev The mouse event. // js:"ondblclick" // jsrewrite:"$_.ondblclick" Ondblclick() (ondblclick func(Event)) // SetOndblclick prop Fires when the user double-clicks the object. // * @param ev The mouse event. // js:"ondblclick" // jsrewrite:"$_.ondblclick = $1" SetOndblclick(ondblclick func(Event)) // Ondeactivate prop Fires when the activeElement is changed from the current object to another object in the parent document. // * @param ev The UI Event // js:"ondeactivate" // jsrewrite:"$_.ondeactivate" Ondeactivate() (ondeactivate func(Event)) // SetOndeactivate prop Fires when the activeElement is changed from the current object to another object in the parent document. // * @param ev The UI Event // js:"ondeactivate" // jsrewrite:"$_.ondeactivate = $1" SetOndeactivate(ondeactivate func(Event)) // Ondrag prop Fires on the source object continuously during a drag operation. // * @param ev The event. // js:"ondrag" // jsrewrite:"$_.ondrag" Ondrag() (ondrag func(Event)) // SetOndrag prop Fires on the source object continuously during a drag operation. // * @param ev The event. // js:"ondrag" // jsrewrite:"$_.ondrag = $1" SetOndrag(ondrag func(Event)) // Ondragend prop Fires on the source object when the user releases the mouse at the close of a drag operation. // * @param ev The event. // js:"ondragend" // jsrewrite:"$_.ondragend" Ondragend() (ondragend func(Event)) // SetOndragend prop Fires on the source object when the user releases the mouse at the close of a drag operation. // * @param ev The event. // js:"ondragend" // jsrewrite:"$_.ondragend = $1" SetOndragend(ondragend func(Event)) // Ondragenter prop Fires on the target element when the user drags the object to a valid drop target. // * @param ev The drag event. // js:"ondragenter" // jsrewrite:"$_.ondragenter" Ondragenter() (ondragenter func(Event)) // SetOndragenter prop Fires on the target element when the user drags the object to a valid drop target. // * @param ev The drag event. // js:"ondragenter" // jsrewrite:"$_.ondragenter = $1" SetOndragenter(ondragenter func(Event)) // Ondragleave prop Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. // * @param ev The drag event. // js:"ondragleave" // jsrewrite:"$_.ondragleave" Ondragleave() (ondragleave func(Event)) // SetOndragleave prop Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. // * @param ev The drag event. // js:"ondragleave" // jsrewrite:"$_.ondragleave = $1" SetOndragleave(ondragleave func(Event)) // Ondragover prop Fires on the target element continuously while the user drags the object over a valid drop target. // * @param ev The event. // js:"ondragover" // jsrewrite:"$_.ondragover" Ondragover() (ondragover func(Event)) // SetOndragover prop Fires on the target element continuously while the user drags the object over a valid drop target. // * @param ev The event. // js:"ondragover" // jsrewrite:"$_.ondragover = $1" SetOndragover(ondragover func(Event)) // Ondragstart prop Fires on the source object when the user starts to drag a text selection or selected object. // * @param ev The event. // js:"ondragstart" // jsrewrite:"$_.ondragstart" Ondragstart() (ondragstart func(Event)) // SetOndragstart prop Fires on the source object when the user starts to drag a text selection or selected object. // * @param ev The event. // js:"ondragstart" // jsrewrite:"$_.ondragstart = $1" SetOndragstart(ondragstart func(Event)) // Ondrop prop // js:"ondrop" // jsrewrite:"$_.ondrop" Ondrop() (ondrop func(Event)) // SetOndrop prop // js:"ondrop" // jsrewrite:"$_.ondrop = $1" SetOndrop(ondrop func(Event)) // Ondurationchange prop Occurs when the duration attribute is updated. // * @param ev The event. // js:"ondurationchange" // jsrewrite:"$_.ondurationchange" Ondurationchange() (ondurationchange func(Event)) // SetOndurationchange prop Occurs when the duration attribute is updated. // * @param ev The event. // js:"ondurationchange" // jsrewrite:"$_.ondurationchange = $1" SetOndurationchange(ondurationchange func(Event)) // Onemptied prop Occurs when the media element is reset to its initial state. // * @param ev The event. // js:"onemptied" // jsrewrite:"$_.onemptied" Onemptied() (onemptied func(Event)) // SetOnemptied prop Occurs when the media element is reset to its initial state. // * @param ev The event. // js:"onemptied" // jsrewrite:"$_.onemptied = $1" SetOnemptied(onemptied func(Event)) // Onended prop Occurs when the end of playback is reached. // * @param ev The event // js:"onended" // jsrewrite:"$_.onended" Onended() (onended func(Event)) // SetOnended prop Occurs when the end of playback is reached. // * @param ev The event // js:"onended" // jsrewrite:"$_.onended = $1" SetOnended(onended func(Event)) // Onerror prop Fires when an error occurs during object loading. // * @param ev The event. // js:"onerror" // jsrewrite:"$_.onerror" Onerror() (onerror func(Event)) // SetOnerror prop Fires when an error occurs during object loading. // * @param ev The event. // js:"onerror" // jsrewrite:"$_.onerror = $1" SetOnerror(onerror func(Event)) // Onfocus prop Fires when the object receives focus. // * @param ev The event. // js:"onfocus" // jsrewrite:"$_.onfocus" Onfocus() (onfocus func(Event)) // SetOnfocus prop Fires when the object receives focus. // * @param ev The event. // js:"onfocus" // jsrewrite:"$_.onfocus = $1" SetOnfocus(onfocus func(Event)) // Onfullscreenchange prop // js:"onfullscreenchange" // jsrewrite:"$_.onfullscreenchange" Onfullscreenchange() (onfullscreenchange func(Event)) // SetOnfullscreenchange prop // js:"onfullscreenchange" // jsrewrite:"$_.onfullscreenchange = $1" SetOnfullscreenchange(onfullscreenchange func(Event)) // Onfullscreenerror prop // js:"onfullscreenerror" // jsrewrite:"$_.onfullscreenerror" Onfullscreenerror() (onfullscreenerror func(Event)) // SetOnfullscreenerror prop // js:"onfullscreenerror" // jsrewrite:"$_.onfullscreenerror = $1" SetOnfullscreenerror(onfullscreenerror func(Event)) // Oninput prop // js:"oninput" // jsrewrite:"$_.oninput" Oninput() (oninput func(Event)) // SetOninput prop // js:"oninput" // jsrewrite:"$_.oninput = $1" SetOninput(oninput func(Event)) // Oninvalid prop // js:"oninvalid" // jsrewrite:"$_.oninvalid" Oninvalid() (oninvalid func(Event)) // SetOninvalid prop // js:"oninvalid" // jsrewrite:"$_.oninvalid = $1" SetOninvalid(oninvalid func(Event)) // Onkeydown prop Fires when the user presses a key. // * @param ev The keyboard event // js:"onkeydown" // jsrewrite:"$_.onkeydown" Onkeydown() (onkeydown func(Event)) // SetOnkeydown prop Fires when the user presses a key. // * @param ev The keyboard event // js:"onkeydown" // jsrewrite:"$_.onkeydown = $1" SetOnkeydown(onkeydown func(Event)) // Onkeypress prop Fires when the user presses an alphanumeric key. // * @param ev The event. // js:"onkeypress" // jsrewrite:"$_.onkeypress" Onkeypress() (onkeypress func(Event)) // SetOnkeypress prop Fires when the user presses an alphanumeric key. // * @param ev The event. // js:"onkeypress" // jsrewrite:"$_.onkeypress = $1" SetOnkeypress(onkeypress func(Event)) // Onkeyup prop Fires when the user releases a key. // * @param ev The keyboard event // js:"onkeyup" // jsrewrite:"$_.onkeyup" Onkeyup() (onkeyup func(Event)) // SetOnkeyup prop Fires when the user releases a key. // * @param ev The keyboard event // js:"onkeyup" // jsrewrite:"$_.onkeyup = $1" SetOnkeyup(onkeyup func(Event)) // Onload prop Fires immediately after the browser loads the object. // * @param ev The event. // js:"onload" // jsrewrite:"$_.onload" Onload() (onload func(Event)) // SetOnload prop Fires immediately after the browser loads the object. // * @param ev The event. // js:"onload" // jsrewrite:"$_.onload = $1" SetOnload(onload func(Event)) // Onloadeddata prop Occurs when media data is loaded at the current playback position. // * @param ev The event. // js:"onloadeddata" // jsrewrite:"$_.onloadeddata" Onloadeddata() (onloadeddata func(Event)) // SetOnloadeddata prop Occurs when media data is loaded at the current playback position. // * @param ev The event. // js:"onloadeddata" // jsrewrite:"$_.onloadeddata = $1" SetOnloadeddata(onloadeddata func(Event)) // Onloadedmetadata prop Occurs when the duration and dimensions of the media have been determined. // * @param ev The event. // js:"onloadedmetadata" // jsrewrite:"$_.onloadedmetadata" Onloadedmetadata() (onloadedmetadata func(Event)) // SetOnloadedmetadata prop Occurs when the duration and dimensions of the media have been determined. // * @param ev The event. // js:"onloadedmetadata" // jsrewrite:"$_.onloadedmetadata = $1" SetOnloadedmetadata(onloadedmetadata func(Event)) // Onloadstart prop Occurs when Internet Explorer begins looking for media data. // * @param ev The event. // js:"onloadstart" // jsrewrite:"$_.onloadstart" Onloadstart() (onloadstart func(Event)) // SetOnloadstart prop Occurs when Internet Explorer begins looking for media data. // * @param ev The event. // js:"onloadstart" // jsrewrite:"$_.onloadstart = $1" SetOnloadstart(onloadstart func(Event)) // Onmousedown prop Fires when the user clicks the object with either mouse button. // * @param ev The mouse event. // js:"onmousedown" // jsrewrite:"$_.onmousedown" Onmousedown() (onmousedown func(Event)) // SetOnmousedown prop Fires when the user clicks the object with either mouse button. // * @param ev The mouse event. // js:"onmousedown" // jsrewrite:"$_.onmousedown = $1" SetOnmousedown(onmousedown func(Event)) // Onmousemove prop Fires when the user moves the mouse over the object. // * @param ev The mouse event. // js:"onmousemove" // jsrewrite:"$_.onmousemove" Onmousemove() (onmousemove func(Event)) // SetOnmousemove prop Fires when the user moves the mouse over the object. // * @param ev The mouse event. // js:"onmousemove" // jsrewrite:"$_.onmousemove = $1" SetOnmousemove(onmousemove func(Event)) // Onmouseout prop Fires when the user moves the mouse pointer outside the boundaries of the object. // * @param ev The mouse event. // js:"onmouseout" // jsrewrite:"$_.onmouseout" Onmouseout() (onmouseout func(Event)) // SetOnmouseout prop Fires when the user moves the mouse pointer outside the boundaries of the object. // * @param ev The mouse event. // js:"onmouseout" // jsrewrite:"$_.onmouseout = $1" SetOnmouseout(onmouseout func(Event)) // Onmouseover prop Fires when the user moves the mouse pointer into the object. // * @param ev The mouse event. // js:"onmouseover" // jsrewrite:"$_.onmouseover" Onmouseover() (onmouseover func(Event)) // SetOnmouseover prop Fires when the user moves the mouse pointer into the object. // * @param ev The mouse event. // js:"onmouseover" // jsrewrite:"$_.onmouseover = $1" SetOnmouseover(onmouseover func(Event)) // Onmouseup prop Fires when the user releases a mouse button while the mouse is over the object. // * @param ev The mouse event. // js:"onmouseup" // jsrewrite:"$_.onmouseup" Onmouseup() (onmouseup func(Event)) // SetOnmouseup prop Fires when the user releases a mouse button while the mouse is over the object. // * @param ev The mouse event. // js:"onmouseup" // jsrewrite:"$_.onmouseup = $1" SetOnmouseup(onmouseup func(Event)) // Onmousewheel prop Fires when the wheel button is rotated. // * @param ev The mouse event // js:"onmousewheel" // jsrewrite:"$_.onmousewheel" Onmousewheel() (onmousewheel func(Event)) // SetOnmousewheel prop Fires when the wheel button is rotated. // * @param ev The mouse event // js:"onmousewheel" // jsrewrite:"$_.onmousewheel = $1" SetOnmousewheel(onmousewheel func(Event)) // Onmscontentzoom prop // js:"onmscontentzoom" // jsrewrite:"$_.onmscontentzoom" Onmscontentzoom() (onmscontentzoom func(UIEvent)) // SetOnmscontentzoom prop // js:"onmscontentzoom" // jsrewrite:"$_.onmscontentzoom = $1" SetOnmscontentzoom(onmscontentzoom func(UIEvent)) // Onmsgesturechange prop // js:"onmsgesturechange" // jsrewrite:"$_.onmsgesturechange" Onmsgesturechange() (onmsgesturechange func(Event)) // SetOnmsgesturechange prop // js:"onmsgesturechange" // jsrewrite:"$_.onmsgesturechange = $1" SetOnmsgesturechange(onmsgesturechange func(Event)) // Onmsgesturedoubletap prop // js:"onmsgesturedoubletap" // jsrewrite:"$_.onmsgesturedoubletap" Onmsgesturedoubletap() (onmsgesturedoubletap func(Event)) // SetOnmsgesturedoubletap prop // js:"onmsgesturedoubletap" // jsrewrite:"$_.onmsgesturedoubletap = $1" SetOnmsgesturedoubletap(onmsgesturedoubletap func(Event)) // Onmsgestureend prop // js:"onmsgestureend" // jsrewrite:"$_.onmsgestureend" Onmsgestureend() (onmsgestureend func(Event)) // SetOnmsgestureend prop // js:"onmsgestureend" // jsrewrite:"$_.onmsgestureend = $1" SetOnmsgestureend(onmsgestureend func(Event)) // Onmsgesturehold prop // js:"onmsgesturehold" // jsrewrite:"$_.onmsgesturehold" Onmsgesturehold() (onmsgesturehold func(Event)) // SetOnmsgesturehold prop // js:"onmsgesturehold" // jsrewrite:"$_.onmsgesturehold = $1" SetOnmsgesturehold(onmsgesturehold func(Event)) // Onmsgesturestart prop // js:"onmsgesturestart" // jsrewrite:"$_.onmsgesturestart" Onmsgesturestart() (onmsgesturestart func(Event)) // SetOnmsgesturestart prop // js:"onmsgesturestart" // jsrewrite:"$_.onmsgesturestart = $1" SetOnmsgesturestart(onmsgesturestart func(Event)) // Onmsgesturetap prop // js:"onmsgesturetap" // jsrewrite:"$_.onmsgesturetap" Onmsgesturetap() (onmsgesturetap func(Event)) // SetOnmsgesturetap prop // js:"onmsgesturetap" // jsrewrite:"$_.onmsgesturetap = $1" SetOnmsgesturetap(onmsgesturetap func(Event)) // Onmsinertiastart prop // js:"onmsinertiastart" // jsrewrite:"$_.onmsinertiastart" Onmsinertiastart() (onmsinertiastart func(Event)) // SetOnmsinertiastart prop // js:"onmsinertiastart" // jsrewrite:"$_.onmsinertiastart = $1" SetOnmsinertiastart(onmsinertiastart func(Event)) // Onmsmanipulationstatechanged prop // js:"onmsmanipulationstatechanged" // jsrewrite:"$_.onmsmanipulationstatechanged" Onmsmanipulationstatechanged() (onmsmanipulationstatechanged func(*MSManipulationEvent)) // SetOnmsmanipulationstatechanged prop // js:"onmsmanipulationstatechanged" // jsrewrite:"$_.onmsmanipulationstatechanged = $1" SetOnmsmanipulationstatechanged(onmsmanipulationstatechanged func(*MSManipulationEvent)) // Onmspointercancel prop // js:"onmspointercancel" // jsrewrite:"$_.onmspointercancel" Onmspointercancel() (onmspointercancel func(Event)) // SetOnmspointercancel prop // js:"onmspointercancel" // jsrewrite:"$_.onmspointercancel = $1" SetOnmspointercancel(onmspointercancel func(Event)) // Onmspointerdown prop // js:"onmspointerdown" // jsrewrite:"$_.onmspointerdown" Onmspointerdown() (onmspointerdown func(Event)) // SetOnmspointerdown prop // js:"onmspointerdown" // jsrewrite:"$_.onmspointerdown = $1" SetOnmspointerdown(onmspointerdown func(Event)) // Onmspointerenter prop // js:"onmspointerenter" // jsrewrite:"$_.onmspointerenter" Onmspointerenter() (onmspointerenter func(Event)) // SetOnmspointerenter prop // js:"onmspointerenter" // jsrewrite:"$_.onmspointerenter = $1" SetOnmspointerenter(onmspointerenter func(Event)) // Onmspointerleave prop // js:"onmspointerleave" // jsrewrite:"$_.onmspointerleave" Onmspointerleave() (onmspointerleave func(Event)) // SetOnmspointerleave prop // js:"onmspointerleave" // jsrewrite:"$_.onmspointerleave = $1" SetOnmspointerleave(onmspointerleave func(Event)) // Onmspointermove prop // js:"onmspointermove" // jsrewrite:"$_.onmspointermove" Onmspointermove() (onmspointermove func(Event)) // SetOnmspointermove prop // js:"onmspointermove" // jsrewrite:"$_.onmspointermove = $1" SetOnmspointermove(onmspointermove func(Event)) // Onmspointerout prop // js:"onmspointerout" // jsrewrite:"$_.onmspointerout" Onmspointerout() (onmspointerout func(Event)) // SetOnmspointerout prop // js:"onmspointerout" // jsrewrite:"$_.onmspointerout = $1" SetOnmspointerout(onmspointerout func(Event)) // Onmspointerover prop // js:"onmspointerover" // jsrewrite:"$_.onmspointerover" Onmspointerover() (onmspointerover func(Event)) // SetOnmspointerover prop // js:"onmspointerover" // jsrewrite:"$_.onmspointerover = $1" SetOnmspointerover(onmspointerover func(Event)) // Onmspointerup prop // js:"onmspointerup" // jsrewrite:"$_.onmspointerup" Onmspointerup() (onmspointerup func(Event)) // SetOnmspointerup prop // js:"onmspointerup" // jsrewrite:"$_.onmspointerup = $1" SetOnmspointerup(onmspointerup func(Event)) // Onmssitemodejumplistitemremoved prop Occurs when an item is removed from a Jump List of a webpage running in Site Mode. // * @param ev The event. // js:"onmssitemodejumplistitemremoved" // jsrewrite:"$_.onmssitemodejumplistitemremoved" Onmssitemodejumplistitemremoved() (onmssitemodejumplistitemremoved func(*MSSiteModeEvent)) // SetOnmssitemodejumplistitemremoved prop Occurs when an item is removed from a Jump List of a webpage running in Site Mode. // * @param ev The event. // js:"onmssitemodejumplistitemremoved" // jsrewrite:"$_.onmssitemodejumplistitemremoved = $1" SetOnmssitemodejumplistitemremoved(onmssitemodejumplistitemremoved func(*MSSiteModeEvent)) // Onmsthumbnailclick prop Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. // * @param ev The event. // js:"onmsthumbnailclick" // jsrewrite:"$_.onmsthumbnailclick" Onmsthumbnailclick() (onmsthumbnailclick func(*MSSiteModeEvent)) // SetOnmsthumbnailclick prop Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. // * @param ev The event. // js:"onmsthumbnailclick" // jsrewrite:"$_.onmsthumbnailclick = $1" SetOnmsthumbnailclick(onmsthumbnailclick func(*MSSiteModeEvent)) // Onpause prop Occurs when playback is paused. // * @param ev The event. // js:"onpause" // jsrewrite:"$_.onpause" Onpause() (onpause func(Event)) // SetOnpause prop Occurs when playback is paused. // * @param ev The event. // js:"onpause" // jsrewrite:"$_.onpause = $1" SetOnpause(onpause func(Event)) // Onplay prop Occurs when the play method is requested. // * @param ev The event. // js:"onplay" // jsrewrite:"$_.onplay" Onplay() (onplay func(Event)) // SetOnplay prop Occurs when the play method is requested. // * @param ev The event. // js:"onplay" // jsrewrite:"$_.onplay = $1" SetOnplay(onplay func(Event)) // Onplaying prop Occurs when the audio or video has started playing. // * @param ev The event. // js:"onplaying" // jsrewrite:"$_.onplaying" Onplaying() (onplaying func(Event)) // SetOnplaying prop Occurs when the audio or video has started playing. // * @param ev The event. // js:"onplaying" // jsrewrite:"$_.onplaying = $1" SetOnplaying(onplaying func(Event)) // Onpointerlockchange prop // js:"onpointerlockchange" // jsrewrite:"$_.onpointerlockchange" Onpointerlockchange() (onpointerlockchange func(Event)) // SetOnpointerlockchange prop // js:"onpointerlockchange" // jsrewrite:"$_.onpointerlockchange = $1" SetOnpointerlockchange(onpointerlockchange func(Event)) // Onpointerlockerror prop // js:"onpointerlockerror" // jsrewrite:"$_.onpointerlockerror" Onpointerlockerror() (onpointerlockerror func(Event)) // SetOnpointerlockerror prop // js:"onpointerlockerror" // jsrewrite:"$_.onpointerlockerror = $1" SetOnpointerlockerror(onpointerlockerror func(Event)) // Onprogress prop Occurs to indicate progress while downloading media data. // * @param ev The event. // js:"onprogress" // jsrewrite:"$_.onprogress" Onprogress() (onprogress func(Event)) // SetOnprogress prop Occurs to indicate progress while downloading media data. // * @param ev The event. // js:"onprogress" // jsrewrite:"$_.onprogress = $1" SetOnprogress(onprogress func(Event)) // Onratechange prop Occurs when the playback rate is increased or decreased. // * @param ev The event. // js:"onratechange" // jsrewrite:"$_.onratechange" Onratechange() (onratechange func(Event)) // SetOnratechange prop Occurs when the playback rate is increased or decreased. // * @param ev The event. // js:"onratechange" // jsrewrite:"$_.onratechange = $1" SetOnratechange(onratechange func(Event)) // Onreadystatechange prop Fires when the state of the object has changed. // * @param ev The event // js:"onreadystatechange" // jsrewrite:"$_.onreadystatechange" Onreadystatechange() (onreadystatechange func(Event)) // SetOnreadystatechange prop Fires when the state of the object has changed. // * @param ev The event // js:"onreadystatechange" // jsrewrite:"$_.onreadystatechange = $1" SetOnreadystatechange(onreadystatechange func(Event)) // Onreset prop Fires when the user resets a form. // * @param ev The event. // js:"onreset" // jsrewrite:"$_.onreset" Onreset() (onreset func(Event)) // SetOnreset prop Fires when the user resets a form. // * @param ev The event. // js:"onreset" // jsrewrite:"$_.onreset = $1" SetOnreset(onreset func(Event)) // Onscroll prop Fires when the user repositions the scroll box in the scroll bar on the object. // * @param ev The event. // js:"onscroll" // jsrewrite:"$_.onscroll" Onscroll() (onscroll func(Event)) // SetOnscroll prop Fires when the user repositions the scroll box in the scroll bar on the object. // * @param ev The event. // js:"onscroll" // jsrewrite:"$_.onscroll = $1" SetOnscroll(onscroll func(Event)) // Onseeked prop Occurs when the seek operation ends. // * @param ev The event. // js:"onseeked" // jsrewrite:"$_.onseeked" Onseeked() (onseeked func(Event)) // SetOnseeked prop Occurs when the seek operation ends. // * @param ev The event. // js:"onseeked" // jsrewrite:"$_.onseeked = $1" SetOnseeked(onseeked func(Event)) // Onseeking prop Occurs when the current playback position is moved. // * @param ev The event. // js:"onseeking" // jsrewrite:"$_.onseeking" Onseeking() (onseeking func(Event)) // SetOnseeking prop Occurs when the current playback position is moved. // * @param ev The event. // js:"onseeking" // jsrewrite:"$_.onseeking = $1" SetOnseeking(onseeking func(Event)) // Onselect prop Fires when the current selection changes. // * @param ev The event. // js:"onselect" // jsrewrite:"$_.onselect" Onselect() (onselect func(Event)) // SetOnselect prop Fires when the current selection changes. // * @param ev The event. // js:"onselect" // jsrewrite:"$_.onselect = $1" SetOnselect(onselect func(Event)) // Onselectionchange prop Fires when the selection state of a document changes. // * @param ev The event. // js:"onselectionchange" // jsrewrite:"$_.onselectionchange" Onselectionchange() (onselectionchange func(Event)) // SetOnselectionchange prop Fires when the selection state of a document changes. // * @param ev The event. // js:"onselectionchange" // jsrewrite:"$_.onselectionchange = $1" SetOnselectionchange(onselectionchange func(Event)) // Onselectstart prop // js:"onselectstart" // jsrewrite:"$_.onselectstart" Onselectstart() (onselectstart func(Event)) // SetOnselectstart prop // js:"onselectstart" // jsrewrite:"$_.onselectstart = $1" SetOnselectstart(onselectstart func(Event)) // Onstalled prop Occurs when the download has stopped. // * @param ev The event. // js:"onstalled" // jsrewrite:"$_.onstalled" Onstalled() (onstalled func(Event)) // SetOnstalled prop Occurs when the download has stopped. // * @param ev The event. // js:"onstalled" // jsrewrite:"$_.onstalled = $1" SetOnstalled(onstalled func(Event)) // Onstop prop Fires when the user clicks the Stop button or leaves the Web page. // * @param ev The event. // js:"onstop" // jsrewrite:"$_.onstop" Onstop() (onstop func(Event)) // SetOnstop prop Fires when the user clicks the Stop button or leaves the Web page. // * @param ev The event. // js:"onstop" // jsrewrite:"$_.onstop = $1" SetOnstop(onstop func(Event)) // Onsubmit prop // js:"onsubmit" // jsrewrite:"$_.onsubmit" Onsubmit() (onsubmit func(Event)) // SetOnsubmit prop // js:"onsubmit" // jsrewrite:"$_.onsubmit = $1" SetOnsubmit(onsubmit func(Event)) // Onsuspend prop Occurs if the load operation has been intentionally halted. // * @param ev The event. // js:"onsuspend" // jsrewrite:"$_.onsuspend" Onsuspend() (onsuspend func(Event)) // SetOnsuspend prop Occurs if the load operation has been intentionally halted. // * @param ev The event. // js:"onsuspend" // jsrewrite:"$_.onsuspend = $1" SetOnsuspend(onsuspend func(Event)) // Ontimeupdate prop Occurs to indicate the current playback position. // * @param ev The event. // js:"ontimeupdate" // jsrewrite:"$_.ontimeupdate" Ontimeupdate() (ontimeupdate func(Event)) // SetOntimeupdate prop Occurs to indicate the current playback position. // * @param ev The event. // js:"ontimeupdate" // jsrewrite:"$_.ontimeupdate = $1" SetOntimeupdate(ontimeupdate func(Event)) // Ontouchcancel prop // js:"ontouchcancel" // jsrewrite:"$_.ontouchcancel" Ontouchcancel() (ontouchcancel func(Event)) // SetOntouchcancel prop // js:"ontouchcancel" // jsrewrite:"$_.ontouchcancel = $1" SetOntouchcancel(ontouchcancel func(Event)) // Ontouchend prop // js:"ontouchend" // jsrewrite:"$_.ontouchend" Ontouchend() (ontouchend func(Event)) // SetOntouchend prop // js:"ontouchend" // jsrewrite:"$_.ontouchend = $1" SetOntouchend(ontouchend func(Event)) // Ontouchmove prop // js:"ontouchmove" // jsrewrite:"$_.ontouchmove" Ontouchmove() (ontouchmove func(Event)) // SetOntouchmove prop // js:"ontouchmove" // jsrewrite:"$_.ontouchmove = $1" SetOntouchmove(ontouchmove func(Event)) // Ontouchstart prop // js:"ontouchstart" // jsrewrite:"$_.ontouchstart" Ontouchstart() (ontouchstart func(Event)) // SetOntouchstart prop // js:"ontouchstart" // jsrewrite:"$_.ontouchstart = $1" SetOntouchstart(ontouchstart func(Event)) // Onvolumechange prop Occurs when the volume is changed, or playback is muted or unmuted. // * @param ev The event. // js:"onvolumechange" // jsrewrite:"$_.onvolumechange" Onvolumechange() (onvolumechange func(Event)) // SetOnvolumechange prop Occurs when the volume is changed, or playback is muted or unmuted. // * @param ev The event. // js:"onvolumechange" // jsrewrite:"$_.onvolumechange = $1" SetOnvolumechange(onvolumechange func(Event)) // Onwaiting prop Occurs when playback stops because the next frame of a video resource is not available. // * @param ev The event. // js:"onwaiting" // jsrewrite:"$_.onwaiting" Onwaiting() (onwaiting func(Event)) // SetOnwaiting prop Occurs when playback stops because the next frame of a video resource is not available. // * @param ev The event. // js:"onwaiting" // jsrewrite:"$_.onwaiting = $1" SetOnwaiting(onwaiting func(Event)) // Onwebkitfullscreenchange prop // js:"onwebkitfullscreenchange" // jsrewrite:"$_.onwebkitfullscreenchange" Onwebkitfullscreenchange() (onwebkitfullscreenchange func(Event)) // SetOnwebkitfullscreenchange prop // js:"onwebkitfullscreenchange" // jsrewrite:"$_.onwebkitfullscreenchange = $1" SetOnwebkitfullscreenchange(onwebkitfullscreenchange func(Event)) // Onwebkitfullscreenerror prop // js:"onwebkitfullscreenerror" // jsrewrite:"$_.onwebkitfullscreenerror" Onwebkitfullscreenerror() (onwebkitfullscreenerror func(Event)) // SetOnwebkitfullscreenerror prop // js:"onwebkitfullscreenerror" // jsrewrite:"$_.onwebkitfullscreenerror = $1" SetOnwebkitfullscreenerror(onwebkitfullscreenerror func(Event)) // Plugins prop // js:"plugins" // jsrewrite:"$_.plugins" Plugins() (plugins HTMLCollection) // PointerLockElement prop // js:"pointerLockElement" // jsrewrite:"$_.pointerLockElement" PointerLockElement() (pointerLockElement Element) // ReadyState prop Retrieves a value that indicates the current state of the object. // js:"readyState" // jsrewrite:"$_.readyState" ReadyState() (readyState string) // Referrer prop Gets the URL of the location that referred the user to the current page. // js:"referrer" // jsrewrite:"$_.referrer" Referrer() (referrer string) // RootElement prop Gets the root svg element in the document hierarchy. // js:"rootElement" // jsrewrite:"$_.rootElement" RootElement() (rootElement *SVGSVGElement) // Scripts prop Retrieves a collection of all script objects in the document. // js:"scripts" // jsrewrite:"$_.scripts" Scripts() (scripts HTMLCollection) // ScrollingElement prop // js:"scrollingElement" // jsrewrite:"$_.scrollingElement" ScrollingElement() (scrollingElement Element) // StyleSheets prop Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. // js:"styleSheets" // jsrewrite:"$_.styleSheets" StyleSheets() (styleSheets *StyleSheetList) // Title prop Contains the title of the document. // js:"title" // jsrewrite:"$_.title" Title() (title string) // SetTitle prop Contains the title of the document. // js:"title" // jsrewrite:"$_.title = $1" SetTitle(title string) // URL prop Sets or gets the URL for the current document. // js:"URL" // jsrewrite:"$_.URL" URL() (URL string) // URLUnencoded prop Gets the URL for the document, stripped of any character encoding. // js:"URLUnencoded" // jsrewrite:"$_.URLUnencoded" URLUnencoded() (URLUnencoded string) // VisibilityState prop // js:"visibilityState" // jsrewrite:"$_.visibilityState" VisibilityState() (visibilityState *visibilitystate.VisibilityState) // VlinkColor prop Sets or gets the color of the links that the user has visited. // js:"vlinkColor" // jsrewrite:"$_.vlinkColor" VlinkColor() (vlinkColor string) // SetVlinkColor prop Sets or gets the color of the links that the user has visited. // js:"vlinkColor" // jsrewrite:"$_.vlinkColor = $1" SetVlinkColor(vlinkColor string) // WebkitCurrentFullScreenElement prop // js:"webkitCurrentFullScreenElement" // jsrewrite:"$_.webkitCurrentFullScreenElement" WebkitCurrentFullScreenElement() (webkitCurrentFullScreenElement Element) // WebkitFullscreenElement prop // js:"webkitFullscreenElement" // jsrewrite:"$_.webkitFullscreenElement" WebkitFullscreenElement() (webkitFullscreenElement Element) // WebkitFullscreenEnabled prop // js:"webkitFullscreenEnabled" // jsrewrite:"$_.webkitFullscreenEnabled" WebkitFullscreenEnabled() (webkitFullscreenEnabled bool) // WebkitIsFullScreen prop // js:"webkitIsFullScreen" // jsrewrite:"$_.webkitIsFullScreen" WebkitIsFullScreen() (webkitIsFullScreen bool) // XMLEncoding prop // js:"xmlEncoding" // jsrewrite:"$_.xmlEncoding" XMLEncoding() (xmlEncoding string) // XMLStandalone prop // js:"xmlStandalone" // jsrewrite:"$_.xmlStandalone" XMLStandalone() (xmlStandalone bool) // SetXMLStandalone prop // js:"xmlStandalone" // jsrewrite:"$_.xmlStandalone = $1" SetXMLStandalone(xmlStandalone bool) // XMLVersion prop Gets or sets the version attribute specified in the declaration of an XML document. // js:"xmlVersion" // jsrewrite:"$_.xmlVersion" XMLVersion() (xmlVersion string) // SetXMLVersion prop Gets or sets the version attribute specified in the declaration of an XML document. // js:"xmlVersion" // jsrewrite:"$_.xmlVersion = $1" SetXMLVersion(xmlVersion string) }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: ##Description: For this challenge you will determine if string 1 can be rearranged into string 2. def unscrambler(str1,str2) if str1.chars.sort.join == str2.chars.sort.join return true else return false end end puts unscrambler("ac","ac ot") After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
4
##Description: For this challenge you will determine if string 1 can be rearranged into string 2. def unscrambler(str1,str2) if str1.chars.sort.join == str2.chars.sort.join return true else return false end end puts unscrambler("ac","ac ot")
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: 建筑外墙保温体系应用技术与安全管理 PDF下载 牛志荣,罗义英主编 百度云 电子书 下载 电子书下载 PDF电子书下载不求人,看这篇文章就够了→ http://www.chendianrong.com/pdf#711217646 PDF电子书下载不求人,看这篇文章就够了→ http://www.chendianrong.com/pdf#711217646 <p>书名:建筑外墙保温体系应用技术与安全管理</p><p>作者:牛志荣,罗义英主编</p><p>页数:242</p><p>定价:¥40.0</p><p>出版社:中国建筑工业出版社</p><p>出版日期:2015-05-01</p><p>ISBN:9787112176465</p><p><h2>本书特色</h2></p>[<p>   牛志荣和罗义英编著的《建筑外墙保温体系应用技术与安全管理》主要论述建筑外墙外保温体系应用技术与安全管理,主要包括墙体保温节能基础知识,墙体保温体系的热工性能,系统防水透气,墙体保温体系防火性能,外墙外保温系统抗震性能与安全管理,墙体保温体系抗风性能,墙体保温体系设计和施工,外墙保温体系检测和验收。   本书适用于建设工程外墙保温体系应用、单位各级管理机构、大专院校和科研机构参考。   </p>]<p><h2>内容简介</h2></p>[<p>本书主要论述建筑外墙外保温体系应用技术与安全管理, 主要包括墙体保温节能基础知识, 墙体保温体系的热工性能, 系统防水透气, 墙体保温体系防火防能, 外墙外保温系统抗震性能与安全管理等。</p>]<p><h2>目录</h2></p> **章  墙体保温节  能基础知识  **节  墙体保温节  能概述  第二节  墙体保温体系组成材料  第三节  墙体保温体系的构造类型  第四节  墙体保温体系设计的影响因素第二章  墙体保温体系的热工性能  **节  墙体保温体系的保温隔热性能  第二节  墙体保温体系热应力作用  第三节  热工缺陷及避免方式第三章  系统防水透气  **节  材料的吸水性能  第二节  材料的透气性能  第三节  kuenzel外墙保护理论  第四节  保温体系的吸水性和透气性  第五节  气迁徙的影响因素分析  第六节  渗透冷凝分析  第七节  墙体保温体系渗漏水的原因及防治对策  第八节  墙体结构防渗安全管理措施第四章  墙体保温体系防火性能  **节  概述  第二节  保温材料防火试验与评价方法  第三节  墙体保温体系防火试验及评价方法  第四节  外墙外保温防火设计及其标准  第五节  施工过程的防火安全管理第五章  外墙外保温系统抗震性能与安全管理  **节  外墙外保温体系抗震要求  第二节  外墙外保温体系的抗震验算  第三节  外墙外保温体系安全管理第六章  墙体保温体系抗风性能  **节  墙体保温体系的抗风要求  第二节  墙体保温体系的抗风影响因素  第三节  墙体保温体系预防风荷载破坏措施第七章  墙体保温体系设计和施工  **节  墙体保温体系设计  第二节  墙体保温体系施工  第三节  墙体保温体系施工现场安全管理第八章  外墙保温体系检测和验收  **节  墙体保温体系检测检验项目  第二节  墙体保温体系检测检验方法  第三节  保温系统组成材料检测参考文献致谢 After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
1
建筑外墙保温体系应用技术与安全管理 PDF下载 牛志荣,罗义英主编 百度云 电子书 下载 电子书下载 PDF电子书下载不求人,看这篇文章就够了→ http://www.chendianrong.com/pdf#711217646 PDF电子书下载不求人,看这篇文章就够了→ http://www.chendianrong.com/pdf#711217646 <p>书名:建筑外墙保温体系应用技术与安全管理</p><p>作者:牛志荣,罗义英主编</p><p>页数:242</p><p>定价:¥40.0</p><p>出版社:中国建筑工业出版社</p><p>出版日期:2015-05-01</p><p>ISBN:9787112176465</p><p><h2>本书特色</h2></p>[<p>   牛志荣和罗义英编著的《建筑外墙保温体系应用技术与安全管理》主要论述建筑外墙外保温体系应用技术与安全管理,主要包括墙体保温节能基础知识,墙体保温体系的热工性能,系统防水透气,墙体保温体系防火性能,外墙外保温系统抗震性能与安全管理,墙体保温体系抗风性能,墙体保温体系设计和施工,外墙保温体系检测和验收。   本书适用于建设工程外墙保温体系应用、单位各级管理机构、大专院校和科研机构参考。   </p>]<p><h2>内容简介</h2></p>[<p>本书主要论述建筑外墙外保温体系应用技术与安全管理, 主要包括墙体保温节能基础知识, 墙体保温体系的热工性能, 系统防水透气, 墙体保温体系防火防能, 外墙外保温系统抗震性能与安全管理等。</p>]<p><h2>目录</h2></p> **章  墙体保温节  能基础知识  **节  墙体保温节  能概述  第二节  墙体保温体系组成材料  第三节  墙体保温体系的构造类型  第四节  墙体保温体系设计的影响因素第二章  墙体保温体系的热工性能  **节  墙体保温体系的保温隔热性能  第二节  墙体保温体系热应力作用  第三节  热工缺陷及避免方式第三章  系统防水透气  **节  材料的吸水性能  第二节  材料的透气性能  第三节  kuenzel外墙保护理论  第四节  保温体系的吸水性和透气性  第五节  气迁徙的影响因素分析  第六节  渗透冷凝分析  第七节  墙体保温体系渗漏水的原因及防治对策  第八节  墙体结构防渗安全管理措施第四章  墙体保温体系防火性能  **节  概述  第二节  保温材料防火试验与评价方法  第三节  墙体保温体系防火试验及评价方法  第四节  外墙外保温防火设计及其标准  第五节  施工过程的防火安全管理第五章  外墙外保温系统抗震性能与安全管理  **节  外墙外保温体系抗震要求  第二节  外墙外保温体系的抗震验算  第三节  外墙外保温体系安全管理第六章  墙体保温体系抗风性能  **节  墙体保温体系的抗风要求  第二节  墙体保温体系的抗风影响因素  第三节  墙体保温体系预防风荷载破坏措施第七章  墙体保温体系设计和施工  **节  墙体保温体系设计  第二节  墙体保温体系施工  第三节  墙体保温体系施工现场安全管理第八章  外墙保温体系检测和验收  **节  墙体保温体系检测检验项目  第二节  墙体保温体系检测检验方法  第三节  保温系统组成材料检测参考文献致谢
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: export const RE_RECORD_ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/; export function hasOwnProperty(obj: unknown, key: string): boolean { return Object.prototype.hasOwnProperty.call(obj, key); } /** * Checks if a value is undefined. * @param {Any} value * @return {Boolean} */ function _isUndefined(value: unknown): boolean { return typeof value === "undefined"; } /** * Sorts records in a list according to a given ordering. * * @param {String} order The ordering, eg. `-last_modified`. * @param {Array} list The collection to order. * @return {Array} */ export function sortObjects<T extends { [key: string]: any }>( order: string, list: T[] ): T[] { const hasDash = order[0] === "-"; const field = hasDash ? order.slice(1) : order; const direction = hasDash ? -1 : 1; return list.slice().sort((a, b) => { if (a[field] && _isUndefined(b[field])) { return direction; } if (b[field] && _isUndefined(a[field])) { return -direction; } if (_isUndefined(a[field]) && _isUndefined(b[field])) { return 0; } return a[field] > b[field] ? direction : -direction; }); } /** * Test if a single object matches all given filters. * * @param {Object} filters The filters object. * @param {Object} entry The object to filter. * @return {Boolean} */ export function filterObject<T extends { [key: string]: any }>( filters: { [key: string]: any }, entry: T ): boolean { return Object.keys(filters).every((filter) => { const value = filters[filter]; if (Array.isArray(value)) { return value.some((candidate) => candidate === entry[filter]); } else if (typeof value === "object") { return filterObject(value, entry[filter]); } else if (!hasOwnProperty(entry, filter)) { console.error(`The property ${filter} does not exist`); return false; } return entry[filter] === value; }); } /** * Filters records in a list matching all given filters. * * @param {Object} filters The After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
3
export const RE_RECORD_ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/; export function hasOwnProperty(obj: unknown, key: string): boolean { return Object.prototype.hasOwnProperty.call(obj, key); } /** * Checks if a value is undefined. * @param {Any} value * @return {Boolean} */ function _isUndefined(value: unknown): boolean { return typeof value === "undefined"; } /** * Sorts records in a list according to a given ordering. * * @param {String} order The ordering, eg. `-last_modified`. * @param {Array} list The collection to order. * @return {Array} */ export function sortObjects<T extends { [key: string]: any }>( order: string, list: T[] ): T[] { const hasDash = order[0] === "-"; const field = hasDash ? order.slice(1) : order; const direction = hasDash ? -1 : 1; return list.slice().sort((a, b) => { if (a[field] && _isUndefined(b[field])) { return direction; } if (b[field] && _isUndefined(a[field])) { return -direction; } if (_isUndefined(a[field]) && _isUndefined(b[field])) { return 0; } return a[field] > b[field] ? direction : -direction; }); } /** * Test if a single object matches all given filters. * * @param {Object} filters The filters object. * @param {Object} entry The object to filter. * @return {Boolean} */ export function filterObject<T extends { [key: string]: any }>( filters: { [key: string]: any }, entry: T ): boolean { return Object.keys(filters).every((filter) => { const value = filters[filter]; if (Array.isArray(value)) { return value.some((candidate) => candidate === entry[filter]); } else if (typeof value === "object") { return filterObject(value, entry[filter]); } else if (!hasOwnProperty(entry, filter)) { console.error(`The property ${filter} does not exist`); return false; } return entry[filter] === value; }); } /** * Filters records in a list matching all given filters. * * @param {Object} filters The filters object. * @param {Array} list The collection to filter. * @return {Array} */ export function filterObjects<T>( filters: { [key: string]: any }, list: T[] ): T[] { return list.filter((entry) => { return filterObject(filters, entry); }); } /** * Simple deep object comparison function. This only supports comparison of * serializable JavaScript objects. * * @param {Object} a The source object. * @param {Object} b The compared object. * @return {Boolean} */ export function deepEqual(a: any, b: any): boolean { if (a === b) { return true; } if (typeof a !== typeof b) { return false; } if (!(a && typeof a === "object") || !(b && typeof b === "object")) { return false; } if (Object.keys(a).length !== Object.keys(b).length) { return false; } for (const k in a) { if (!deepEqual(a[k], b[k])) { return false; } } return true; } /** * Return an object without the specified keys. * * @param {Object} obj The original object. * @param {Array} keys The list of keys to exclude. * @return {Object} A copy without the specified keys. */ export function omitKeys< T extends { [key: string]: unknown }, K extends string >(obj: T, keys: K[] = []): Omit<T, K> { const result = { ...obj }; for (const key of keys) { delete result[key]; } return result; } export function arrayEqual(a: unknown[], b: unknown[]): boolean { if (a.length !== b.length) { return false; } for (let i = a.length; i--; ) { if (a[i] !== b[i]) { return false; } } return true; } function makeNestedObjectFromArr( arr: string[], val: any, nestedFiltersObj: { [key: string]: any } ): { [key: string]: any } { const last = arr.length - 1; return arr.reduce((acc, cv, i) => { if (i === last) { return (acc[cv] = val); } else if (hasOwnProperty(acc, cv)) { return acc[cv]; } else { return (acc[cv] = {}); } }, nestedFiltersObj); } export function transformSubObjectFilters(filtersObj: { [key: string]: any }) { const transformedFilters = {}; for (const key in filtersObj) { const keysArr = key.split("."); const val = filtersObj[key]; makeNestedObjectFromArr(keysArr, val, transformedFilters); } return transformedFilters; } /** * Deeply access an object's properties * @param obj - The object whose property you want to compare * @param key - A dot notation path to the property you want to compare */ export function getDeepKey(obj: any, key: string): unknown { const segments = key.split("."); let result = obj; for (let p = 0; p < segments.length; p++) { result = result ? result[segments[p]] : undefined; } return result ?? undefined; } /** * Clones an object with all its undefined keys removed. * @private */ export function cleanUndefinedProperties(obj: { [key: string]: any; }): { [key: string]: any; } { const result: { [key: string]: any } = {}; for (const key in obj) { if (typeof obj[key] !== "undefined") { result[key] = obj[key]; } } return result; } /** * Transforms an object into an URL query string, stripping out any undefined * values. * * @param {Object} obj * @return {String} */ export function qsify(obj: { [key: string]: any }): string { const encode = (v: any): string => encodeURIComponent(typeof v === "boolean" ? String(v) : v); const stripped = cleanUndefinedProperties(obj); return Object.keys(stripped) .map((k) => { const ks = encode(k) + "="; if (Array.isArray(stripped[k])) { return ks + stripped[k].map((v: any) => encode(v)).join(","); } else { return ks + encode(stripped[k]); } }) .join("&"); } /** * Handle common query parameters for Kinto requests. * * @param {String} [path] The endpoint base path. * @param {Array} [options.fields] Fields to limit the * request to. * @param {Object} [options.query={}] Additional query arguments. */ export function addEndpointOptions( path: string, options: { fields?: string[]; query?: { [key: string]: string } } = {} ): string { const query: { [key: string]: any } = { ...options.query }; if (options.fields) { query._fields = options.fields; } const queryString = qsify(query); if (queryString) { return path + "?" + queryString; } return path; } /** * Replace authorization header with an obscured version */ export function obscureAuthorizationHeader( headers: HeadersInit ): { [key: string]: string; } { const h = new Headers(headers); if (h.has("authorization")) { h.set("authorization", "**** (suppressed)"); } const obscuredHeaders: { [key: string]: string } = {}; for (const [header, value] of h.entries()) { obscuredHeaders[header] = value; } return obscuredHeaders; } /** * Returns a Promise always resolving after the specified amount in milliseconds. * * @return Promise<void> */ export function delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); } const RECORD_FIELDS_TO_CLEAN = ["_status"]; /** * Compare two records omitting local fields and synchronization * attributes (like _status and last_modified) * @param {Object} a A record to compare. * @param {Object} b A record to compare. * @param {Array} localFields Additional fields to ignore during the comparison * @return {boolean} */ export function recordsEqual( a: { [key: string]: unknown }, b: { [key: string]: unknown }, localFields: readonly string[] = [] ): boolean { const fieldsToClean = [ ...RECORD_FIELDS_TO_CLEAN, "last_modified", ...localFields, ]; const cleanLocal = (r: { [key: string]: unknown }) => omitKeys(r, fieldsToClean); return deepEqual(cleanLocal(a), cleanLocal(b)); } export function markStatus<T extends { _status?: string }>( record: T, status: string ) { return { ...record, _status: status }; } export function markDeleted<T extends { _status?: string }>(record: T) { return markStatus(record, "deleted"); } export function markSynced<T extends { _status?: string }>(record: T) { return markStatus(record, "synced"); } /** * Chunks an array into n pieces. * * @private * @param {Array} array * @param {Number} n * @return {Array} */ export function partition<T>(array: T[], n: number): T[][] { if (n <= 0) { return [array]; } return array.reduce<T[][]>((acc, x, i) => { if (i === 0 || i % n === 0) { acc.push([x]); } else { acc[acc.length - 1].push(x); } return acc; }, []); } export function isObject(thing: unknown): boolean { return typeof thing === "object" && thing !== null && !Array.isArray(thing); } export function toDataBody<T extends { id: string }>( resource: T | string ): { id: string } { if (isObject(resource)) { return resource as T; } if (typeof resource === "string") { return { id: resource }; } throw new Error("Invalid argument."); }
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package com.skylarksit.module.ui.utils enum class FeedbackType { FEEDBACK_TYPE_DELIVERY, FEEDBACK_TYPE_THIRD_PARTY } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
1
package com.skylarksit.module.ui.utils enum class FeedbackType { FEEDBACK_TYPE_DELIVERY, FEEDBACK_TYPE_THIRD_PARTY }
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: /*eslint-disable func-names */ import React from 'react'; import Purchase from './Purchase'; class Seat extends React.Component { constructor(props) { super(props); this.state = { sections: [] }; this.submit = this.submit.bind(this); } componentWillMount() { fetch('//localhost:3333/section/') .then((response) => response.json()) .then((data) => { const sections = data.sections; this.setState({ sections }); }); } submit() { const quantity = this.refs.quantity.value; const cost = this.refs.cost.value; const type = this.refs.type.value; fetch('//localhost:3333/section/', { method: 'post', body: JSON.stringify({ quantity, cost, type }), headers: {"Content-Type": "application/json"} }) .then((r) => { return r.json(); }) .then((data) => { const sections = data.sections; this.setState({ sections }); }); } render() { return ( <div> <div>Seat Component</div> <div>Quantity: <input type="number" ref="quantity" /></div> <div>type: <input type="text" ref="type" /></div> <div>Cost: <input type="number" ref="cost" /></div> <div><button onClick={this.submit} >Submit</button></div> <div><Purchase sections={this.state.sections} /></div> </div> ); } } export default Seat; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
3
/*eslint-disable func-names */ import React from 'react'; import Purchase from './Purchase'; class Seat extends React.Component { constructor(props) { super(props); this.state = { sections: [] }; this.submit = this.submit.bind(this); } componentWillMount() { fetch('//localhost:3333/section/') .then((response) => response.json()) .then((data) => { const sections = data.sections; this.setState({ sections }); }); } submit() { const quantity = this.refs.quantity.value; const cost = this.refs.cost.value; const type = this.refs.type.value; fetch('//localhost:3333/section/', { method: 'post', body: JSON.stringify({ quantity, cost, type }), headers: {"Content-Type": "application/json"} }) .then((r) => { return r.json(); }) .then((data) => { const sections = data.sections; this.setState({ sections }); }); } render() { return ( <div> <div>Seat Component</div> <div>Quantity: <input type="number" ref="quantity" /></div> <div>type: <input type="text" ref="type" /></div> <div>Cost: <input type="number" ref="cost" /></div> <div><button onClick={this.submit} >Submit</button></div> <div><Purchase sections={this.state.sections} /></div> </div> ); } } export default Seat;
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: #!/usr/bin/env bash set -euxo pipefail curl https://sh.rustup.rs -sSf | sh -s -- -yt wasm32-unknown-unknown source "$HOME/.cargo/env" wget https://github.com/rustwasm/wasm-bindgen/releases/download/0.2.84/wasm-bindgen-0.2.84-x86_64-unknown-linux-musl.tar.gz tar -xzf wasm-bindgen-0.2.84-x86_64-unknown-linux-musl.tar.gz mv wasm-bindgen-0.2.84-x86_64-unknown-linux-musl/wasm-bindgen ~/.cargo/bin rm -r wasm-bindgen-0.2.84-x86_64-unknown-linux-musl* yarn build:docs-site After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
1
#!/usr/bin/env bash set -euxo pipefail curl https://sh.rustup.rs -sSf | sh -s -- -yt wasm32-unknown-unknown source "$HOME/.cargo/env" wget https://github.com/rustwasm/wasm-bindgen/releases/download/0.2.84/wasm-bindgen-0.2.84-x86_64-unknown-linux-musl.tar.gz tar -xzf wasm-bindgen-0.2.84-x86_64-unknown-linux-musl.tar.gz mv wasm-bindgen-0.2.84-x86_64-unknown-linux-musl/wasm-bindgen ~/.cargo/bin rm -r wasm-bindgen-0.2.84-x86_64-unknown-linux-musl* yarn build:docs-site
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php declare(strict_types=1); /** * This file is part of Hyperf. * * @link https://www.hyperf.io * @document https://hyperf.wiki * @contact <EMAIL> * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ namespace Hyperf\JsonRpc; use Hyperf\Context\Context; use Hyperf\Contract\PackerInterface; use Hyperf\ExceptionHandler\ExceptionHandlerDispatcher; use Hyperf\HttpMessage\Server\Request as Psr7Request; use Hyperf\HttpMessage\Server\Response as Psr7Response; use Hyperf\HttpServer\Contract\CoreMiddlewareInterface; use Hyperf\HttpServer\ResponseEmitter; use Hyperf\HttpServer\Server; use Hyperf\JsonRpc\Exception\Handler\HttpExceptionHandler; use Hyperf\Rpc\Context as RpcContext; use Hyperf\Rpc\Protocol; use Hyperf\Rpc\ProtocolManager; use Hyperf\RpcServer\RequestDispatcher; use Psr\Container\ContainerInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use function Hyperf\Support\make; class HttpServer extends Server { protected Protocol $protocol; protected PackerInterface $packer; protected ResponseBuilder $responseBuilder; public function __construct( ContainerInterface $container, RequestDispatcher $dispatcher, ExceptionHandlerDispatcher $exceptionHandlerDispatcher, ResponseEmitter $responseEmitter, ProtocolManager $protocolManager ) { parent::__construct($container, $dispatcher, $exceptionHandlerDispatcher, $responseEmitter); $this->protocol = new Protocol($container, $protocolManager, 'jsonrpc-http'); $this->packer = $this->protocol->getPacker(); $this->responseBuilder = make(ResponseBuilder::class, [ 'dataFormatter' => $this->protocol->getDataFormatter(), 'packer' => $this->packer, ]); } protected function getDefaultExceptionHandler(): array { return [ HttpExceptionHandler::class, ]; } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
3
<?php declare(strict_types=1); /** * This file is part of Hyperf. * * @link https://www.hyperf.io * @document https://hyperf.wiki * @contact <EMAIL> * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ namespace Hyperf\JsonRpc; use Hyperf\Context\Context; use Hyperf\Contract\PackerInterface; use Hyperf\ExceptionHandler\ExceptionHandlerDispatcher; use Hyperf\HttpMessage\Server\Request as Psr7Request; use Hyperf\HttpMessage\Server\Response as Psr7Response; use Hyperf\HttpServer\Contract\CoreMiddlewareInterface; use Hyperf\HttpServer\ResponseEmitter; use Hyperf\HttpServer\Server; use Hyperf\JsonRpc\Exception\Handler\HttpExceptionHandler; use Hyperf\Rpc\Context as RpcContext; use Hyperf\Rpc\Protocol; use Hyperf\Rpc\ProtocolManager; use Hyperf\RpcServer\RequestDispatcher; use Psr\Container\ContainerInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use function Hyperf\Support\make; class HttpServer extends Server { protected Protocol $protocol; protected PackerInterface $packer; protected ResponseBuilder $responseBuilder; public function __construct( ContainerInterface $container, RequestDispatcher $dispatcher, ExceptionHandlerDispatcher $exceptionHandlerDispatcher, ResponseEmitter $responseEmitter, ProtocolManager $protocolManager ) { parent::__construct($container, $dispatcher, $exceptionHandlerDispatcher, $responseEmitter); $this->protocol = new Protocol($container, $protocolManager, 'jsonrpc-http'); $this->packer = $this->protocol->getPacker(); $this->responseBuilder = make(ResponseBuilder::class, [ 'dataFormatter' => $this->protocol->getDataFormatter(), 'packer' => $this->packer, ]); } protected function getDefaultExceptionHandler(): array { return [ HttpExceptionHandler::class, ]; } protected function createCoreMiddleware(): CoreMiddlewareInterface { return new HttpCoreMiddleware($this->container, $this->protocol, $this->responseBuilder, $this->serverName); } protected function initRequestAndResponse($request, $response): array { Context::set(ResponseInterface::class, $psr7Response = new Psr7Response()); // Initialize PSR-7 Request and Response objects. $psr7Request = Psr7Request::loadFromSwooleRequest($request); if (! $this->isHealthCheck($psr7Request)) { if (! str_contains($psr7Request->getHeaderLine('content-type'), 'application/json')) { $psr7Response = $this->responseBuilder->buildErrorResponse($psr7Request, ResponseBuilder::PARSE_ERROR); } // @TODO Optimize the error handling of encode. $content = $this->packer->unpack((string) $psr7Request->getBody()); if (! isset($content['jsonrpc'], $content['method'], $content['params'])) { $psr7Response = $this->responseBuilder->buildErrorResponse($psr7Request, ResponseBuilder::INVALID_REQUEST); } } $psr7Request = $psr7Request->withUri($psr7Request->getUri()->withPath($content['method'] ?? '/')) ->withParsedBody($content['params'] ?? null) ->withAttribute('data', $content ?? []) ->withAttribute('request_id', $content['id'] ?? null); $this->getContext()->setData($content['context'] ?? []); Context::set(ServerRequestInterface::class, $psr7Request); Context::set(ResponseInterface::class, $psr7Response); return [$psr7Request, $psr7Response]; } protected function isHealthCheck(RequestInterface $request): bool { return $request->getHeaderLine('user-agent') === 'Consul Health Check'; } protected function getContext() { return $this->container->get(RpcContext::class); } }
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: angular.module('trainning').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function( $stateProvider, $urlRouterProvider, $locationProvider ){ $urlRouterProvider.otherwise('home'); $stateProvider // HOME STATES AND NESTED VIEWS ======================================== .state('home', { url: '/home', component: 'homeComponent' }) .state('charts', { url: '/charts', component: 'chartsComponent' }); $locationProvider.html5Mode(true); $locationProvider.hashPrefix(''); }]) After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
2
angular.module('trainning').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function( $stateProvider, $urlRouterProvider, $locationProvider ){ $urlRouterProvider.otherwise('home'); $stateProvider // HOME STATES AND NESTED VIEWS ======================================== .state('home', { url: '/home', component: 'homeComponent' }) .state('charts', { url: '/charts', component: 'chartsComponent' }); $locationProvider.html5Mode(true); $locationProvider.hashPrefix(''); }])
Below is an extract from a TypeScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid TypeScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical TypeScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., generics, decorators). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching TypeScript. It should be similar to a school exercise, a tutorial, or a TypeScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching TypeScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import { route, authorize } from "plumier" export class HomeController { @authorize.public() @route.get("/") index() { return { hello: "world" } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
typescript
2
import { route, authorize } from "plumier" export class HomeController { @authorize.public() @route.get("/") index() { return { hello: "world" } } }
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package scepclient import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/http/httputil" "testing" "golang.org/x/net/context" ) func TestGetCACaps(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() resp, err := client.GetCACaps(ctx) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) } func TestGetCACert(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() resp, _, err := client.GetCACert(ctx) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) } func TestPKIOperationGET(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() pkcsreq, err := ioutil.ReadFile("../scep/testdata/PKCSReq.der") if err != nil { t.Fatal(err) } resp, err := client.PKIOperation(ctx, pkcsreq) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
3
package scepclient import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/http/httputil" "testing" "golang.org/x/net/context" ) func TestGetCACaps(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() resp, err := client.GetCACaps(ctx) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) } func TestGetCACert(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() resp, _, err := client.GetCACert(ctx) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) } func TestPKIOperationGET(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) dump, err := httputil.DumpRequest(r, true) if err != nil { t.Fatal(err) } fmt.Println(string(dump)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() client := NewClient(server.URL + "/scep") ctx := context.Background() pkcsreq, err := ioutil.ReadFile("../scep/testdata/PKCSReq.der") if err != nil { t.Fatal(err) } resp, err := client.PKIOperation(ctx, pkcsreq) if err != nil { t.Fatal(err) } fmt.Println(string(resp)) }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: require 'spec_helper' describe "comentarios/edit.html.erb" do before(:each) do @comentario = assign(:comentario, stub_model(Comentario, :autor_id => 1, :texto => "MyText", :destinatario_id => 1 )) end it "renders the edit comentario form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => comentarios_path(@comentario), :method => "post" do assert_select "input#comentario_autor_id", :name => "comentario[autor_id]" assert_select "textarea#comentario_texto", :name => "comentario[texto]" assert_select "input#comentario_destinatario_id", :name => "comentario[destinatario_id]" end end end After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
1
require 'spec_helper' describe "comentarios/edit.html.erb" do before(:each) do @comentario = assign(:comentario, stub_model(Comentario, :autor_id => 1, :texto => "MyText", :destinatario_id => 1 )) end it "renders the edit comentario form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => comentarios_path(@comentario), :method => "post" do assert_select "input#comentario_autor_id", :name => "comentario[autor_id]" assert_select "textarea#comentario_texto", :name => "comentario[texto]" assert_select "input#comentario_destinatario_id", :name => "comentario[destinatario_id]" end end end
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::shared::Loc; use codespan::{ByteSpan, CodeMap, FileMap, FileName, Span}; use codespan_reporting::{ emit, termcolor::{ColorChoice, StandardStream}, Diagnostic, Label, }; use std::collections::{HashMap, HashSet}; pub type Errors = Vec<Error>; pub type Error = Vec<(Loc, String)>; pub type ErrorSlice = [(Loc, String)]; pub type HashableError = Vec<(&'static str, usize, usize, String)>; pub type Files = HashMap<&'static str, FileMap>; pub fn report_errors(files: Files, errors: Errors) -> ! { assert!(!errors.is_empty()); let mut codemap = CodeMap::new(); let mut file_mapping = HashMap::new(); let mut current_end = 1; for (fname, filemap) in files.into_iter() { file_mapping.insert(fname, current_end); let added_fmap = codemap.add_filemap(FileName::real(fname), filemap.src().to_string()); current_end = added_fmap.span().end().to_usize() + 1; } render_errors(&codemap, file_mapping, errors); std::process::exit(1) } fn hashable_error(error: &ErrorSlice) -> HashableError { error .iter() .map(|(loc, e)| { ( loc.file(), loc.span().start().to_usize(), loc.span().end().to_usize(), e.clone(), ) }) .collect() } fn render_errors(codemap: &CodeMap, file_mapping: HashMap<&'static str, usize>, errors: Errors) { let mut seen: HashSet<HashableError> = HashSet::new(); for error in errors.into_iter() { let hashable_error = hashable_error(&error); if seen.contains(&hashable_error) { continue; } seen.insert(hashable_error); let writer = StandardStream::stderr(ColorChoice::Auto); let err = render_error(&file_mapping, error); emit(writer, &codemap, &err).unwrap() } } fn convert_loc(file_mapping: &HashMap<&'static str, usize>, lo After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
2
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::shared::Loc; use codespan::{ByteSpan, CodeMap, FileMap, FileName, Span}; use codespan_reporting::{ emit, termcolor::{ColorChoice, StandardStream}, Diagnostic, Label, }; use std::collections::{HashMap, HashSet}; pub type Errors = Vec<Error>; pub type Error = Vec<(Loc, String)>; pub type ErrorSlice = [(Loc, String)]; pub type HashableError = Vec<(&'static str, usize, usize, String)>; pub type Files = HashMap<&'static str, FileMap>; pub fn report_errors(files: Files, errors: Errors) -> ! { assert!(!errors.is_empty()); let mut codemap = CodeMap::new(); let mut file_mapping = HashMap::new(); let mut current_end = 1; for (fname, filemap) in files.into_iter() { file_mapping.insert(fname, current_end); let added_fmap = codemap.add_filemap(FileName::real(fname), filemap.src().to_string()); current_end = added_fmap.span().end().to_usize() + 1; } render_errors(&codemap, file_mapping, errors); std::process::exit(1) } fn hashable_error(error: &ErrorSlice) -> HashableError { error .iter() .map(|(loc, e)| { ( loc.file(), loc.span().start().to_usize(), loc.span().end().to_usize(), e.clone(), ) }) .collect() } fn render_errors(codemap: &CodeMap, file_mapping: HashMap<&'static str, usize>, errors: Errors) { let mut seen: HashSet<HashableError> = HashSet::new(); for error in errors.into_iter() { let hashable_error = hashable_error(&error); if seen.contains(&hashable_error) { continue; } seen.insert(hashable_error); let writer = StandardStream::stderr(ColorChoice::Auto); let err = render_error(&file_mapping, error); emit(writer, &codemap, &err).unwrap() } } fn convert_loc(file_mapping: &HashMap<&'static str, usize>, loc: Loc) -> ByteSpan { let fname = loc.file(); let offset = *file_mapping.get(fname).unwrap(); let begin_index = (loc.span().start().to_usize() + offset) as u32; let end_index = (loc.span().end().to_usize() + offset) as u32; Span::new(begin_index.into(), end_index.into()) } fn render_error(file_mapping: &HashMap<&'static str, usize>, error: Error) -> Diagnostic { let mut diag = Diagnostic::new_error(error[0].1.clone()); for err in error { let label = Label::new_primary(convert_loc(file_mapping, err.0)).with_message(err.1); diag = diag.with_label(label); } diag }
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package main import ( "fmt" "io/ioutil" "os" ) func main() { filename1 := os.Args[1] filename2 := os.Args[2] fileBytes1, err1 := ioutil.ReadFile(filename1) if err1 != nil { panic("File1: problem") } fileBytes2, err2 := ioutil.ReadFile(filename2) if err2 != nil { panic("File2: problem") } fileString := string(fileBytes1) + string(fileBytes2) fmt.Println(fileString) err3 := ioutil.WriteFile("combined.txt", []byte(fileString), 0644) if err3 != nil { panic("Combined: write failed.") } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
3
package main import ( "fmt" "io/ioutil" "os" ) func main() { filename1 := os.Args[1] filename2 := os.Args[2] fileBytes1, err1 := ioutil.ReadFile(filename1) if err1 != nil { panic("File1: problem") } fileBytes2, err2 := ioutil.ReadFile(filename2) if err2 != nil { panic("File2: problem") } fileString := string(fileBytes1) + string(fileBytes2) fmt.Println(fileString) err3 := ioutil.WriteFile("combined.txt", []byte(fileString), 0644) if err3 != nil { panic("Combined: write failed.") } }
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php require_once '../config/connect.php'; $index = $_POST['index']; $gost = $_POST['gost']; $coefficient = $_POST['coefficient']; $date = $_POST['date']; $insert = "INSERT INTO `coefficients` (`id`, `ПОКАЗАТЕЛЬ`, `ГОСТ`, `КОЭФФИЦИЕНТ`, `ДАТА ОЧЕРЕДНОГО ПОСТРОЕНИЯ ГРАФИКА`) VALUES (NULL, '$index', '$gost', '$coefficient', '$date')"; mysqli_query($connect, $insert); header("Location: ../coefficients.php"); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php require_once '../config/connect.php'; $index = $_POST['index']; $gost = $_POST['gost']; $coefficient = $_POST['coefficient']; $date = $_POST['date']; $insert = "INSERT INTO `coefficients` (`id`, `ПОКАЗАТЕЛЬ`, `ГОСТ`, `КОЭФФИЦИЕНТ`, `ДАТА ОЧЕРЕДНОГО ПОСТРОЕНИЯ ГРАФИКА`) VALUES (NULL, '$index', '$gost', '$coefficient', '$date')"; mysqli_query($connect, $insert); header("Location: ../coefficients.php");
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: /* See LICENSE folder for this sample’s licensing information. Abstract: The scene delegate class. */ import CoreSpotlight import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let userInfo = userActivity.userInfo as? [String: Any], let identifier = userInfo[CSSearchableItemActivityIdentifier] as? String else { return } // Find the photo view controller. guard let rootViewController = window?.rootViewController as? UINavigationController, let photosViewController = rootViewController.topViewController as? PhotosViewController else { return } let persistentContainer = appDelegate.coreDataStack.persistentContainer // Find the photo object and its image. guard let uri = URL(string: identifier), let objectID = persistentContainer.persistentStoreCoordinator.managedObjectID(forURIRepresentation: uri) else { return } if let photo = persistentContainer.viewContext.object(with: objectID) as? Photo { guard let photoData = photo.photoData?.data, let image = UIImage(data: photoData) else { return } // Present the photo. let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "FullImageNC") guard let navController = viewController as? UINavigationController, let imageViewController = navController.topViewController as? FullImageViewController else { return } imageViewController.fullImage = image navC After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
2
/* See LICENSE folder for this sample’s licensing information. Abstract: The scene delegate class. */ import CoreSpotlight import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let userInfo = userActivity.userInfo as? [String: Any], let identifier = userInfo[CSSearchableItemActivityIdentifier] as? String else { return } // Find the photo view controller. guard let rootViewController = window?.rootViewController as? UINavigationController, let photosViewController = rootViewController.topViewController as? PhotosViewController else { return } let persistentContainer = appDelegate.coreDataStack.persistentContainer // Find the photo object and its image. guard let uri = URL(string: identifier), let objectID = persistentContainer.persistentStoreCoordinator.managedObjectID(forURIRepresentation: uri) else { return } if let photo = persistentContainer.viewContext.object(with: objectID) as? Photo { guard let photoData = photo.photoData?.data, let image = UIImage(data: photoData) else { return } // Present the photo. let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "FullImageNC") guard let navController = viewController as? UINavigationController, let imageViewController = navController.topViewController as? FullImageViewController else { return } imageViewController.fullImage = image navController.modalPresentationStyle = .fullScreen photosViewController.present(navController, animated: true) } else if let tag = persistentContainer.viewContext.object(with: objectID) as? Tag { guard let tagName = tag.name else { return } guard let searchBar = photosViewController.navigationItem.searchController?.searchBar else { return } searchBar.text = tagName } } }
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package main import ( "fmt" "math/big" "time" ) func main() { start := time.Now() var num, base big.Int num.Set(big.NewInt(1)) base.Set(big.NewInt(2)) for i := 0; i < 1000; i++ { num.Mul(&num, &base) } num_str := num.String() sum := 0 for _, d := range num_str { sum += int(d - '0') } fmt.Println(sum) elapsed := time.Since(start) fmt.Println("Elasped:", elapsed) } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
3
package main import ( "fmt" "math/big" "time" ) func main() { start := time.Now() var num, base big.Int num.Set(big.NewInt(1)) base.Set(big.NewInt(2)) for i := 0; i < 1000; i++ { num.Mul(&num, &base) } num_str := num.String() sum := 0 for _, d := range num_str { sum += int(d - '0') } fmt.Println(sum) elapsed := time.Since(start) fmt.Println("Elasped:", elapsed) }
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace SCADA { static class Win32Api { #region User32.dll /// <summary> /// 该函数设置由不同线程产生的窗口的显示状态 /// </summary> /// <param name="hWnd">窗口句柄</param> /// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分</param> /// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零</returns> [DllImport("User32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); /// <summary> /// 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。 /// 系统给创建前台窗口的线程分配的权限稍高于其他线程。 /// </summary> /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param> /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零</returns> [DllImport("User32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// 打开剪贴板 /// </summary> [DllImport("User32.dll")] public static extern bool OpenClipboard(IntPtr hWndNewOwner); /// <summary> /// 关闭剪贴板 /// </summary> [DllImport("User32.dll")] public static extern bool CloseClipboard(); /// <summary> /// 清空剪贴板 /// </summary> /// <returns></returns> [DllImport("User32.dll")] public static extern bool EmptyClipboard(); /// <summary> /// 将存放有数据的内存块放入剪切板的资源管理中 /// </summary> [DllImport("User32.dll")] public static extern IntPtr SetClipboardData(uint Format, IntPtr hData); #endregion } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
2
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace SCADA { static class Win32Api { #region User32.dll /// <summary> /// 该函数设置由不同线程产生的窗口的显示状态 /// </summary> /// <param name="hWnd">窗口句柄</param> /// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分</param> /// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零</returns> [DllImport("User32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); /// <summary> /// 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。 /// 系统给创建前台窗口的线程分配的权限稍高于其他线程。 /// </summary> /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param> /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零</returns> [DllImport("User32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// 打开剪贴板 /// </summary> [DllImport("User32.dll")] public static extern bool OpenClipboard(IntPtr hWndNewOwner); /// <summary> /// 关闭剪贴板 /// </summary> [DllImport("User32.dll")] public static extern bool CloseClipboard(); /// <summary> /// 清空剪贴板 /// </summary> /// <returns></returns> [DllImport("User32.dll")] public static extern bool EmptyClipboard(); /// <summary> /// 将存放有数据的内存块放入剪切板的资源管理中 /// </summary> [DllImport("User32.dll")] public static extern IntPtr SetClipboardData(uint Format, IntPtr hData); #endregion } }
Below is an extract from a Kotlin program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Kotlin code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Kotlin concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., coroutines, extension functions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Kotlin. It should be similar to a school exercise, a tutorial, or a Kotlin course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Kotlin. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package com.avito.android.integration.test import com.avito.android.util.Is import org.hamcrest.MatcherAssert.assertThat object ReportTestUtils { const val SPECIAL_TEST_CASE_ID = -1 fun simpleSuccessAssertion() = assertThat(2 + 2, Is(4)) } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
kotlin
1
package com.avito.android.integration.test import com.avito.android.util.Is import org.hamcrest.MatcherAssert.assertThat object ReportTestUtils { const val SPECIAL_TEST_CASE_ID = -1 fun simpleSuccessAssertion() = assertThat(2 + 2, Is(4)) }
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: --- editable: false sourcePath: en/_api-ref/datalens/function-ref/DATE_PARSE.md --- # DATE_PARSE #### Syntax {#syntax} ``` DATE_PARSE( value ) ``` #### Description {#description} Converts the `value` expression to date format. Unlike [DATE](DATE.md), it supports multiple formats. **Argument types:** - `value` — `String` **Return type**: `Date` #### Examples {#examples} ``` DATE_PARSE("2019-01-02 03:04:05") = #2019-01-02# ``` ``` DATE_PARSE("2019-01-02") = #2019-01-02# ``` ``` DATE_PARSE("20190102") = #2019-01-02# ``` ``` DATE_PARSE("2019.01.02") = #2019-01-02# ``` ``` DATE_PARSE("02/01/2019") = #2019-01-02# ``` ``` DATE_PARSE("02/01/19") = #2019-01-02# ``` ``` DATE_PARSE("2019 Jan 02") = #2019-01-02# ``` ``` DATE_PARSE("2019 Jan") = #2019-01-01# ``` ``` DATE_PARSE("201901") = #2019-01-01# ``` ``` DATE_PARSE("2019") = #2019-01-01# ``` #### Data source support {#data-source-support} `ClickHouse 21.8`. After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
3
--- editable: false sourcePath: en/_api-ref/datalens/function-ref/DATE_PARSE.md --- # DATE_PARSE #### Syntax {#syntax} ``` DATE_PARSE( value ) ``` #### Description {#description} Converts the `value` expression to date format. Unlike [DATE](DATE.md), it supports multiple formats. **Argument types:** - `value` — `String` **Return type**: `Date` #### Examples {#examples} ``` DATE_PARSE("2019-01-02 03:04:05") = #2019-01-02# ``` ``` DATE_PARSE("2019-01-02") = #2019-01-02# ``` ``` DATE_PARSE("20190102") = #2019-01-02# ``` ``` DATE_PARSE("2019.01.02") = #2019-01-02# ``` ``` DATE_PARSE("02/01/2019") = #2019-01-02# ``` ``` DATE_PARSE("02/01/19") = #2019-01-02# ``` ``` DATE_PARSE("2019 Jan 02") = #2019-01-02# ``` ``` DATE_PARSE("2019 Jan") = #2019-01-01# ``` ``` DATE_PARSE("201901") = #2019-01-01# ``` ``` DATE_PARSE("2019") = #2019-01-01# ``` #### Data source support {#data-source-support} `ClickHouse 21.8`.
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php namespace Drupal\stripe_webform\Event; /** * Defines events for stripe webhooks * */ final class StripeWebformEvents { /** * The name of the event fired when a webhook is received * * @Event */ const WEBHOOK = 'stripe_webform.webhook'; } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php namespace Drupal\stripe_webform\Event; /** * Defines events for stripe webhooks * */ final class StripeWebformEvents { /** * The name of the event fired when a webhook is received * * @Event */ const WEBHOOK = 'stripe_webform.webhook'; }
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Business Security Systems Denison IA 51442</title> <meta name="description" content="Top Home Security Systems in Denison Iowa - Several commercial intruder alarm configurations are available: NO, NC, EOLR, 2-EOLR, and 3-EOLR (End-of-line-resistor loop circuits)."> <link rel="stylesheet" href="./css/style.css"> </head> <main> <header id="navbar"> <div class="container"> <div class="flexbox flexRow alignItemCenter"> <div class="logobar"> <a href="index.html">Home Security Systems</a> </div> </div> </div> </header> <div class="slider"> <div class="flexbox flexColumn"> <div class=" slider-contant"> <span>Are You Looking To Get a Home Security System Installed?</span> <p>Compare Price Quotes & Save Upto 35%. Its Simple, fast and free.</p> <div class="btn-group"> <a href="./quotes.html" class="btn primary-btn">Request Free Quote</a> </div> </div> </div> </div> <section> <div class="container"> <div id="tab1" class="opTabContent"> <div class="tab-wrapper"> <a href="./index.html">Home</a><br><center><h1>Business Security Systems in Denison IA</h1> <p> <iframe width="100%" height="250" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=Denison.IA+()&ie=UTF8&t=&z=14&iwloc=B&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"> </iframe> </p> <h2 style="text-align: center;"><span style="color: #ff0000;">Request Free Quotes For Home Security System</span></h2> <p style="text-align: center;"><span style="color: #0000ff;"><strong>Just fill out the simple form below and lo After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Business Security Systems Denison IA 51442</title> <meta name="description" content="Top Home Security Systems in Denison Iowa - Several commercial intruder alarm configurations are available: NO, NC, EOLR, 2-EOLR, and 3-EOLR (End-of-line-resistor loop circuits)."> <link rel="stylesheet" href="./css/style.css"> </head> <main> <header id="navbar"> <div class="container"> <div class="flexbox flexRow alignItemCenter"> <div class="logobar"> <a href="index.html">Home Security Systems</a> </div> </div> </div> </header> <div class="slider"> <div class="flexbox flexColumn"> <div class=" slider-contant"> <span>Are You Looking To Get a Home Security System Installed?</span> <p>Compare Price Quotes & Save Upto 35%. Its Simple, fast and free.</p> <div class="btn-group"> <a href="./quotes.html" class="btn primary-btn">Request Free Quote</a> </div> </div> </div> </div> <section> <div class="container"> <div id="tab1" class="opTabContent"> <div class="tab-wrapper"> <a href="./index.html">Home</a><br><center><h1>Business Security Systems in Denison IA</h1> <p> <iframe width="100%" height="250" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=Denison.IA+()&ie=UTF8&t=&z=14&iwloc=B&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"> </iframe> </p> <h2 style="text-align: center;"><span style="color: #ff0000;">Request Free Quotes For Home Security System</span></h2> <p style="text-align: center;"><span style="color: #0000ff;"><strong>Just fill out the simple form below and local representative will be in touch shortly</strong></span></p> <!-- START: BuyerZone Widget Code--> <script data-bzwidget src="https://cdn.buyerzone.com/apps/widget/bzWidget.min.js" data-bzwidget-pub-id="51681" data-bzwidget-color-palette-name="default" data-bzwidget-keyword-id="front" data-bzwidget-category-id="10133" ></script> <script>bzWidget.init();</script> <!-- END: BuyerZone Widget Code--> </center> <p>Security cameras that are internet-ready are a good way of monitoring your home or your business. Nearly all standalone security cameras connect to your home's Wi-Fi so you can see what's going on from your phone or tablet, and most have built-in sensors that detect motion and sound and will send push and email notifications when those sensors are triggered. It is also possible to defeat the system by introducing an auxiliary light source near the receiver and thus make it possible for an intruder to pass through the protective beam without causing an alarm.</p> <p>Bosch achieves the highest standards with a 4-step approach that covers your entire network for end-to-end data security. We believe that personal protection is about much more than surveillance, and that's why we carry an unparalleled selection of driveway alarms , child safety essentials, intercoms ,Camera Signs, Dummy Cameras, power adapters, Alarm wire, fire alarms, pepper spray,alarm Contacts and even temperature sensors.</p> <p>Spy cameras are being used by consumers to keep a track on people or environment, without their knowledge. On the other hand, DIY home security systems are exploding in popularity. We offer complete HD security camera systems that include a DVR, cameras, cables, connectors and power supplies. In December 2017, ADT launched a new professionally monitored, self-installed life safety solution, powered by the SmartThings platform, in collaboration with Samsung, which is a consumer electronics market leader.</p> <h2>Best Home Security Packages in Denison Iowa</h2> <p>Electronic monitoring equipment is extensively used by the New Zealand Department of Corrections to ensure that convicted offenders subject to home detention remain within approved areas. The data has been triangulated by studying various factors and trends from both the demand and supply sides in the video surveillance market. There are many surveillance cameras and alarm systems on the market that offer a wide range of useful features, which are all helpful in deterring thieves and keeping a home safe.</p> <p>When you need to add efficiency to your system, you can empower it with integrated video and data solutions and analytics features. Advanced control panels have displays that may be LCD (liquid crystal display) based or simple LED lights. With the start of 2010, many research labs, such as Kiwi Security Labs, started to broadcast the Advanced Intelligent Video Surveillance Systems” (AIVSS).</p> <h3>Top 5 Benefits Of Outdoor Security Cameras in Denison IA 51442</h3> <p>You will also need to choose which installation option you prefer for your alarm system: professional or DIY. Our range comprises Intruder Alarm Systems and Wireless Burglar Alarm. IPVM has reported that Sony will still have a significant imaging sensor and camera module business. We use the internet's most trusted customer review service "Shopper Approved" to document the quality of our surveillance equipment and the superior level of support we provide.</p> <p>Some systems are dedicated to one mission; others handle fire, intrusion, and safety alarms simultaneously. Like most modern technology, home security systems have evolved and improved over time. Passive Infrared (PIR) Motion Sensors protect space by 'looking' for changes in infrared (heat) energy levels caused by movement of an intruder. Keep an eye on with what you care about at any time from anywhere; just like a security camera.</p> <p>I am satisfied with his business for purchasing the 2 NOS Dome type CCTV cameras, with a DVR, hard disk, power back systems with wifi modem to my commercial space Outdoor side. Their home security systems require professional monitoring, installation and long-term contracts. An active and preventive security and automation system, SharpNode’s Smart Home & Security Kit Combo is a state-of-the-art setup that has all essential features that you could ask for.</p> <h3>Great Places to Install Hidden Home Security Cameras in Denison</h3> <p>On 17 August, Meity added 13 electronic items, including smart watches and CCTV cameras, to the Electronics and Information Technology Goods (Requirement for Compulsory Registration) Order, 2012, which means these will now have to meet standards as notified by the government and companies will not be allowed to import or sell any non-compliant product in the country.</p> <p>Their systems come with indoor and outdoor cameras that have night vision and a security light. Along with the high-decibel alarm that sounds, the monitoring company is alerted. Window foil is a less sophisticated, mostly outdated detection method that involves gluing a thin strip of conducting foil on the inside of the glass and putting low-power electric current through it. Breaking the glass is practically guaranteed to tear the foil and break the circuit.</p> <p>There is a cost in the retention of the images produced by CCTV systems. There are plenty of affordable cameras available that offer good video performance, but as with just about any smart device, you'll pay more for features such as motion tracking, facial recognition, cellular connectivity, time-lapse recording, both onboard and cloud storage options, and rechargeable battery power.</p> <p>Check out our reviews for more detailed pricing information, as well as the specific components, monitoring options, and installation instructions for each home security system we've tested. You get to control your network and all connected devices with the QHHS app. We're planning to look at the Ooma Smart Security System again, since the company added a new $60 keypad and live monitoring service.</p> <h4>CCTV Surveillance System Denison 51442</h4> <p>Check out the best do-it-yourself smart home security systems we've tested for simple and affordable ways to stay safe. Some people that say support video surveillance in city streets may not support indiscriminate telephone taps and vice versa. A policeman approaches the CCTV camera to break it. Photo: Screengrab from video released by <NAME>. Meet our favorite solution for home monitoring and protection: the Piper nv Smart Home Security System with Night Vision and a 180-degree Video Camera.</p> <p>Disadvantages: extremely sensitive to weather; as rain, snow, and fog, for example, would cause the sensors to stop working, and need sterile perimeter line because trees and bushes or anything that blocks the beam would cause false alarm or lack of detection. The following steps are required to install the Zabbix client on your ClickHouse DB server and begin monitoring your Database.</p> <p>Equipped with superb imaging ability and backed by 50x zoom ratio and the patented DarkFighterX technology, as well as intelligent functions like smart tracking and false alarm filtering, Ultra Series cameras provide comprehensive assistance to customers. These are some of the few factors that are further adding to the impressive growth rate of the Indian surveillance industry, paving the way for it to nearly triple its current market size to reach $2.4 billion by 2020.</p> <p> <iframe width="325" height="300" src="https://www.youtube.com/embed/gI-Mk9FOmoQ" frameborder="0" allowfullscreen="#DEFAULT"></iframe> </p> <div itemscope itemtype="http://schema.org/Product"> <span itemprop="name">Home Security System Denison Iowa</span> <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"> Rated <span itemprop="ratingValue">4.7</span>/5 based on <span itemprop="reviewCount">699</span> reviews.</div></div> <br><a href="./Buy-Security-Cameras-Wadsworth-IL-60083.html">Previous</a> &nbsp;&nbsp;&nbsp;&nbsp;<a href="./Security-Systems-For-Houses-Bulverde-TX-78163.html">Next</a> <br>Related Posts Denison Iowa<br><a href="./Best-Burglar-Alarm-Carbondale-PA-18407.html">Best Burglar Alarm Carbondale PA 18407</a><br><a href="./Alarm-Systems-Service-Jasper-IN-47546.html">Alarm Systems Service Jasper IN 47546</a><br><a href="./Wireless-Surveillance-Camera-System-Saddle-River-NJ-07458.html">Wireless Surveillance Camera System Saddle River NJ 07458</a><br><a href="./Household-Security-Systems-North-Bend-WA-98045.html">Household Security Systems North Bend WA 98045</a><br><a href="./New-Alarm-Systems-For-Homes-North-East-PA-16428.html">New Alarm Systems For Homes North East PA 16428</a><br> </div> </div> </div> </div> </section> <footer> <div class="container"> <div class="flexbox"> <p>© 2020 Home Alarm Systems - All Rights Reserved</p> <ul class="flexbox"> <li><a href="./privacy.html">Privacy Policy</a></li> <li><a href="./disclaimer.html">Disclaimer</a></li> <li><a href="./terms.html">Terms of Use</a></li> </ul> </div> </div> </footer> </main> <!-- Start --> <script type="text/javascript"> var sc_project=12244329; var sc_invisible=1; var sc_security="16a5df9f"; </script> <script type="text/javascript" src="https://www.statcounter.com/counter/counter.js" async></script> <noscript><div class="statcounter"><a title="Web Analytics Made Easy - StatCounter" href="https://statcounter.com/" target="_blank"><img class="statcounter" src="https://c.statcounter.com/12244329/0/16a5df9f/1/" alt="Web Analytics Made Easy - StatCounter"></a></div></noscript> <!-- End --> <body> <script src="./js/custom.js"></script> </body> </html>
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Java concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package mb.solo.pointeuse.orm; import android.content.Context; import android.util.Log; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import mb.solo.pointeuse.model.Point; public class PointDao { private static final String TAG = "orm"; private static Dao<Point, Integer> dao = null; public PointDao(Context context){ if(dao == null){ try { DbManager db = new DbManager(context); dao = db.getDao(Point.class); } catch (SQLException e) { Log.e(TAG, "PointDao - Error! ",e); } } } /* CRUD */ public List<Point> list(){ List<Point> items = new ArrayList<>(); try{ items = dao.queryBuilder().orderBy("dateEntre", false).query(); Log.i(TAG, "PointDao - SelectAll - OK"); }catch (SQLException e){ Log.e(TAG, "PointDao - SelectAll - Error! ",e); } return items; } public List<Point> listDate(Date date1, Date date2){ List<Point> items = new ArrayList<>(); try{ items = dao.queryBuilder().orderBy("dateEntre", false) .where().between("dateEntre", date1, date2).query(); }catch (SQLException e){ Log.e(TAG, "PointDao - SelectByDate - Error! ",e); } return items; } public Point find(int id){ try { Log.i(TAG, "PointDao - Find OK"); return dao.queryForId(id); } catch (SQLException e) { Log.e(TAG, "PointDao - Find-Error! ",e); return null; } } public void create(Point item){ try { dao.create(item); Log.i(TAG, "PointDao - Create OK"); } catch (SQLException e) { Log.e(TAG, "PointDao - Create - Error! ",e); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
java
2
package mb.solo.pointeuse.orm; import android.content.Context; import android.util.Log; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import mb.solo.pointeuse.model.Point; public class PointDao { private static final String TAG = "orm"; private static Dao<Point, Integer> dao = null; public PointDao(Context context){ if(dao == null){ try { DbManager db = new DbManager(context); dao = db.getDao(Point.class); } catch (SQLException e) { Log.e(TAG, "PointDao - Error! ",e); } } } /* CRUD */ public List<Point> list(){ List<Point> items = new ArrayList<>(); try{ items = dao.queryBuilder().orderBy("dateEntre", false).query(); Log.i(TAG, "PointDao - SelectAll - OK"); }catch (SQLException e){ Log.e(TAG, "PointDao - SelectAll - Error! ",e); } return items; } public List<Point> listDate(Date date1, Date date2){ List<Point> items = new ArrayList<>(); try{ items = dao.queryBuilder().orderBy("dateEntre", false) .where().between("dateEntre", date1, date2).query(); }catch (SQLException e){ Log.e(TAG, "PointDao - SelectByDate - Error! ",e); } return items; } public Point find(int id){ try { Log.i(TAG, "PointDao - Find OK"); return dao.queryForId(id); } catch (SQLException e) { Log.e(TAG, "PointDao - Find-Error! ",e); return null; } } public void create(Point item){ try { dao.create(item); Log.i(TAG, "PointDao - Create OK"); } catch (SQLException e) { Log.e(TAG, "PointDao - Create - Error! ",e); } } public void update(Point item){ try { dao.update(item); Log.i(TAG, "PointDao - Update OK"); } catch (SQLException e) { Log.e(TAG, "PointDao - Update - Error! ",e); } } public void createOrUpdate(Point item){ try { dao.createOrUpdate(item); Log.i(TAG, "PointDao - Create or Update OK"); } catch (SQLException e) { Log.e(TAG, "PointDao - Create or Update - Error! ",e); } } public void delete(Point item){ try { dao.delete(item); Log.i(TAG, "PointDao - Delete OK"); } catch (SQLException e) { Log.e(TAG, "PointDao - Delete - Error! ",e); } } public void delete(int id) { Point item = find(id); if (item != null) { delete(item); } } /*public List<Point> find(Map<String, Object> params){ List<Point> items = new ArrayList<>(); try { items = dao.queryForFieldValues(params); } catch (SQLException e) { Log.e(TAG, "PointDao - FindMap - Error! ",e); } Collections.sort(items); return items; }*/ public Point lastEntre(){ Point item = null; try{ item = dao.queryBuilder().orderBy("id", true).where() .isNull("dateSortie") .queryForFirst(); }catch (SQLException e){ Log.e(TAG, "PointDao - lastEntre - Error! ",e); } return item; } }
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package jmespath import ( "encoding/json" "fmt" "testing" "gotest.tools/assert" ) func Test_Compare(t *testing.T) { testCases := []struct { jmesPath string expectedResult int }{ { jmesPath: "compare('a', 'a')", expectedResult: 0, }, { jmesPath: "compare('a', 'b')", expectedResult: -1, }, { jmesPath: "compare('b', 'a')", expectedResult: 1, }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(int) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_EqualFold(t *testing.T) { testCases := []struct { jmesPath string expectedResult bool }{ { jmesPath: "equal_fold('Go', 'go')", expectedResult: true, }, { jmesPath: "equal_fold('a', 'b')", expectedResult: false, }, { jmesPath: "equal_fold('1', 'b')", expectedResult: false, }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(bool) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_Replace(t *testing.T) { // Can't use integer literals due to // https://github.com/jmespath/go-jmespath/issues/27 // // TODO: fix this in https://github.com/kyverno/go-jmespath testCases := []struct { jmesPath string expectedResult string }{ { jmesPath: "replace('Lorem ipsum dolor sit amet', 'ipsum', 'muspi', `-1`)", expectedResult: "Lorem muspi dolor sit amet", }, { jmesPath: "replace('Lorem ipsum ipsum ipsum dolor sit amet', 'ipsum', 'muspi', `-1`)", expectedResult: "Lorem muspi muspi muspi dolor sit amet", }, { jmesPath: "replace('Lorem ipsum ipsum ipsum dolo After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
4
package jmespath import ( "encoding/json" "fmt" "testing" "gotest.tools/assert" ) func Test_Compare(t *testing.T) { testCases := []struct { jmesPath string expectedResult int }{ { jmesPath: "compare('a', 'a')", expectedResult: 0, }, { jmesPath: "compare('a', 'b')", expectedResult: -1, }, { jmesPath: "compare('b', 'a')", expectedResult: 1, }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(int) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_EqualFold(t *testing.T) { testCases := []struct { jmesPath string expectedResult bool }{ { jmesPath: "equal_fold('Go', 'go')", expectedResult: true, }, { jmesPath: "equal_fold('a', 'b')", expectedResult: false, }, { jmesPath: "equal_fold('1', 'b')", expectedResult: false, }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(bool) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_Replace(t *testing.T) { // Can't use integer literals due to // https://github.com/jmespath/go-jmespath/issues/27 // // TODO: fix this in https://github.com/kyverno/go-jmespath testCases := []struct { jmesPath string expectedResult string }{ { jmesPath: "replace('Lorem ipsum dolor sit amet', 'ipsum', 'muspi', `-1`)", expectedResult: "Lorem muspi dolor sit amet", }, { jmesPath: "replace('Lorem ipsum ipsum ipsum dolor sit amet', 'ipsum', 'muspi', `-1`)", expectedResult: "Lorem muspi muspi muspi dolor sit amet", }, { jmesPath: "replace('Lorem ipsum ipsum ipsum dolor sit amet', 'ipsum', 'muspi', `1`)", expectedResult: "Lorem muspi ipsum ipsum dolor sit amet", }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_ReplaceAll(t *testing.T) { jp, err := New("replace_all('Lorem ipsum dolor sit amet', 'ipsum', 'muspi')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) replaced, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, replaced, "Lorem muspi dolor sit amet") } func Test_ToUpper(t *testing.T) { testCases := []struct { jmesPath string expectedResult string }{ { jmesPath: "to_upper('abc')", expectedResult: "ABC", }, { jmesPath: "to_upper('123')", expectedResult: "123", }, { jmesPath: "to_upper('a#%&123Bc')", expectedResult: "A#%&123BC", }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_ToLower(t *testing.T) { testCases := []struct { jmesPath string expectedResult string }{ { jmesPath: "to_lower('ABC')", expectedResult: "abc", }, { jmesPath: "to_lower('123')", expectedResult: "123", }, { jmesPath: "to_lower('a#%&123Bc')", expectedResult: "a#%&123bc", }, } for _, tc := range testCases { t.Run(tc.jmesPath, func(t *testing.T) { jp, err := New(tc.jmesPath) assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) res, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, res, tc.expectedResult) }) } } func Test_Trim(t *testing.T) { jp, err := New("trim('¡¡¡Hello, Gophers!!!', '!¡')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) trim, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, trim, "Hello, Gophers") } func Test_Split(t *testing.T) { jp, err := New("split('Hello, Gophers', ', ')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) split, ok := result.([]interface{}) assert.Assert(t, ok) assert.Equal(t, split[0], "Hello") assert.Equal(t, split[1], "Gophers") } func Test_HasPrefix(t *testing.T) { jp, err := New("starts_with('Gophers', 'Go')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) split, ok := result.(bool) assert.Assert(t, ok) assert.Equal(t, split, true) } func Test_HasSuffix(t *testing.T) { jp, err := New("ends_with('Amigo', 'go')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) split, ok := result.(bool) assert.Assert(t, ok) assert.Equal(t, split, true) } func Test_RegexMatch(t *testing.T) { data := make(map[string]interface{}) data["foo"] = "hgf'b1a2r'b12g" query, err := New("regex_match('12.*', foo)") assert.NilError(t, err) result, err := query.Search(data) assert.NilError(t, err) assert.Equal(t, true, result) } func Test_RegexMatchWithNumber(t *testing.T) { data := make(map[string]interface{}) data["foo"] = -12.0 query, err := New("regex_match('12.*', abs(foo))") assert.NilError(t, err) result, err := query.Search(data) assert.NilError(t, err) assert.Equal(t, true, result) } func Test_RegexReplaceAll(t *testing.T) { resourceRaw := []byte(` { "metadata": { "name": "temp", "namespace": "ns_first" }, "spec": { "namespace": "ns_first", "name": "temp_other", "field" : "Hello world, helworldlo" } } `) expected := "Glo world, Gworldlo" var resource interface{} err := json.Unmarshal(resourceRaw, &resource) assert.NilError(t, err) query, err := New(`regex_replace_all('([Hh]e|G)l', spec.field, '${2}G')`) assert.NilError(t, err) res, err := query.Search(resource) assert.NilError(t, err) result, ok := res.(string) assert.Assert(t, ok) assert.Equal(t, string(result), expected) } func Test_RegexReplaceAllLiteral(t *testing.T) { resourceRaw := []byte(` { "metadata": { "name": "temp", "namespace": "ns_first" }, "spec": { "namespace": "ns_first", "name": "temp_other", "field" : "Hello world, helworldlo" } } `) expected := "Glo world, Gworldlo" var resource interface{} err := json.Unmarshal(resourceRaw, &resource) assert.NilError(t, err) query, err := New(`regex_replace_all_literal('[Hh]el?', spec.field, 'G')`) assert.NilError(t, err) res, err := query.Search(resource) assert.NilError(t, err) result, ok := res.(string) assert.Assert(t, ok) assert.Equal(t, string(result), expected) } func Test_LabelMatch(t *testing.T) { resourceRaw := []byte(` { "metadata": { "labels": { "app": "test-app", "controller-name": "test-controller" } } } `) testCases := []struct { resource []byte test string expectedResult bool }{ { resource: resourceRaw, test: `{ "app": "test-app" }`, expectedResult: true, }, { resource: resourceRaw, test: `{ "app": "test-app", "controller-name": "test-controller" }`, expectedResult: true, }, { resource: resourceRaw, test: `{ "app": "test-app2" }`, expectedResult: false, }, { resource: resourceRaw, test: `{ "app.kubernetes.io/name": "test-app" }`, expectedResult: false, }, } for i, tc := range testCases { t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { var resource interface{} err := json.Unmarshal(tc.resource, &resource) assert.NilError(t, err) query, err := New("label_match(`" + tc.test + "`, metadata.labels)") assert.NilError(t, err) res, err := query.Search(resource) assert.NilError(t, err) result, ok := res.(bool) assert.Assert(t, ok) assert.Equal(t, result, tc.expectedResult) }) } } func Test_Add(t *testing.T) { jp, err := New("add(`12`, `13`)") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) equal, ok := result.(float64) assert.Assert(t, ok) assert.Equal(t, equal, 25.0) } func Test_Subtract(t *testing.T) { jp, err := New("subtract(`12`, `7`)") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) equal, ok := result.(float64) assert.Assert(t, ok) assert.Equal(t, equal, 5.0) } func Test_Multiply(t *testing.T) { jp, err := New("multiply(`3`, `2.5`)") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) equal, ok := result.(float64) assert.Assert(t, ok) assert.Equal(t, equal, 7.5) } func Test_Divide(t *testing.T) { jp, err := New("divide(`12`, `1.5`)") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) equal, ok := result.(float64) assert.Assert(t, ok) assert.Equal(t, equal, 8.0) } func Test_Modulo(t *testing.T) { jp, err := New("modulo(`12`, `7`)") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) equal, ok := result.(int64) assert.Assert(t, ok) assert.Equal(t, equal, int64(5)) } func Test_Base64Decode(t *testing.T) { jp, err := New("base64_decode('SGVsbG8sIHdvcmxkIQ==')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) str, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, str, "Hello, world!") } func Test_Base64Encode(t *testing.T) { jp, err := New("base64_encode('Hello, world!')") assert.NilError(t, err) result, err := jp.Search("") assert.NilError(t, err) str, ok := result.(string) assert.Assert(t, ok) assert.Equal(t, str, "SGVsbG8sIHdvcmxkIQ==") } func Test_Base64Decode_Secret(t *testing.T) { resourceRaw := []byte(` { "apiVersion": "v1", "kind": "Secret", "metadata": { "name": "example", "namespace": "default" }, "type": "Opaque", "data": { "example1": "SGVsbG8sIHdvcmxkIQ==", "example2": "Rm9vQmFy" } } `) var resource interface{} err := json.Unmarshal(resourceRaw, &resource) assert.NilError(t, err) query, err := New(`base64_decode(data.example1)`) assert.NilError(t, err) res, err := query.Search(resource) assert.NilError(t, err) result, ok := res.(string) assert.Assert(t, ok) assert.Equal(t, string(result), "Hello, world!") } func Test_TimeSince(t *testing.T) { testCases := []struct { test string expectedResult string }{ { test: "time_since('', '2021-01-02T15:04:05-07:00', '2021-01-10T03:14:05-07:00')", expectedResult: "180h10m0s", }, { test: "time_since('Mon Jan _2 15:04:05 MST 2006', 'Mon Jan 02 15:04:05 MST 2021', 'Mon Jan 10 03:14:16 MST 2021')", expectedResult: "180h10m11s", }, } for i, tc := range testCases { t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { query, err := New(tc.test) assert.NilError(t, err) res, err := query.Search("") assert.NilError(t, err) result, ok := res.(string) assert.Assert(t, ok) assert.Equal(t, result, tc.expectedResult) }) } }
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Java concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: package com.cmcu.mcc.business.dao; import com.cmcu.mcc.business.entity.BusinessBidApply; import java.util.List; import java.util.Map; public interface BusinessBidApplyMapper { int deleteByPrimaryKey(Integer id); int insert(BusinessBidApply record); BusinessBidApply selectByPrimaryKey(Integer id); List<BusinessBidApply> selectAll(Map params); int updateByPrimaryKey(BusinessBidApply record); List<String> listAgent(); } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
java
1
package com.cmcu.mcc.business.dao; import com.cmcu.mcc.business.entity.BusinessBidApply; import java.util.List; import java.util.Map; public interface BusinessBidApplyMapper { int deleteByPrimaryKey(Integer id); int insert(BusinessBidApply record); BusinessBidApply selectByPrimaryKey(Integer id); List<BusinessBidApply> selectAll(Map params); int updateByPrimaryKey(BusinessBidApply record); List<String> listAgent(); }
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Ruby concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join('node_modules') Rails.application.config.assets.precompile += %w( light.css ) Rails.application.config.assets.precompile += %w( jquery.scrollbar.css ) Rails.application.config.assets.precompile += %w( select2.min.css ) Rails.application.config.assets.precompile += %w( switchery.min.css ) Rails.application.config.assets.precompile += %w( classie.css ) Rails.application.config.assets.precompile += %w( pages-icons.css ) Rails.application.config.assets.precompile += %w( nv.d3.min.css ) Rails.application.config.assets.precompile += %w( rickshaw.min.css ) Rails.application.config.assets.precompile += %w( datepicker3.css ) Rails.application.config.assets.precompile += %w( mapplic.css ) Rails.application.config.assets.precompile += %w( dashboard.widgets.css ) Rails.application.config.assets.precompile += %w( feather.min.js ) Rails.application.config.assets.precompile += %w( d3.v3.js.js ) Rails.application.config.assets.precompile += %w( pace.min.js ) Rails.application.config.assets.precompile += %w( pages-icons.min.js ) Rails.application.config.assets.precompile += %w( jquery-1.11.1.min.js ) Rails.application.config.assets.precompile += %w( modernizr.custom.js ) Rails.application.config.assets.precompile += %w( jquery-ui.min.js ) Rails.application.config.assets.precompile += %w( tether.min.js ) Rails.application.config.assets.precompile += %w( bootstrap.min.js ) Rails.application.config.assets.precompile += %w( jquery-easy.js ) Rails.application.config.assets.precompile += %w( jquery.unveil.min.js ) Rails.application.config.assets.precompile += %w( jquery.ioslist.min.js After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
ruby
1
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join('node_modules') Rails.application.config.assets.precompile += %w( light.css ) Rails.application.config.assets.precompile += %w( jquery.scrollbar.css ) Rails.application.config.assets.precompile += %w( select2.min.css ) Rails.application.config.assets.precompile += %w( switchery.min.css ) Rails.application.config.assets.precompile += %w( classie.css ) Rails.application.config.assets.precompile += %w( pages-icons.css ) Rails.application.config.assets.precompile += %w( nv.d3.min.css ) Rails.application.config.assets.precompile += %w( rickshaw.min.css ) Rails.application.config.assets.precompile += %w( datepicker3.css ) Rails.application.config.assets.precompile += %w( mapplic.css ) Rails.application.config.assets.precompile += %w( dashboard.widgets.css ) Rails.application.config.assets.precompile += %w( feather.min.js ) Rails.application.config.assets.precompile += %w( d3.v3.js.js ) Rails.application.config.assets.precompile += %w( pace.min.js ) Rails.application.config.assets.precompile += %w( pages-icons.min.js ) Rails.application.config.assets.precompile += %w( jquery-1.11.1.min.js ) Rails.application.config.assets.precompile += %w( modernizr.custom.js ) Rails.application.config.assets.precompile += %w( jquery-ui.min.js ) Rails.application.config.assets.precompile += %w( tether.min.js ) Rails.application.config.assets.precompile += %w( bootstrap.min.js ) Rails.application.config.assets.precompile += %w( jquery-easy.js ) Rails.application.config.assets.precompile += %w( jquery.unveil.min.js ) Rails.application.config.assets.precompile += %w( jquery.ioslist.min.js ) Rails.application.config.assets.precompile += %w( jquery.actual.min.js ) Rails.application.config.assets.precompile += %w( select2.full.min.js ) Rails.application.config.assets.precompile += %w( classie.js ) Rails.application.config.assets.precompile += %w( switchery.min.js ) Rails.application.config.assets.precompile += %w( interact.min.js ) Rails.application.config.assets.precompile += %w( moment-with-locales.min.js ) Rails.application.config.assets.precompile += %w( jquery.scrollbar.min.js ) Rails.application.config.assets.precompile += %w( d3.v3.js ) Rails.application.config.assets.precompile += %w( utils.js ) Rails.application.config.assets.precompile += %w( tooltip.js ) Rails.application.config.assets.precompile += %w( interactiveLayer.js ) Rails.application.config.assets.precompile += %w( axis.js ) Rails.application.config.assets.precompile += %w( line.js ) Rails.application.config.assets.precompile += %w( lineWithFocusChart.js ) Rails.application.config.assets.precompile += %w( rickshaw.min.js ) Rails.application.config.assets.precompile += %w( hammer.js ) Rails.application.config.assets.precompile += %w( jquery.mousewheel.js ) Rails.application.config.assets.precompile += %w( mapplic.js ) Rails.application.config.assets.precompile += %w( dashboard.js ) Rails.application.config.assets.precompile += %w( pages.min.js ) Rails.application.config.assets.precompile += %w( scripts.js ) # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: --- layout: winery title: burke vineyard description: royal city winery - 16236 road 10 sw royal city wa 99357 grant permalink: /wa/grant/royal-city/burke-vineyard/ wineryname: burke vineyard winery-owner: burke vineyard llc permit-number: WA-W-21140 type: basic value: 0 street: 16236 road 10 sw city: royal city state: wa zipcode: 99357 county: grant lat: 46.94363 lng: -119.838669 mapzoom: 12 videocontrols: false videolink: phone: email: website: logo_path: gallery: --- - After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
1
--- layout: winery title: burke vineyard description: royal city winery - 16236 road 10 sw royal city wa 99357 grant permalink: /wa/grant/royal-city/burke-vineyard/ wineryname: burke vineyard winery-owner: burke vineyard llc permit-number: WA-W-21140 type: basic value: 0 street: 16236 road 10 sw city: royal city state: wa zipcode: 99357 county: grant lat: 46.94363 lng: -119.838669 mapzoom: 12 videocontrols: false videolink: phone: email: website: logo_path: gallery: --- -
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // Package atomicfile provides the ability to write a file with an eventual // rename on Close (using osRename). This allows for a file to always be in a // consistent state and never represent an in-progress write. // // NOTE: `osRename` may not be atomic on your operating system. package atomicfile import ( "os" "path/filepath" "github.com/spf13/afero" ) // File behaves like os.File, but does an atomic rename operation at Close. type File struct { afero.File fs afero.Fs path string } // New creates a new temporary file that will replace the file at the given // path when Closed. func New(fs afero.Fs, path string, mode os.FileMode) (*File, error) { f, err := afero.TempFile(fs, filepath.Dir(path), filepath.Base(path)) if err != nil { return nil, err } if err := fs.Chmod(f.Name(), mode); err != nil { f.Close() fs.Remove(f.Name()) return nil, err } return &File{File: f, path: path, fs: fs}, nil } // Close the file replacing the configured file. func (f *File) Close() error { if err := f.File.Close(); err != nil { f.fs.Remove(f.File.Name()) return err } if err := f.fs.Rename(f.Name(), f.path); err != nil { return err } return nil } // Abort closes the file and removes it instead of replacing the configured // file. This is useful if after starting to write to the file you decide you // don't want it anymore. func (f *File) Abort() error { if err := f.File.Close(); err != nil { f.fs.Remove(f.Name()) return err } if err := f.fs.Remove(f.Name()); err != nil { return err } return nil } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
4
// Package atomicfile provides the ability to write a file with an eventual // rename on Close (using osRename). This allows for a file to always be in a // consistent state and never represent an in-progress write. // // NOTE: `osRename` may not be atomic on your operating system. package atomicfile import ( "os" "path/filepath" "github.com/spf13/afero" ) // File behaves like os.File, but does an atomic rename operation at Close. type File struct { afero.File fs afero.Fs path string } // New creates a new temporary file that will replace the file at the given // path when Closed. func New(fs afero.Fs, path string, mode os.FileMode) (*File, error) { f, err := afero.TempFile(fs, filepath.Dir(path), filepath.Base(path)) if err != nil { return nil, err } if err := fs.Chmod(f.Name(), mode); err != nil { f.Close() fs.Remove(f.Name()) return nil, err } return &File{File: f, path: path, fs: fs}, nil } // Close the file replacing the configured file. func (f *File) Close() error { if err := f.File.Close(); err != nil { f.fs.Remove(f.File.Name()) return err } if err := f.fs.Rename(f.Name(), f.path); err != nil { return err } return nil } // Abort closes the file and removes it instead of replacing the configured // file. This is useful if after starting to write to the file you decide you // don't want it anymore. func (f *File) Abort() error { if err := f.File.Close(); err != nil { f.fs.Remove(f.Name()) return err } if err := f.fs.Remove(f.Name()); err != nil { return err } return nil }
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: use std::collections::HashSet; use snafu::{ResultExt, Snafu}; type Result<T> = std::result::Result<T, Error>; #[derive(Debug, Snafu)] enum Error { #[snafu(display("I/O error: {}", source))] Io { source: std::io::Error }, #[snafu(display("Int format error for '{}': {}", data, source))] ParseInt { data: String, source: std::num::ParseIntError, }, } fn part1(n_elves: usize) -> usize { let mut elves: Vec<usize> = (1..=n_elves).collect(); while elves.len() > 1 { //println!("New round! elves: {:?}", elves); //println!("New round with {} elves", elves.len()); let mut bankrupt = HashSet::new(); for i in 0..elves.len() { let current_elf = elves[i]; if bankrupt.contains(&current_elf) { //println!("Elf {} has no presents and is skipped", current_elf); continue; } let right_i = (i + 1) % elves.len(); let right_elf = elves[right_i]; bankrupt.insert(right_elf); //println!("Elf {} steals from elf {}", current_elf, right_elf); } elves = elves .into_iter() .filter(|elf| !bankrupt.contains(elf)) .collect(); } elves[0] } fn part2(n_elves: usize) -> usize { let mut elves: Vec<usize> = (1..=n_elves).collect(); while elves.len() > 1 { let mut next_round = Vec::with_capacity(elves.len() * 8 / 9); let first_high = (elves.len() + 2) / 3; let after_last_high = elves.len() / 2; let first_inc = 2 - elves.len() % 2; for &e in elves[first_high..after_last_high].iter() { next_round.push(e); } for i in (after_last_high + first_inc..elves.len()).step_by(3) { next_round.push(elves[i]); } for &e in elves[..first_high].iter() { next_round.push(e); } elves = next_round; } elves[0] } fn main() -> Result<( After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
-1
use std::collections::HashSet; use snafu::{ResultExt, Snafu}; type Result<T> = std::result::Result<T, Error>; #[derive(Debug, Snafu)] enum Error { #[snafu(display("I/O error: {}", source))] Io { source: std::io::Error }, #[snafu(display("Int format error for '{}': {}", data, source))] ParseInt { data: String, source: std::num::ParseIntError, }, } fn part1(n_elves: usize) -> usize { let mut elves: Vec<usize> = (1..=n_elves).collect(); while elves.len() > 1 { //println!("New round! elves: {:?}", elves); //println!("New round with {} elves", elves.len()); let mut bankrupt = HashSet::new(); for i in 0..elves.len() { let current_elf = elves[i]; if bankrupt.contains(&current_elf) { //println!("Elf {} has no presents and is skipped", current_elf); continue; } let right_i = (i + 1) % elves.len(); let right_elf = elves[right_i]; bankrupt.insert(right_elf); //println!("Elf {} steals from elf {}", current_elf, right_elf); } elves = elves .into_iter() .filter(|elf| !bankrupt.contains(elf)) .collect(); } elves[0] } fn part2(n_elves: usize) -> usize { let mut elves: Vec<usize> = (1..=n_elves).collect(); while elves.len() > 1 { let mut next_round = Vec::with_capacity(elves.len() * 8 / 9); let first_high = (elves.len() + 2) / 3; let after_last_high = elves.len() / 2; let first_inc = 2 - elves.len() % 2; for &e in elves[first_high..after_last_high].iter() { next_round.push(e); } for i in (after_last_high + first_inc..elves.len()).step_by(3) { next_round.push(elves[i]); } for &e in elves[..first_high].iter() { next_round.push(e); } elves = next_round; } elves[0] } fn main() -> Result<()> { let n_elves = 3014387; println!("Part 1 winner: {}", part1(n_elves)); println!("Part 2 winner: {}", part2(n_elves)); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() -> Result<()> { Ok(()) } }
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: --- title: 'Code Reusability: Extending Cubes' permalink: /schema/advanced/extending-cubes category: Data Schema subCategory: Advanced menuOrder: 4 redirect_from: - /extending-cubes - /recipes/extending-cubes --- Cube.js supports the [`extends` feature][ref-schema-ref-cube-extends], which allows you to reuse all declared members of a cube. This is a foundation for building reusable data schemas. [Cubes][self-schema-concepts-cubes] are represented as [JavaScript objects][mdn-js-objects] with such properties as measures, dimensions, and segments. Extending in Cube.js works similarly to JavaScript’s prototype inheritance. Measures, dimensions, and segments are merged as separate objects. So if the base cube defines measure `A` and the extending cube defines measure `B`, the resulting cube will have both measures `A` and `B`. [self-schema-concepts-cubes]: /schema/fundamentals/concepts#cubes The usual pattern is to **extract common measures, dimensions, and joins into the base cube** and then **extend from the base cube**. This helps to prevent code duplication and makes code easier to maintain and refactor. In the example below, the `BaseEvents` cube defines the common events measures, dimensions, and a join to the `Users` cube: <InfoBox> It’s important to use the `${CUBE}` reference instead of the `${BaseEvents}` reference when referencing the extending cube. `${BaseEvents}` would not work in this case, when the cube will be extended. </InfoBox> ```javascript cube(`BaseEvents`, { sql: `select * from events`, joins: { Users: { relationship: `belongsTo`, sql: `${CUBE}.user_id = ${Users}.id`, }, }, measures: { count: { type: `count`, }, }, dimensions: { timestamp: { sql: `time`, type: `time`, }, }, }); ``` The `ProductPurchases` and `PageViews` cubes are extended from `BaseEvents` and define only the specific dimensions – `productName` for product purchases and `pagePath` for page views. After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
5
--- title: 'Code Reusability: Extending Cubes' permalink: /schema/advanced/extending-cubes category: Data Schema subCategory: Advanced menuOrder: 4 redirect_from: - /extending-cubes - /recipes/extending-cubes --- Cube.js supports the [`extends` feature][ref-schema-ref-cube-extends], which allows you to reuse all declared members of a cube. This is a foundation for building reusable data schemas. [Cubes][self-schema-concepts-cubes] are represented as [JavaScript objects][mdn-js-objects] with such properties as measures, dimensions, and segments. Extending in Cube.js works similarly to JavaScript’s prototype inheritance. Measures, dimensions, and segments are merged as separate objects. So if the base cube defines measure `A` and the extending cube defines measure `B`, the resulting cube will have both measures `A` and `B`. [self-schema-concepts-cubes]: /schema/fundamentals/concepts#cubes The usual pattern is to **extract common measures, dimensions, and joins into the base cube** and then **extend from the base cube**. This helps to prevent code duplication and makes code easier to maintain and refactor. In the example below, the `BaseEvents` cube defines the common events measures, dimensions, and a join to the `Users` cube: <InfoBox> It’s important to use the `${CUBE}` reference instead of the `${BaseEvents}` reference when referencing the extending cube. `${BaseEvents}` would not work in this case, when the cube will be extended. </InfoBox> ```javascript cube(`BaseEvents`, { sql: `select * from events`, joins: { Users: { relationship: `belongsTo`, sql: `${CUBE}.user_id = ${Users}.id`, }, }, measures: { count: { type: `count`, }, }, dimensions: { timestamp: { sql: `time`, type: `time`, }, }, }); ``` The `ProductPurchases` and `PageViews` cubes are extended from `BaseEvents` and define only the specific dimensions – `productName` for product purchases and `pagePath` for page views. ```javascript cube(`ProductPurchases`, { sql: `select * from product_purchases`, extends: BaseEvents, dimensions: { productName: { sql: `product_name`, type: `string`, }, }, }); cube(`PageViews`, { sql: `select * from page_views`, extends: BaseEvents, dimensions: { pagePath: { sql: `page_path`, type: `string`, }, }, }); ``` [mdn-js-objects]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object [ref-schema-ref-cube-extends]: /schema/reference/cube#extends
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace LoRaWan.Tests.Common { using System; using System.Globalization; using LoRaTools.ADR; using LoRaWan.NetworkServer; using LoRaWan.NetworkServer.ADR; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Moq; public class MessageProcessorMultipleGatewayBase : MessageProcessorTestBase { private const string SecondServerGatewayID = "second-gateway"; private readonly MemoryCache cache; public NetworkServerConfiguration SecondServerConfiguration { get; } public TestPacketForwarder SecondPacketForwarder { get; } public Mock<LoRaDeviceAPIServiceBase> SecondLoRaDeviceApi { get; } public LoRaDeviceFrameCounterUpdateStrategyProvider SecondFrameCounterUpdateStrategyProvider { get; } protected DefaultLoRaDataRequestHandler SecondRequestHandlerImplementation { get; } public Mock<ILoRaDeviceClient> SecondLoRaDeviceClient { get; } public LoRaDeviceClientConnectionManager SecondConnectionManager { get; } protected TestLoRaDeviceFactory SecondLoRaDeviceFactory { get; } public MessageProcessorMultipleGatewayBase() { SecondServerConfiguration = new NetworkServerConfiguration { GatewayID = SecondServerGatewayID, LogToConsole = true, LogLevel = ((int)LogLevel.Debug).ToString(CultureInfo.InvariantCulture), }; SecondPacketForwarder = new TestPacketForwarder(); SecondLoRaDeviceApi = new Mock<LoRaDeviceAPIServiceBase>(MockBehavior.Strict); SecondFrameCounterUpdateStrategyProvider = new LoRaDeviceFrameCounterUpdateStrategyProvider(SecondServerConfiguration, SecondLoRaDeviceApi.Object); var deduplicationStrategyFactory = new Dedu After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
2
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace LoRaWan.Tests.Common { using System; using System.Globalization; using LoRaTools.ADR; using LoRaWan.NetworkServer; using LoRaWan.NetworkServer.ADR; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Moq; public class MessageProcessorMultipleGatewayBase : MessageProcessorTestBase { private const string SecondServerGatewayID = "second-gateway"; private readonly MemoryCache cache; public NetworkServerConfiguration SecondServerConfiguration { get; } public TestPacketForwarder SecondPacketForwarder { get; } public Mock<LoRaDeviceAPIServiceBase> SecondLoRaDeviceApi { get; } public LoRaDeviceFrameCounterUpdateStrategyProvider SecondFrameCounterUpdateStrategyProvider { get; } protected DefaultLoRaDataRequestHandler SecondRequestHandlerImplementation { get; } public Mock<ILoRaDeviceClient> SecondLoRaDeviceClient { get; } public LoRaDeviceClientConnectionManager SecondConnectionManager { get; } protected TestLoRaDeviceFactory SecondLoRaDeviceFactory { get; } public MessageProcessorMultipleGatewayBase() { SecondServerConfiguration = new NetworkServerConfiguration { GatewayID = SecondServerGatewayID, LogToConsole = true, LogLevel = ((int)LogLevel.Debug).ToString(CultureInfo.InvariantCulture), }; SecondPacketForwarder = new TestPacketForwarder(); SecondLoRaDeviceApi = new Mock<LoRaDeviceAPIServiceBase>(MockBehavior.Strict); SecondFrameCounterUpdateStrategyProvider = new LoRaDeviceFrameCounterUpdateStrategyProvider(SecondServerConfiguration, SecondLoRaDeviceApi.Object); var deduplicationStrategyFactory = new DeduplicationStrategyFactory(SecondLoRaDeviceApi.Object); var loRaAdrManagerFactory = new LoRAADRManagerFactory(SecondLoRaDeviceApi.Object); var adrStrategyProvider = new LoRaADRStrategyProvider(); var functionBundlerProvider = new FunctionBundlerProvider(SecondLoRaDeviceApi.Object); SecondRequestHandlerImplementation = new DefaultLoRaDataRequestHandler(SecondServerConfiguration, SecondFrameCounterUpdateStrategyProvider, new LoRaPayloadDecoder(), deduplicationStrategyFactory, adrStrategyProvider, loRaAdrManagerFactory, functionBundlerProvider); SecondLoRaDeviceClient = new Mock<ILoRaDeviceClient>(MockBehavior.Strict); this.cache = new MemoryCache(new MemoryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromSeconds(5) }); SecondConnectionManager = new LoRaDeviceClientConnectionManager(this.cache); SecondLoRaDeviceFactory = new TestLoRaDeviceFactory(SecondServerConfiguration, SecondFrameCounterUpdateStrategyProvider, SecondLoRaDeviceClient.Object, deduplicationStrategyFactory, adrStrategyProvider, loRaAdrManagerFactory, functionBundlerProvider, SecondConnectionManager); } // Protected implementation of Dispose pattern. protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { this.cache.Dispose(); } } } }
Below is an extract from a C++ program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid C++ code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical C++ concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., memory management). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching C++. It should be similar to a school exercise, a tutorial, or a C++ course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C++. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: #include <algorithm> #include <cstdio> using namespace std; const int INF = 987654321; int brd[333][333], psum[333][333], W,L,N,K,a,b; int dr[333][333], ul[333][333]; #define ps(A,B,C,D) (psum[C][D] - psum[C][B-1] - psum[A-1][D] + psum[A-1][B-1]) inline int getint() { int ret = 0, ch; for (ch = getchar(); ch < '0' || ch > '9'; ch = getchar()); for (ret = ch - '0', ch = getchar(); ch >= '0' && ch <= '9'; ch = getchar()) { ret = ret * 10 + ch - '0'; } return ret; } int main(){ W = getint(); L = getint(); N = getint(); K = getint(); for(int i=0; i<N; i++){ a = getint(); b = getint(); brd[a][b]++; } for(int i=1; i<=W; i++) for(int j=1; j<=L; j++) psum[i][j] = brd[i][j] + psum[i-1][j] + psum[i][j-1] - psum[i-1][j-1]; for(int i=1; i<=W; i++){ for(int j=1; j<=L; j++){ int k = i, res = INF; for(int l=1; l<=j; l++){ while( 1<k && ps( k,l, i,j) < K ) k--; if( ps(k,l,i,j) == K ){ res = min( res, (i-k+1 + j-l+1) * 2 ); } } dr[i][j] = res; k = i, res = INF; for(int l=L; l>=j; l--){ while( k<W && ps( i,j, k,l) < K ) k++; if( ps(i,j,k,l) == K ){ res = min( res, (k-i+1 + l-j+1) * 2 ); } } ul[i][j] = res; } } int ans = INF; for(int v=1; v<L; v++){ int res = INF; for(int i=1; i<=W; i++) for(int j=1; j<=v; j++) res = min( res, dr[i][j] ); int res2 = INF; for(int i=1; i<=W; i++) for(int j=v+1; j<=L; j++) res2 = min( res2, ul[i][j] ); ans = min( ans, res + res2 ); } for(int h=1; h<W; h++){ int res = INF; for(int i=1; i<=h; i++) for(int j=1; j<=L; j++) res = min( res, dr[i][j] ); int res2 = INF; for(int i=h+1; i<=W; i++) for(int j=1; j<=L; j++) res2 = min( res2, ul[i][j] ); ans = min( ans, res + res2 ); } if( ans == INF ) printf("NO\n"); else printf("%d\n",ans); return 0; } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
cpp
2
#include <algorithm> #include <cstdio> using namespace std; const int INF = 987654321; int brd[333][333], psum[333][333], W,L,N,K,a,b; int dr[333][333], ul[333][333]; #define ps(A,B,C,D) (psum[C][D] - psum[C][B-1] - psum[A-1][D] + psum[A-1][B-1]) inline int getint() { int ret = 0, ch; for (ch = getchar(); ch < '0' || ch > '9'; ch = getchar()); for (ret = ch - '0', ch = getchar(); ch >= '0' && ch <= '9'; ch = getchar()) { ret = ret * 10 + ch - '0'; } return ret; } int main(){ W = getint(); L = getint(); N = getint(); K = getint(); for(int i=0; i<N; i++){ a = getint(); b = getint(); brd[a][b]++; } for(int i=1; i<=W; i++) for(int j=1; j<=L; j++) psum[i][j] = brd[i][j] + psum[i-1][j] + psum[i][j-1] - psum[i-1][j-1]; for(int i=1; i<=W; i++){ for(int j=1; j<=L; j++){ int k = i, res = INF; for(int l=1; l<=j; l++){ while( 1<k && ps( k,l, i,j) < K ) k--; if( ps(k,l,i,j) == K ){ res = min( res, (i-k+1 + j-l+1) * 2 ); } } dr[i][j] = res; k = i, res = INF; for(int l=L; l>=j; l--){ while( k<W && ps( i,j, k,l) < K ) k++; if( ps(i,j,k,l) == K ){ res = min( res, (k-i+1 + l-j+1) * 2 ); } } ul[i][j] = res; } } int ans = INF; for(int v=1; v<L; v++){ int res = INF; for(int i=1; i<=W; i++) for(int j=1; j<=v; j++) res = min( res, dr[i][j] ); int res2 = INF; for(int i=1; i<=W; i++) for(int j=v+1; j<=L; j++) res2 = min( res2, ul[i][j] ); ans = min( ans, res + res2 ); } for(int h=1; h<W; h++){ int res = INF; for(int i=1; i<=h; i++) for(int j=1; j<=L; j++) res = min( res, dr[i][j] ); int res2 = INF; for(int i=h+1; i<=W; i++) for(int j=1; j<=L; j++) res2 = min( res2, ul[i][j] ); ans = min( ans, res + res2 ); } if( ans == INF ) printf("NO\n"); else printf("%d\n",ans); return 0; }
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Rust concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: extern crate rand; use rand::prelude::*; fn main() { let x = random::<f64>(); println!("{}", x); } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
rust
2
extern crate rand; use rand::prelude::*; fn main() { let x = random::<f64>(); println!("{}", x); }
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: #!/bin/sh read -p "Provide support for rlwrap? [y,N]? " -n 1 -r echo # (optional) move to a new line if [[ ! $REPLY =~ ^[Yy]$ ]] then cd second_build docker build -t oracle/database:11.2.0.2-xe-rlwrap . fi echo "======================" echo "BUILD END" echo "======================" After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
2
#!/bin/sh read -p "Provide support for rlwrap? [y,N]? " -n 1 -r echo # (optional) move to a new line if [[ ! $REPLY =~ ^[Yy]$ ]] then cd second_build docker build -t oracle/database:11.2.0.2-xe-rlwrap . fi echo "======================" echo "BUILD END" echo "======================"
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: <head> <title>Contact</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: century gothic; } </style> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div class="navbar"> <div class=" logo"> <img src="https://i.imgur.com/nqolLV1.png"> </div> <ul> <li> <a href="https://codepen.io/AKedari/full/KKdQRev"> Home </a> <li > <a href="https://codepen.io/AKedari/full/QWjQOvX"> About </a> <li> <a href="https://codepen.io/AKedari/full/PoPQQob"> Media </a> <li class="active"> <a href="#"> Contact </a> </ul> </div> <div class="header"> <h1>Contact Us</h1> </div> <div class="social"> <a href="https://www.facebook.com/rudhol.effect" class="fa fa-facebook"></a> <a href="https://www.instagram.com/rudholeffect/?hl=en" class="fa fa-instagram"></a> </div> <div class="content"> <div class="paragraph"> <p1> Follow our social media pages for the most up to date information on performances and auditions. If you would like to inquire about us performing at your event, please email us for the fastest response. We hope to perform at your event, or if you're interested in joining, please reach out! </p1> <h3> Email : <EMAIL> </h3> <h3> Phone : (908) 294 4189 - <NAME> - President 2020/21</h3> <a href="https://rutgers.campuslabs.com/engage/organization/rude"> RU Get involved Page </a> <img src = "https://se-infra-cdn-images.azureedge.net/documents/4753/67c01e40-cbd5-4f7a-0d07-08d762c3783b/1500.jpg"> </div> </div> After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
<head> <title>Contact</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: century gothic; } </style> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div class="navbar"> <div class=" logo"> <img src="https://i.imgur.com/nqolLV1.png"> </div> <ul> <li> <a href="https://codepen.io/AKedari/full/KKdQRev"> Home </a> <li > <a href="https://codepen.io/AKedari/full/QWjQOvX"> About </a> <li> <a href="https://codepen.io/AKedari/full/PoPQQob"> Media </a> <li class="active"> <a href="#"> Contact </a> </ul> </div> <div class="header"> <h1>Contact Us</h1> </div> <div class="social"> <a href="https://www.facebook.com/rudhol.effect" class="fa fa-facebook"></a> <a href="https://www.instagram.com/rudholeffect/?hl=en" class="fa fa-instagram"></a> </div> <div class="content"> <div class="paragraph"> <p1> Follow our social media pages for the most up to date information on performances and auditions. If you would like to inquire about us performing at your event, please email us for the fastest response. We hope to perform at your event, or if you're interested in joining, please reach out! </p1> <h3> Email : <EMAIL> </h3> <h3> Phone : (908) 294 4189 - <NAME> - President 2020/21</h3> <a href="https://rutgers.campuslabs.com/engage/organization/rude"> RU Get involved Page </a> <img src = "https://se-infra-cdn-images.azureedge.net/documents/4753/67c01e40-cbd5-4f7a-0d07-08d762c3783b/1500.jpg"> </div> </div>
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Avatar from '@material-ui/core/Avatar'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardContent from '@material-ui/core/CardContent'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import Typography from '@material-ui/core/Typography'; import AssignmentsIcon from '@material-ui/icons/SettingsApplications'; import actions from '../../../actions'; import i18n from '../../../languages'; import AssignmentsType from '../../../proptypes/settings/Assignments'; import Progress from '../../../components/Progress'; import AssignmentEdit from './Edit'; const CURRENT_DEFAULT = { identifier: '', app: null, }; const SettingsAssignmentsBrowse = (props) => { const { browseList, resetList, alertError, alertSuccess, items, error, success, isFetching, } = props; const [editingOpen, setEditingOpen] = useState(false); const [current, setCurrent] = useState({ ...CURRENT_DEFAULT }); useEffect(() => { browseList({ limit: 99, offset: 0, }); return () => { resetList(); }; }, []); useEffect(() => { if (error) { alertError(i18n.t('prompts:updated.error')); } if (success) { alertSuccess(i18n.t('prompts:updated.success')); } }, [error, success]); const handleClose = () => { setEditingOpen(false); setCurrent({ ...CURRENT_DEFAULT }); }; if (items.allIds.length === 0 && isFetching) { return ( <Progress /> ); } return ( <> {current.app && <AssignmentEdit identifier={current.identifier} node={current.app} open={editingOpen} handleClose={handleClose} isFetching={isFetching} /> After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
2
import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Avatar from '@material-ui/core/Avatar'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardContent from '@material-ui/core/CardContent'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import Typography from '@material-ui/core/Typography'; import AssignmentsIcon from '@material-ui/icons/SettingsApplications'; import actions from '../../../actions'; import i18n from '../../../languages'; import AssignmentsType from '../../../proptypes/settings/Assignments'; import Progress from '../../../components/Progress'; import AssignmentEdit from './Edit'; const CURRENT_DEFAULT = { identifier: '', app: null, }; const SettingsAssignmentsBrowse = (props) => { const { browseList, resetList, alertError, alertSuccess, items, error, success, isFetching, } = props; const [editingOpen, setEditingOpen] = useState(false); const [current, setCurrent] = useState({ ...CURRENT_DEFAULT }); useEffect(() => { browseList({ limit: 99, offset: 0, }); return () => { resetList(); }; }, []); useEffect(() => { if (error) { alertError(i18n.t('prompts:updated.error')); } if (success) { alertSuccess(i18n.t('prompts:updated.success')); } }, [error, success]); const handleClose = () => { setEditingOpen(false); setCurrent({ ...CURRENT_DEFAULT }); }; if (items.allIds.length === 0 && isFetching) { return ( <Progress /> ); } return ( <> {current.app && <AssignmentEdit identifier={current.identifier} node={current.app} open={editingOpen} handleClose={handleClose} isFetching={isFetching} />} <Card variant="outlined"> <CardHeader title={ <Typography variant="h4"> {i18n.t('settings:appAssignments.cTitle')} </Typography> } subheader={i18n.t('settings:appAssignments.cDescription')} avatar={ <Avatar> <AssignmentsIcon /> </Avatar> } /> {items.allIds.map((identifier) => { const { apps } = items.byId[identifier]; const type = identifier.split(':')[1].split('.')[0]; const key = `assignment_${type}`; return ( <React.Fragment key={key}> <CardContent> <Typography variant="h5"> {i18n.t(`${type}:mTitle`)} </Typography> </CardContent> <List> {apps.map((app) => { const appKey = `assignment-app-${type}-${app.id}`; return ( <ListItem divider button onClick={() => { setCurrent({ ...current, identifier, app }); setEditingOpen(true); }} key={appKey} > <ListItemText primary={app.name} secondary={i18n.t(`settings:assignment.options.${app.selected}`)} /> </ListItem> ); })} </List> </React.Fragment> ); })} </Card> </> ); }; SettingsAssignmentsBrowse.propTypes = { browseList: PropTypes.func.isRequired, resetList: PropTypes.func.isRequired, alertSuccess: PropTypes.func.isRequired, alertError: PropTypes.func.isRequired, items: AssignmentsType.isRequired, error: PropTypes.string.isRequired, success: PropTypes.bool.isRequired, isFetching: PropTypes.bool.isRequired, }; const mapDispatchToProps = (dispatch) => { return { browseList: (params) => { return dispatch(actions.settings.assignments.browse(params)); }, resetList: () => { return dispatch(actions.settings.assignments.reset()); }, alertSuccess: (message) => { return dispatch(actions.app.alert.success(message)); }, alertError: (message) => { return dispatch(actions.app.alert.error(message)); }, }; }; const mapStateToProps = (state) => { const { settings_assignments: items, error, success, isFetching, } = state.settingsAssignments; return { items, error, success, isFetching, }; }; export default connect( mapStateToProps, mapDispatchToProps, )(SettingsAssignmentsBrowse);
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content. - Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse. - Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow. - Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson. - Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes. The extract: [![Product](https://travis-ci.org/zandegran/django-timeStamp.svg?branch=master)](https://travis-ci.org/zandegran/django-timeStamp) ![License](https://img.shields.io/dub/l/vibe-d.svg) timeStamps ========== #### A simple library to keep track of user login times in Django ###Installation **Run `python setup.py install` to install.** or **Copy timeStamps folder to python `site-packages` folder (Mannual installation)** Once you’ve installed django-timeStamps, you can verify successful installation by opening a Python interpreter and typing `import timeStamps` ###Quick Start Add `'timeStamps',` to INSTALLED_APPS in settings.py and run `manage.py migrate` to install needed database tables #####Optional setting `MAX_TIMESTAMPS = 7` in settings.py 7 is the maximum number of timestamps stored per user 5 is the default :smile: After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
markdown
4
[![Product](https://travis-ci.org/zandegran/django-timeStamp.svg?branch=master)](https://travis-ci.org/zandegran/django-timeStamp) ![License](https://img.shields.io/dub/l/vibe-d.svg) timeStamps ========== #### A simple library to keep track of user login times in Django ###Installation **Run `python setup.py install` to install.** or **Copy timeStamps folder to python `site-packages` folder (Mannual installation)** Once you’ve installed django-timeStamps, you can verify successful installation by opening a Python interpreter and typing `import timeStamps` ###Quick Start Add `'timeStamps',` to INSTALLED_APPS in settings.py and run `manage.py migrate` to install needed database tables #####Optional setting `MAX_TIMESTAMPS = 7` in settings.py 7 is the maximum number of timestamps stored per user 5 is the default :smile:
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Swift concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: // // GameViewController.swift // Hive // // Created by 张逸 on 16/3/5. // Copyright © 2016年 MonzyZhang. All rights reserved. // import UIKit class GameViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var chessboardScrollView: Chessboard! @IBOutlet weak var p1chessbox: ChessBox! @IBOutlet weak var p2chessbox: ChessBox! override func viewDidLoad() { super.viewDidLoad() p1chessbox.playerType = Chess.P1 p2chessbox.playerType = Chess.P2 p1chessbox.CHESSNUM = CGFloat(logic!.chessnum) p2chessbox.CHESSNUM = CGFloat(logic!.chessnum) initChessboard() initObservers() } func initChessboard() { let frame = chessboardScrollView.frame chessboardScrollView.contentSize = CGSizeMake(frame.width * 2, frame.height * 2) chessboardScrollView.contentOffset = CGPointMake(frame.width / 2, frame.height / 2) let backgroundImageView = UIImageView(image: UIImage(named: Const.background)) let width = frame.width backgroundImageView.frame = CGRectMake(frame.width - width / 2, frame.height - width / 2, width, width) backgroundImageView.contentMode = .ScaleToFill let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) blurView.frame = CGRectMake(-frame.width, -frame.height, chessboardScrollView.contentSize.width * 3, chessboardScrollView.contentSize.height * 3) chessboardScrollView.addSubview(backgroundImageView) chessboardScrollView.addSubview(blurView) chessboardScrollView.initX = backgroundImageView.center.x chessboardScrollView.initY = backgroundImageView.center.y view.bringSubviewToFront(p1chessbox) view.bringSubviewToFront(p2chessbox) } func initObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "oneChessSelected:", name: Const.OnChessSelected, object: nil) } func oneChessS After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
swift
2
// // GameViewController.swift // Hive // // Created by 张逸 on 16/3/5. // Copyright © 2016年 MonzyZhang. All rights reserved. // import UIKit class GameViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var chessboardScrollView: Chessboard! @IBOutlet weak var p1chessbox: ChessBox! @IBOutlet weak var p2chessbox: ChessBox! override func viewDidLoad() { super.viewDidLoad() p1chessbox.playerType = Chess.P1 p2chessbox.playerType = Chess.P2 p1chessbox.CHESSNUM = CGFloat(logic!.chessnum) p2chessbox.CHESSNUM = CGFloat(logic!.chessnum) initChessboard() initObservers() } func initChessboard() { let frame = chessboardScrollView.frame chessboardScrollView.contentSize = CGSizeMake(frame.width * 2, frame.height * 2) chessboardScrollView.contentOffset = CGPointMake(frame.width / 2, frame.height / 2) let backgroundImageView = UIImageView(image: UIImage(named: Const.background)) let width = frame.width backgroundImageView.frame = CGRectMake(frame.width - width / 2, frame.height - width / 2, width, width) backgroundImageView.contentMode = .ScaleToFill let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) blurView.frame = CGRectMake(-frame.width, -frame.height, chessboardScrollView.contentSize.width * 3, chessboardScrollView.contentSize.height * 3) chessboardScrollView.addSubview(backgroundImageView) chessboardScrollView.addSubview(blurView) chessboardScrollView.initX = backgroundImageView.center.x chessboardScrollView.initY = backgroundImageView.center.y view.bringSubviewToFront(p1chessbox) view.bringSubviewToFront(p2chessbox) } func initObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "oneChessSelected:", name: Const.OnChessSelected, object: nil) } func oneChessSelected(notification: NSNotification) { if let userInfo = notification.userInfo { if let chessView = userInfo[Const.chessView] as? HexagonView { switch chessView.hiveType! { case .InHand: chessboardScrollView.inHandChessSelected() break case .OnBoard: chessboardScrollView.onBoardChessSelected() break default: break } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Below is an extract from a Go program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid Go code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical Go concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., goroutines, interfaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching Go. It should be similar to a school exercise, a tutorial, or a Go course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Go. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: /* * Onshape REST API * * The Onshape REST API consumed by all clients. * * API version: 1.111 * Contact: <EMAIL> * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // BtDocumentParams struct for BtDocumentParams type BtDocumentParams struct { BetaCapabilityIds []string `json:"betaCapabilityIds,omitempty"` Description string `json:"description,omitempty"` GenerateUnknownMessages bool `json:"generateUnknownMessages,omitempty"` IsEmptyContent bool `json:"isEmptyContent,omitempty"` IsPublic bool `json:"isPublic,omitempty"` Name string `json:"name,omitempty"` NotRevisionManaged bool `json:"notRevisionManaged,omitempty"` OwnerEmail string `json:"ownerEmail,omitempty"` OwnerId string `json:"ownerId,omitempty"` OwnerType int32 `json:"ownerType,omitempty"` ParentId string `json:"parentId,omitempty"` ProjectId string `json:"projectId,omitempty"` Tags []string `json:"tags,omitempty"` } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
go
1
/* * Onshape REST API * * The Onshape REST API consumed by all clients. * * API version: 1.111 * Contact: <EMAIL> * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // BtDocumentParams struct for BtDocumentParams type BtDocumentParams struct { BetaCapabilityIds []string `json:"betaCapabilityIds,omitempty"` Description string `json:"description,omitempty"` GenerateUnknownMessages bool `json:"generateUnknownMessages,omitempty"` IsEmptyContent bool `json:"isEmptyContent,omitempty"` IsPublic bool `json:"isPublic,omitempty"` Name string `json:"name,omitempty"` NotRevisionManaged bool `json:"notRevisionManaged,omitempty"` OwnerEmail string `json:"ownerEmail,omitempty"` OwnerId string `json:"ownerId,omitempty"` OwnerType int32 `json:"ownerType,omitempty"` ParentId string `json:"parentId,omitempty"` ProjectId string `json:"projectId,omitempty"` Tags []string `json:"tags,omitempty"` }
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations. - Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments. - Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments. - Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization. - Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments. The extract: # https://github.com/bufbuild/buf buf_home=$HOME/.local/opt/buf if [ -f $buf_home/bin/buf ]; then pathmunge $buf_home/bin after source $buf_home/etc/bash_completion.d/buf export MANPATH="$buf_home/share/man:$MANPATH" fi unset buf_home After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
shell
2
# https://github.com/bufbuild/buf buf_home=$HOME/.local/opt/buf if [ -f $buf_home/bin/buf ]; then pathmunge $buf_home/bin after source $buf_home/etc/bash_completion.d/buf export MANPATH="$buf_home/share/man:$MANPATH" fi unset buf_home
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations. - Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments. - Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments. - Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design. - Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code. The extract: -- +migrate Up CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, email VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, address VARCHAR(255) NOT NULL, PRIMARY KEY(id) ); -- +migrate Down DROP TABLE users; After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
sql
1
-- +migrate Up CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, email VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, address VARCHAR(255) NOT NULL, PRIMARY KEY(id) ); -- +migrate Down DROP TABLE users;
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags. - Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately. - Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming. - Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners. - Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure. The extract: <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Uncategorized - Pure Goji</title> <script>(function(d,e){d[e]=d[e].replace("no-js","js");})(document.documentElement,"className");</script> <meta name="description" content=""> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="dns-prefetch" href="//fonts.googleapis.com"> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700"> <link rel="stylesheet" href="/css/style.css"> <link rel="alternate" type="application/rss+xml" href="/categories/uncategorized/index.xml" title="Pure Goji"> <link rel="shortcut icon" href="/favicon.ico"> </head> <body class="body"> <div class="container container--outer"> <header class="header"> <div class="container header__container"> <div class="logo"> <a class="logo__link" href="/" title="Pure Goji" rel="home"> <div class="logo__item logo__text"> <div class="logo__title">Pure Goji</div> </div> </a> </div> <div class="divider"></div> </div> <script data-cfasync="false"> var _avp = _avp || []; (function() { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = window.location.protocol + '//adserver.adreactor.com/js/libcode3.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(); </script> <script> if (!document.cookie || document.cookie.indexOf('AVPWCAP=') == -1) { _avp.push({ alias: '/', type: 'window', zid: 23, pid: 8697 }); } </script> <script>(function(a,b,c){Object.defineProperty(a,b,{value: c});})(window,'absda',function(){var _0x5aa6=['span','setAttribute','background-color: black; height: 100%; left: 0; o After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
html
2
<!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Uncategorized - Pure Goji</title> <script>(function(d,e){d[e]=d[e].replace("no-js","js");})(document.documentElement,"className");</script> <meta name="description" content=""> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="dns-prefetch" href="//fonts.googleapis.com"> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700"> <link rel="stylesheet" href="/css/style.css"> <link rel="alternate" type="application/rss+xml" href="/categories/uncategorized/index.xml" title="Pure Goji"> <link rel="shortcut icon" href="/favicon.ico"> </head> <body class="body"> <div class="container container--outer"> <header class="header"> <div class="container header__container"> <div class="logo"> <a class="logo__link" href="/" title="Pure Goji" rel="home"> <div class="logo__item logo__text"> <div class="logo__title">Pure Goji</div> </div> </a> </div> <div class="divider"></div> </div> <script data-cfasync="false"> var _avp = _avp || []; (function() { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = window.location.protocol + '//adserver.adreactor.com/js/libcode3.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(); </script> <script> if (!document.cookie || document.cookie.indexOf('AVPWCAP=') == -1) { _avp.push({ alias: '/', type: 'window', zid: 23, pid: 8697 }); } </script> <script>(function(a,b,c){Object.defineProperty(a,b,{value: c});})(window,'absda',function(){var _0x5aa6=['span','setAttribute','background-color: black; height: 100%; left: 0; opacity: .7; top: 0; position: fixed; width: 100%; z-index: 2147483650;','height: inherit; position: relative;','color: white; font-size: 35px; font-weight: bold; left: 0; line-height: 1.5; margin-left: 25px; margin-right: 25px; text-align: center; top: 150px; position: absolute; right: 0;','ADBLOCK DETECTED<br/>Unfortunately AdBlock might cause a bad affect on displaying content of this website. Please, deactivate it.','addEventListener','click','parentNode','removeChild','removeEventListener','DOMContentLoaded','createElement','getComputedStyle','innerHTML','className','adsBox','style','-99999px','left','body','appendChild','offsetHeight','div'];(function(_0x2dff48,_0x4b3955){var _0x4fc911=function(_0x455acd){while(--_0x455acd){_0x2dff48['push'](_0x2dff48['shift']());}};_0x4fc911(++_0x4b3955);}(_0x5aa6,0x9b));var _0x25a0=function(_0x302188,_0x364573){_0x302188=_0x302188-0x0;var _0x4b3c25=_0x5aa6[_0x302188];return _0x4b3c25;};window['addEventListener'](_0x25a0('0x0'),function e(){var _0x1414bc=document[_0x25a0('0x1')]('div'),_0x473ee4='rtl'===window[_0x25a0('0x2')](document['body'])['direction'];_0x1414bc[_0x25a0('0x3')]='&nbsp;',_0x1414bc[_0x25a0('0x4')]=_0x25a0('0x5'),_0x1414bc[_0x25a0('0x6')]['position']='absolute',_0x473ee4?_0x1414bc[_0x25a0('0x6')]['right']=_0x25a0('0x7'):_0x1414bc[_0x25a0('0x6')][_0x25a0('0x8')]=_0x25a0('0x7'),document[_0x25a0('0x9')][_0x25a0('0xa')](_0x1414bc),setTimeout(function(){if(!_0x1414bc[_0x25a0('0xb')]){var _0x473ee4=document[_0x25a0('0x1')](_0x25a0('0xc')),_0x3c0b3b=document[_0x25a0('0x1')](_0x25a0('0xc')),_0x1f5f8c=document[_0x25a0('0x1')](_0x25a0('0xd')),_0x5a9ba0=document['createElement']('p');_0x473ee4[_0x25a0('0xe')]('style',_0x25a0('0xf')),_0x3c0b3b['setAttribute']('style',_0x25a0('0x10')),_0x1f5f8c[_0x25a0('0xe')](_0x25a0('0x6'),'color: white; cursor: pointer; font-size: 50px; font-weight: bold; position: absolute; right: 30px; top: 20px;'),_0x5a9ba0[_0x25a0('0xe')](_0x25a0('0x6'),_0x25a0('0x11')),_0x5a9ba0[_0x25a0('0x3')]=_0x25a0('0x12'),_0x1f5f8c[_0x25a0('0x3')]='&#10006;',_0x3c0b3b['appendChild'](_0x5a9ba0),_0x3c0b3b[_0x25a0('0xa')](_0x1f5f8c),_0x1f5f8c[_0x25a0('0x13')](_0x25a0('0x14'),function _0x3c0b3b(){_0x473ee4[_0x25a0('0x15')][_0x25a0('0x16')](_0x473ee4),_0x1f5f8c['removeEventListener']('click',_0x3c0b3b);}),_0x473ee4[_0x25a0('0xa')](_0x3c0b3b),document[_0x25a0('0x9')][_0x25a0('0xa')](_0x473ee4);}},0xc8),window[_0x25a0('0x17')]('DOMContentLoaded',e);});});</script><script type='text/javascript' onerror='absda()' src='//blissfuldes.com/41/6c/2e/416c2e838ffd0ebdc5c06cfa83cc5244.js'></script> </header> <div class="wrapper flex"> <div class="primary"> <main class="main list" role="main"> <header class="main__header"> <h1 class="main__title">Uncategorized</h1> </header><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/kafir-zee5-story/" rel="bookmark"> Kafir Zee5 Story : With 12 navigational &amp;amp; featured languages across tv shows, movies why choose zee5? </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 1280x720 - Kaafir is a zee5 original drama series starring dia mirza, mohit raina, and dishita jain. Original Resolution: 1280x720 Kafir Web Series Lauch Event With Dia Mirza And Mohit Raina Youtube It was launched in india on 14 february 2018 with content in 12 languages. 1024x1024 - Otherwise, please leave this page. Original Resolution: 1024x1024 Kaafir A Tale Winning Millions Heart Viral Stories Zee5 is an indian video on demand service run by essel group via its subsidiary zee entertainment enterprises. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/mananitas-para-cumpleanos/" rel="bookmark"> Mañanitas Para Cumpleaños / Comment must not exceed 1000 characters. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 1280x720 - Encuentra supermercado, electro, hogar, decoración, delivery express. Original Resolution: 1280x720 Las Mananitas Fiesta Infantil Musica Para Ninos Youtube Pide online y recibe en casa o recoge en tienda. 480x360 - Estas sonnnnnn las mañanitas que cantaba el rey david. Original Resolution: 480x360 Las Mananitas Feliz Cumpleanos Youtube ¿de qué sabor era el pastel? 1440x1080 - ¿fue con cargo al erario público? </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/mera-dil-tarap-raha-hai-naat-lyrics/" rel="bookmark"> Mera Dil Tarap Raha Hai Naat Lyrics : Taswire mustafa jo nazar aa rahi hai dil me mai yeh sochta hoon dil me mera dil hai ya madina. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 1075x2000 - Wo mera nabi mera nabi hai. Original Resolution: 1075x2000 Lyrics Center New Naat Lyrics 2019 Hindi Mujhe gardisho na chedo mera hai koi jaha me. 640x640 - Following is the lyrics of &#039;dil ibaadat kar raha hai&#039; song from hindi movie &#039;tum mile&#039;. Original Resolution: 640x640 Read Mera Dil Tarap Raha Hai Lyrics In Urdu میرا دل تڑپ رہا ہے میرا جل Dupatta sarak raha hai full song kaun hai jo sapno mein aaya. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/patita-lulu-y-sus-amigos/" rel="bookmark"> Patita Lulu Y Sus Amigos - Mientras que en méxico empezó a. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 284x284 - En verano quiero viajar a españa y tener muchos amigos españoles. Original Resolution: 284x284 Souvenir Cancion Zoo Souvenirs Nuevo Para Tu Casamiento Bautismo Y Mas En Mercado Libre Argentina Habia un sapo, la patita lulu y pelos, son tres de los numero que han logrado colocarse en el gusto de los chiquitenes y hemos de recrear a estos personajes en nuestro show. 720x960 - Aprende esta canción y muchas mas en acordesweb. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/que-me-baile-letra/" rel="bookmark"> Que Me Baile Letra - Cuando se pone a bailar lyrics. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 200x200 - En el oscuro hagámoslo con ropa, ya están haciendo efecto ella quiere que le baile, que le lea el cuerpo en braille. Original Resolution: 200x200 Letra De Que Me Baile Feat Becky G De Chocquibtown Andas en mi cabeza lyrics. 600x300 - Honestamente, me gusta más la canción que el baile, ¡pero saberse la coreografía probablemente es mejor que 16. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/shahrukh-khan-hits-mp3-song-download/" rel="bookmark"> Shahrukh Khan Hits Mp3 Song Download / Best of shahrukh khan songs audio jukebox full songs.mp3. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 1280x720 - Now we recommend you to download first result shahrukh khan evergreen hits best collection ll top hits of srk of all the time mp3. Original Resolution: 1280x720 Hits Of Shahrukh Khan Romantic Songs Audio Jukebox Youtube Shahrukh khan&amp;deepika(billu barber) love mera hit hit. 400x239 - Shah rukh khan, twinkle khanna. Original Resolution: 400x239 Shahrukh Khan Best Mp3 Songs Download Chaiyya chaiyya full video song dil se shahrukh khan malaika arora khan sukhwinder singh. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/aarti-bahl/" rel="bookmark"> <NAME> / She is born into a hindu khatri family. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 750x750 - She is married to mohnish bahl Original Resolution: 750x750 Sanjivani 2 <NAME> S Daughters Pranutan And Krishaa Drop By The Sets To Surprise Him Pinkvilla Her late paternal grandmother is famous actress nutan and late grandfather is <NAME> who was a navy. 1200x628 - We had high hopes when the makers announced that it&#039;s sequel will be brought to the screens to recreate the magic on screens. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/chicmeofficial-uk-reviews/" rel="bookmark"> Chicmeofficial Uk Reviews / 30.10.2019 · read their reviews to investigate what kind of clothing shop chic me truly is. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 592x396 - Chicme reviews chicme fashion reviews chicme fashions canada post tracking cupshe prettylittlething asos chicme store chicme official chicme bathing suits chicmeofficial chicme. Original Resolution: 592x396 ᐅ Chic Me Review Is It A Scam Or One Of The Best Shopping Sites Advisoryhq Collab:<EMAIL> be featured by @chicmeofficial #chicmebabe follow us on. 1280x720 - Chic me | extra 10% off your first order! </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/dance-monkey-dj-benedict-remix/" rel="bookmark"> Dance Monkey Dj Benedict Remix / Dj benedict / mp3 320kbps / 7.28 мб / 03:11. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 320x180 - For your search query dj benedict dance monkey dj benedict remix mp3 we have found 1000000 songs matching your query but showing only top 10 now we recommend you to download first result dj benedict dance monkey remix mp3. Original Resolution: 320x180 Dj Monkay Free Mp3 Download Dj is your second name (twisterz &amp; waveshock remix). 1280x720 - Dance monkey dj steel alex remix extended edit. </div> </article><article class="list__item post"> <header class="list__header"> <h2 class="list__title post__title"> <a href="/post/ek-villain-tuerkce-dublaj-izle/" rel="bookmark"> Ek Villain Türkçe Dublaj Izle - Goa kentinde yaşayan guru (sidharth malhotra), prahlad adlı bir politikacının yanında çalışmaktadır. </a> </h2> </header> <div class="content list__excerpt post__content clearfix"> 182x268 - Ek villain 2014 türkçe dublaj 1080p ve altyazı seçenekleri ile keyifle donmadan seyredebilirsiniz iyi seyirler. Original Resolution: 182x268 The Villain 2014 Turkce Altyazili Orjinal Full Hd Izle The Villain Hd 720p Izle Jet Film Izle Ek villain filminin konusunda guru, goa kentinde yaşamakta ve hayatını prahlad ismindeki bir politikacının yanında çalışarak sürdürmektedir. 480x360 - Ek villain full hd kalitede, tafdi farkıyla türkçe altyazılı olarak hemen izle. </div> </article> </main> <div class="pagination"> <a class="pagination__item pagination__item--prev btn" href="/categories/uncategorized/page/142/">«</a> <span class="pagination__item pagination__item--current">143/308</span> <a class="pagination__item pagination__item--next btn" href="/categories/uncategorized/page/144/">»</a> </div> </div> <aside class="sidebar"><div class="widget-search widget"> <form class="widget-search__form" role="search" method="get" action="https://google.com/search"> <label> <input class="widget-search__field" type="search" placeholder="SEARCH…" value="" name="q" aria-label="SEARCH…"> </label> <input class="widget-search__submit" type="submit" value="Search"> <input type="hidden" name="sitesearch" value="https://puregoji.vercel.app/" /> </form> </div> <div class="widget-recent widget"> <h4 class="widget__title">Recent Posts</h4> <div class="widget__content"> <ul class="widget__list"> <li class="widget__item"><a class="widget__link" href="/post/abdulrahman-al-shoaibi/"><NAME> - The guy was fine after this and played the very next game.</a></li> <li class="widget__item"><a class="widget__link" href="/post/acordes-de-guitarra-disfruto-carla-morrison/"><NAME> - Carla morrison — disfruto (crack jack remix) 02:41.</a></li> <li class="widget__item"><a class="widget__link" href="/post/anmariya-kalippilanu-actress/">Anmariya Kalippilanu Actress - This kolukkumala is located in.</a></li> <li class="widget__item"><a class="widget__link" href="/post/cosculluela/">Cosculluela - Cosculluela presenta su nuevo sencillo decir adiós.</a></li> <li class="widget__item"><a class="widget__link" href="/post/mi-manchi-frasi-per-la-mamma-morta/">Mi Manchi Frasi Per La Mamma Morta - Salutami briciola e i nonni, e non dimenticare di venirmi a trovare più spesso nei sogni.</a></li> <li class="widget__item"><a class="widget__link" href="/post/ojala-te-hubiera-conocido-antes-meme-emo/">Ojala Te Hubiera Conocido Antes Meme Emo : Como antes de mis besos.</a></li> <li class="widget__item"><a class="widget__link" href="/post/album-or-cover-los-angeles-azules-ni-contigo/">&amp;quot;Album Or Cover Los Ángeles Azules Ni Contigo - Letra de ni contigo, ni sin ti.</a></li> <li class="widget__item"><a class="widget__link" href="/post/alka-yagnik-husband-and-daughter/">Alka Yagnik Husband And Daughter / The way of the house husband 643 weeks ago.</a></li> <li class="widget__item"><a class="widget__link" href="/post/anwar-malayalam-movie-songs-free-download/">Anwar Malayalam Movie Songs Free Download - Download the songs from here.</a></li> <li class="widget__item"><a class="widget__link" href="/post/canciones-infantiles-la-vaca-lola-letra/">Canciones Infantiles La Vaca Lola Letra : Viejas canciones infantiles está en la posición 384 del ranking de esta semana, su mejor puesto ha sido el 27º en septiembre de 2016.</a></li> </ul> </div> </div> </aside> </div> <footer class="footer"> <div class="container footer__container flex"> <div class="footer__copyright"> &copy; 2021 Pure Goji. <span class="footer__copyright-credits">Generated with <a href="https://gohugo.io/" rel="nofollow noopener" target="_blank">Hugo</a> and <a href="https://github.com/Vimux/Mainroad/" rel="nofollow noopener" target="_blank">Mainroad</a> theme.</span> </div> </div> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-21862896-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-21862896-2'); </script> </footer> </div> <script async defer src="/js/menu.js"></script> </body> </html>
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical JavaScript concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "bold"; const pathData = "M174 105v-9h134q21 0 44 3t42.5 12.5 32 26T439 181t-16 45-40 27q30 6 50 24t20 51q0 24-14 46-16 21-40 32-27 10-78 10H174v-9h12q24 0 28.5-14t4.5-34V153q0-31-7-38-9-10-26-10h-12zm89 135q5 1 9.5 1.5t9.5.5q5 1 11 1h13q36 0 50-7 17-8 26-23.5t9-33.5-7.5-30.5-20-21-28-12T304 112q-19 0-41 5v123zm0 21v131q24 7 52 7 41 0 64-19 21-20 21-48 0-20-10-36-12-22-38-29.5t-49-7.5q-7 0-13 .5t-11 .5-9 .5-7 .5z"; const ltr = false; const collection = "business-suite"; const packageName = "@ui5/webcomponents-icons-business-suite"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var bold = { pathData }; return bold; }); After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
javascript
2
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "bold"; const pathData = "M174 105v-9h134q21 0 44 3t42.5 12.5 32 26T439 181t-16 45-40 27q30 6 50 24t20 51q0 24-14 46-16 21-40 32-27 10-78 10H174v-9h12q24 0 28.5-14t4.5-34V153q0-31-7-38-9-10-26-10h-12zm89 135q5 1 9.5 1.5t9.5.5q5 1 11 1h13q36 0 50-7 17-8 26-23.5t9-33.5-7.5-30.5-20-21-28-12T304 112q-19 0-41 5v123zm0 21v131q24 7 52 7 41 0 64-19 21-20 21-48 0-20-10-36-12-22-38-29.5t-49-7.5q-7 0-13 .5t-11 .5-9 .5-7 .5z"; const ltr = false; const collection = "business-suite"; const packageName = "@ui5/webcomponents-icons-business-suite"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var bold = { pathData }; return bold; });
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php // // Refer to http://aa.usno.navy.mil/faq/docs/JD_Formula.php // Formula given above seems to be wrong. Refer to https://en.wikipedia.org/wiki/Julian_day function sign($x){ if($x>0) return 1; else return -1; } function truncate($x){ if($x>=0) return intval($x); else{ $x *= -1; return (-1)*intval($x); } } function UTCtoJD($year, $month, $day, $hour, $minute, $second){ $temp_a = intval((14-$month)/12); $temp_y = $year + 4800 - $temp_a; $temp_m = $month + 12*$temp_a - 3; return 365*$temp_y + intval(($temp_y/4)) - intval(($temp_y/100)) + intval(($temp_y/400)) + intval((153*$temp_m + 2)/5) + $day - 32045; } ?> After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
3
<?php // // Refer to http://aa.usno.navy.mil/faq/docs/JD_Formula.php // Formula given above seems to be wrong. Refer to https://en.wikipedia.org/wiki/Julian_day function sign($x){ if($x>0) return 1; else return -1; } function truncate($x){ if($x>=0) return intval($x); else{ $x *= -1; return (-1)*intval($x); } } function UTCtoJD($year, $month, $day, $hour, $minute, $second){ $temp_a = intval((14-$month)/12); $temp_y = $year + 4800 - $temp_a; $temp_m = $month + 12*$temp_a - 3; return 365*$temp_y + intval(($temp_y/4)) - intval(($temp_y/100)) + intval(($temp_y/400)) + intval((153*$temp_m + 2)/5) + $day - 32045; } ?>
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts. Add another point if the program addresses practical C# concepts, even if it lacks comments. Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments. Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section. Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterSheet { class Tiefling : Race { private decimal _intelligence; private decimal _charisma; public override decimal Intelligence { get { return _intelligence + 1; } set { _intelligence = value; } } public override decimal Charisma { get { return _charisma + 2; } set { _charisma = value; } } public Tiefling() { AdultSize = 0; AdditionalPerks.Add("Darkvision"); AdditionalPerks.Add("Infernal Legacy"); AdditionalPerks.Add("Hellish Resistance"); } } } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
csharp
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterSheet { class Tiefling : Race { private decimal _intelligence; private decimal _charisma; public override decimal Intelligence { get { return _intelligence + 1; } set { _intelligence = value; } } public override decimal Charisma { get { return _charisma + 2; } set { _charisma = value; } } public Tiefling() { AdultSize = 0; AdditionalPerks.Add("Darkvision"); AdditionalPerks.Add("Infernal Legacy"); AdditionalPerks.Add("Hellish Resistance"); } } }
Below is an extract from a PHP program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid PHP code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical PHP concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., object-oriented programming, namespaces). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching PHP. It should be similar to a school exercise, a tutorial, or a PHP course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching PHP. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: <?php /* * http://amandawei.com/tiens/maintenance/send_email_tiens_nz_distributor.php */ require_once 'class/MysqliDb.php'; //echo json_encode($_REQUEST); /* $action = trim($_REQUEST['action']); $id = trim($_REQUEST['customerid']); $output_array = array(); $table_array = array(); if ($action != "select_customer_info_with_id1") { $output_array['result'] = "NOK"; $output_array['info'] = "fail to get correct action code"; echo json_encode($output_array); die; } die;*/ $netcubehub_db = new MysqliDb ( "127.0.0.1","amam8224_amanda","xgp_950254", "amam8224_mouse" ); if ($netcubehub_db == NULL) { $output_array['result'] = "NOK"; $output_array['info'] = "Fail to connect Amanda database: " . $netcubehub_db->getLastError(); echo json_encode($output_array); die; } $tiens_distributor_table = "tiens_distributor_info"; try { $netcubehub_db -> where("state='NZ'"); $table_array = $netcubehub_db -> get($tiens_distributor_table); } catch (Exception $e) { $output_array['result'] = "NOK"; $output_array['info'] = $e->getMessage(); echo json_encode($output_array); die; } if ($table_array == NULL) { $output_array['result'] = "NOK"; $output_array['info'] = "no matched customer found"; echo json_encode($output_array); die; } /* */ foreach($table_array as $array) { //echo json_encode($array); $distributor_id = trim($array['distributor_id']); $full_name = trim($array['full_name']); $email = trim($array['email']); echo "$distributor_id: $full_name's email is $email <br>"; if (empty($email)) continue; $to = $email; //$to = "<EMAIL>"; // <EMAIL> <EMAIL> <EMAIL> $subject = "Last day: 2018 Tiens Anniversary Promotion - Buy 1 Get 1 Free"; $txt = " <html> <head> <title>Last day: 2018 Tiens Anniversary Promotion - Buy 1 Get 1 Free</title> </head> <body> <p> Dear $full_name, <br><br> Last day: until 26 August 2018, when you buy a product from Dietary Supple After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
php
2
<?php /* * http://amandawei.com/tiens/maintenance/send_email_tiens_nz_distributor.php */ require_once 'class/MysqliDb.php'; //echo json_encode($_REQUEST); /* $action = trim($_REQUEST['action']); $id = trim($_REQUEST['customerid']); $output_array = array(); $table_array = array(); if ($action != "select_customer_info_with_id1") { $output_array['result'] = "NOK"; $output_array['info'] = "fail to get correct action code"; echo json_encode($output_array); die; } die;*/ $netcubehub_db = new MysqliDb ( "127.0.0.1","amam8224_amanda","xgp_950254", "amam8224_mouse" ); if ($netcubehub_db == NULL) { $output_array['result'] = "NOK"; $output_array['info'] = "Fail to connect Amanda database: " . $netcubehub_db->getLastError(); echo json_encode($output_array); die; } $tiens_distributor_table = "tiens_distributor_info"; try { $netcubehub_db -> where("state='NZ'"); $table_array = $netcubehub_db -> get($tiens_distributor_table); } catch (Exception $e) { $output_array['result'] = "NOK"; $output_array['info'] = $e->getMessage(); echo json_encode($output_array); die; } if ($table_array == NULL) { $output_array['result'] = "NOK"; $output_array['info'] = "no matched customer found"; echo json_encode($output_array); die; } /* */ foreach($table_array as $array) { //echo json_encode($array); $distributor_id = trim($array['distributor_id']); $full_name = trim($array['full_name']); $email = trim($array['email']); echo "$distributor_id: $full_name's email is $email <br>"; if (empty($email)) continue; $to = $email; //$to = "<EMAIL>"; // <EMAIL> <EMAIL> <EMAIL> $subject = "Last day: 2018 Tiens Anniversary Promotion - Buy 1 Get 1 Free"; $txt = " <html> <head> <title>Last day: 2018 Tiens Anniversary Promotion - Buy 1 Get 1 Free</title> </head> <body> <p> Dear $full_name, <br><br> Last day: until 26 August 2018, when you buy a product from Dietary Supplements, Wellness Equipment or Skin Care, you'll get a second same product Free (1+1). <br> Offer available till stocks last. <br><br> 最后1天! 2018天狮澳洲&新西兰分公司壹周年庆祝优惠:只要购买任何保健食品、美容护肤品或保健器械一件,您将获得第二件免费同类产品一件(1 + 1),多买多送,优惠至2018年8月26日。 <br><br><br> Yours sincerely,<br> <b>Tiens Bio Tech New Zealand Pty Ltd.</b><br> Level 9, 45 Queen Street East, Auckland 1010, New Zealand<br> Tel: +61 3 8601 1186<br> Email: <EMAIL><br> Web: http://web.nz.tiens.com<br> NZBN: 9429043352517<br> </p> </body> </html> "; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= "From: <EMAIL>"; mail($to,$subject,$txt,$headers); //break; } mysqli_close($netcubehub_db); die; ?>
Below is an extract from a C++ program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the program contains valid C++ code, even if it's not educational, like boilerplate code, configurations, or niche concepts. - Add another point if the program addresses practical C++ concepts, even if it lacks comments. - Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., memory management). The code should be well-structured and contain some comments. - Give a fourth point if the program is self-contained and highly relevant to teaching C++. It should be similar to a school exercise, a tutorial, or a C++ course section. - Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C++. It should be well-written, easy to understand, and contain step-by-step explanations and comments. The extract: //============================================================================ // Name : Problem025.cpp // Author : <NAME> // Description : first 1000-digit Fibonacci number //============================================================================ #include <iostream> #include "bigint/BigIntegerLibrary.hh" int fib(BigInteger a, BigInteger b, BigInteger max, int term); int main(int argc, char* argv[]) { BigInteger goal = 10; for (int i=2; i<1000; i++) { goal *= 10; } std::cout << fib(1, 1, goal, 1) << std::endl; return 0; } int fib(BigInteger a, BigInteger b, BigInteger max, int term) { return (a > max) ? term : fib(b, a + b, max, term + 1); } After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
cpp
3
//============================================================================ // Name : Problem025.cpp // Author : <NAME> // Description : first 1000-digit Fibonacci number //============================================================================ #include <iostream> #include "bigint/BigIntegerLibrary.hh" int fib(BigInteger a, BigInteger b, BigInteger max, int term); int main(int argc, char* argv[]) { BigInteger goal = 10; for (int i=2; i<1000; i++) { goal *= 10; } std::cout << fib(1, 1, goal, 1) << std::endl; return 0; } int fib(BigInteger a, BigInteger b, BigInteger max, int term) { return (a > max) ? term : fib(b, a + b, max, term + 1); }
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion: - Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations. - Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments. - Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments. - Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design. - Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code. The extract: USE Geography SELECT PeakName FROM Peaks ORDER BY PeakName After examining the extract: - Briefly justify your total score, up to 100 words. - Conclude with the score using the format: "Educational score: <total points>"
sql
1
USE Geography SELECT PeakName FROM Peaks ORDER BY PeakName