prompt
stringlengths 1.3k
3.64k
| language
stringclasses 16
values | label
int64 -1
5
| text
stringlengths 14
130k
|
---|---|---|---|
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:
// source: https://leetcode.com/problems/compare-version-numbers/
/**
*
* Compare two version numbers version1 and version2.
* If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
*
* You may assume that the version strings are non-empty and contain only digits and the . character.
* The . character does not represent a decimal point and is used to separate number sequences.
* For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
*
* Here is an example of version numbers ordering:
*
* 0.1 < 1.1 < 1.2 < 13.37
* Credits:
* Special thanks to @ts for adding this problem and creating all test cases.
*
**/
#include <iostream>
using namespace std;
class Solution {
public:
int compareVersion(string version1, string version2) {
int pos1 = 0, pos2 = 0;
int length1 = version1.length();
int length2 = version2.length();
while(pos1 < length1 && pos2 < length2)
{
int point_pos1 = version1.find_first_of('.', pos1);
int point_pos2 = version2.find_first_of('.', pos2);
string ver1 = point_pos1 >= 0 ? version1.substr(pos1, point_pos1 - pos1) : version1.substr(pos1, length1 - pos1);
string ver2 = point_pos2 >= 0 ? version2.substr(pos2, point_pos2 - pos2) : version2.substr(pos2, length2 - pos2);
pos1 = point_pos1 >= 0 ? point_pos1 + 1 : length1;
pos2 = point_pos2 >= 0 ? point_pos2 + 1 : length2;
int num1 = convertStringToInt(ver1);
int num2 = convertStringToInt(ver2);
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
while(pos1 < length1)
{
int point_pos1 = version1.find_first_of('.', pos1);
string ver1 = point_pos1 >= 0 ? version1.substr(pos1, point_pos1 - pos1) : version1.substr(pos1, length1 - pos1);
if (convertStringToInt(ver1) > 0) return 1;
pos1 = point_pos1 >= 0 ? point_pos1 + 1 : length1;
}
while (pos2 < length2)
{
int point_pos2 = version2.find_first_of('
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 | // source: https://leetcode.com/problems/compare-version-numbers/
/**
*
* Compare two version numbers version1 and version2.
* If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
*
* You may assume that the version strings are non-empty and contain only digits and the . character.
* The . character does not represent a decimal point and is used to separate number sequences.
* For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
*
* Here is an example of version numbers ordering:
*
* 0.1 < 1.1 < 1.2 < 13.37
* Credits:
* Special thanks to @ts for adding this problem and creating all test cases.
*
**/
#include <iostream>
using namespace std;
class Solution {
public:
int compareVersion(string version1, string version2) {
int pos1 = 0, pos2 = 0;
int length1 = version1.length();
int length2 = version2.length();
while(pos1 < length1 && pos2 < length2)
{
int point_pos1 = version1.find_first_of('.', pos1);
int point_pos2 = version2.find_first_of('.', pos2);
string ver1 = point_pos1 >= 0 ? version1.substr(pos1, point_pos1 - pos1) : version1.substr(pos1, length1 - pos1);
string ver2 = point_pos2 >= 0 ? version2.substr(pos2, point_pos2 - pos2) : version2.substr(pos2, length2 - pos2);
pos1 = point_pos1 >= 0 ? point_pos1 + 1 : length1;
pos2 = point_pos2 >= 0 ? point_pos2 + 1 : length2;
int num1 = convertStringToInt(ver1);
int num2 = convertStringToInt(ver2);
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
while(pos1 < length1)
{
int point_pos1 = version1.find_first_of('.', pos1);
string ver1 = point_pos1 >= 0 ? version1.substr(pos1, point_pos1 - pos1) : version1.substr(pos1, length1 - pos1);
if (convertStringToInt(ver1) > 0) return 1;
pos1 = point_pos1 >= 0 ? point_pos1 + 1 : length1;
}
while (pos2 < length2)
{
int point_pos2 = version2.find_first_of('.', pos2);
string ver2 = point_pos2 >= 0 ? version2.substr(pos2, point_pos2 - pos2) : version2.substr(pos2, length2 - pos2);
if (convertStringToInt(ver2) > 0) return -1;
pos2 = point_pos2 >= 0 ? point_pos2 + 1 : length2;
}
return 0;
}
int convertStringToInt(string s)
{
if (s.length() == 0) return 0;
int num = 0;
for (int i = 0; i < s.length(); i++)
{
num = num * 10 + (s[i] - '0');
}
return num;
}
};
int main()
{
Solution* so = new Solution();
string versions1[] = {"2", "2.34", "2.3.13", "2.3", "1.0", "1.0.3"};
string versions2[] = {"10", "13.0", "2.3", "2.3", "1", "1"};
for (int i = 0; i < 6; i++)
cout << "input: version1 = " << versions1[i] << ", version2 = " << versions2[i] << "; output: " << so->compareVersion(versions1[i], versions2[i]) << endl;
}
|
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 <types.h>
#include <spinlock.h>
#include <thread.h>
#include <current.h>
#include <proc.h>
#include <synch.h>
#include <pid.h>
#define MAX_NO_PID 256
static struct pid *pids[MAX_NO_PID];
static struct lock *pid_lock;
static uint16_t available = 2;
struct pid *pid_create(pid_t p_pid, int index)
{
KASSERT(!(index < 1 || index >= MAX_NO_PID));
struct pid *temp = kmalloc(sizeof(struct pid));
KASSERT(temp != NULL);
temp->pid = index;
temp->p_pid = p_pid;
return temp;
}
void pid_bootstrap()
{
pid_lock = lock_create("pid_lock");
if (pid_lock == NULL)
{
panic("pid lock not created\n");
}
/* No need to call the lock. It's bootstrap process so no process will be interfering anyway */
for (uint16_t i = 0; i < MAX_NO_PID; i++)
{
pids[i] = NULL;
}
pids[BOOTPROC_ID] = pid_create(INVALID_ID, BOOTPROC_ID);
}
int pid_alloc(pid_t p_pid)
{
lock_acquire(pid_lock);
if( pids[available] == NULL){
pids[available] = pid_create(p_pid,available);
lock_release(pid_lock);
return available++;
}
uint16_t i;
for (i = 2; i < MAX_NO_PID; i++)
{
if (pids[i] == NULL)
{
pids[i] = pid_create(p_pid, i);
available = i + 1;
lock_release(pid_lock);
return i;
}
}
//Shouldn't reach here.
lock_release(pid_lock);
return INVALID_ID;
}
void pid_dealloc(pid_t pid)
{
lock_acquire(pid_lock);
if (pid < 0 || pid >= MAX_NO_PID)
panic("Invalid range of pid\n");
KASSERT(pid != INVALID_ID);
struct pid *temp = pids[pid];
kfree(temp);
pids[pid] = NULL;
lock_release(pid_lock);
}
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 <types.h>
#include <spinlock.h>
#include <thread.h>
#include <current.h>
#include <proc.h>
#include <synch.h>
#include <pid.h>
#define MAX_NO_PID 256
static struct pid *pids[MAX_NO_PID];
static struct lock *pid_lock;
static uint16_t available = 2;
struct pid *pid_create(pid_t p_pid, int index)
{
KASSERT(!(index < 1 || index >= MAX_NO_PID));
struct pid *temp = kmalloc(sizeof(struct pid));
KASSERT(temp != NULL);
temp->pid = index;
temp->p_pid = p_pid;
return temp;
}
void pid_bootstrap()
{
pid_lock = lock_create("pid_lock");
if (pid_lock == NULL)
{
panic("pid lock not created\n");
}
/* No need to call the lock. It's bootstrap process so no process will be interfering anyway */
for (uint16_t i = 0; i < MAX_NO_PID; i++)
{
pids[i] = NULL;
}
pids[BOOTPROC_ID] = pid_create(INVALID_ID, BOOTPROC_ID);
}
int pid_alloc(pid_t p_pid)
{
lock_acquire(pid_lock);
if( pids[available] == NULL){
pids[available] = pid_create(p_pid,available);
lock_release(pid_lock);
return available++;
}
uint16_t i;
for (i = 2; i < MAX_NO_PID; i++)
{
if (pids[i] == NULL)
{
pids[i] = pid_create(p_pid, i);
available = i + 1;
lock_release(pid_lock);
return i;
}
}
//Shouldn't reach here.
lock_release(pid_lock);
return INVALID_ID;
}
void pid_dealloc(pid_t pid)
{
lock_acquire(pid_lock);
if (pid < 0 || pid >= MAX_NO_PID)
panic("Invalid range of pid\n");
KASSERT(pid != INVALID_ID);
struct pid *temp = pids[pid];
kfree(temp);
pids[pid] = NULL;
lock_release(pid_lock);
}
|
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.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace ApiDapperCrud.Connection
{
public class SqlDbConnection : ISqlDbConnection
{
private string connectionString;
public SqlDbConnection()
{
connectionString = @"Data Source=apidappercrud.cyveqhehh7ab.sa-east-1.rds.amazonaws.com,1433;Initial Catalog=ApiDapperCrud;User ID=apiDapperCrudDev;Password=***********;Connect Timeout=30;Encrypt=False;";
}
public IDbConnection Connection
{
get
{
return new SqlConnection(connectionString);
}
}
}
}
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.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace ApiDapperCrud.Connection
{
public class SqlDbConnection : ISqlDbConnection
{
private string connectionString;
public SqlDbConnection()
{
connectionString = @"Data Source=apidappercrud.cyveqhehh7ab.sa-east-1.rds.amazonaws.com,1433;Initial Catalog=ApiDapperCrud;User ID=apiDapperCrudDev;Password=***********;Connect Timeout=30;Encrypt=False;";
}
public IDbConnection Connection
{
get
{
return new SqlConnection(connectionString);
}
}
}
}
|
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:
//
// ViewControllerStateble.swift
// Utility
//
// Created by jean.vinge on 14/06/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxSwift
import RxCocoa
public protocol Stateable {
var onEnterForeground: Driver<Notification> { get set }
var onEnterBackground: Driver<Notification> { get set }
var viewDidLoad: Driver<Void> { get set }
var viewDidAppear: Driver<Void> { get set }
var viewWillAppear: Driver<Void> { get set }
var viewWillDisappear: Driver<Void> { get set }
}
struct StateableViewController: Stateable {
var onEnterForeground: Driver<Notification>
var onEnterBackground: Driver<Notification>
var viewDidLoad: Driver<Void>
var viewDidAppear: Driver<Void>
var viewWillAppear: Driver<Void>
var viewWillDisappear: Driver<Void>
init(_ viewController: UIViewController) {
self.onEnterForeground = viewController.rx.onEnterForeground
self.onEnterBackground = viewController.rx.onEnterBackground
self.viewDidLoad = viewController.rx.viewDidLoad
self.viewDidAppear = viewController.rx.viewDidAppear
self.viewWillAppear = viewController.rx.viewWillAppear
self.viewWillDisappear = viewController.rx.viewWillDisappear
}
}
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 | //
// ViewControllerStateble.swift
// Utility
//
// Created by jean.vinge on 14/06/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import RxSwift
import RxCocoa
public protocol Stateable {
var onEnterForeground: Driver<Notification> { get set }
var onEnterBackground: Driver<Notification> { get set }
var viewDidLoad: Driver<Void> { get set }
var viewDidAppear: Driver<Void> { get set }
var viewWillAppear: Driver<Void> { get set }
var viewWillDisappear: Driver<Void> { get set }
}
struct StateableViewController: Stateable {
var onEnterForeground: Driver<Notification>
var onEnterBackground: Driver<Notification>
var viewDidLoad: Driver<Void>
var viewDidAppear: Driver<Void>
var viewWillAppear: Driver<Void>
var viewWillDisappear: Driver<Void>
init(_ viewController: UIViewController) {
self.onEnterForeground = viewController.rx.onEnterForeground
self.onEnterBackground = viewController.rx.onEnterBackground
self.viewDidLoad = viewController.rx.viewDidLoad
self.viewDidAppear = viewController.rx.viewDidAppear
self.viewWillAppear = viewController.rx.viewWillAppear
self.viewWillDisappear = viewController.rx.viewWillDisappear
}
}
|
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 mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const TutorialSchema = mongoose.Schema({
title: {type:String,required:true},
content: {type: String,required:true}
});
TutorialSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Tutorial", TutorialSchema);
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 mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const TutorialSchema = mongoose.Schema({
title: {type:String,required:true},
content: {type: String,required:true}
});
TutorialSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Tutorial", TutorialSchema);
|
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 "google_drive"
require "./confluence"
def build_create_table(ws, table_name)
format = <<-EOS
create table %{table} (
%{rows}
minute int,
second int
)
partitioned by (year int, month int, day int, hour int)
stored as parquet
;
EOS
row_format = " %{name} %{type} comment \"%{comment}\","
rows = (2..ws.num_rows).map { |r|
row_format % {
name: ws[r,1].ljust(31),
type: ws[r,2].ljust(20),
comment: ws[r,3],
}
}.join("\n")
return format % {table: table_name, rows: rows}
end
def build_insert(ws, table_name, raw_table_name)
format = <<-EOS
insert into %{table}
partition (year = ${hiveconf:year}, month = ${hiveconf:month}, day = ${hiveconf:day}, hour = ${hiveconf:hour})
select
%{selects}
from_unixtime(nginx_time_stamp, "m"), from_unixtime(nginx_time_stamp, "s")
from %{raw_table}
lateral view json_tuple(json_data,
%{columns_dq}
) data as
%{columns}
;
EOS
columns_list = (2..ws.num_rows).map{|r|ws[r,3]}
return format % {
selects: (2..ws.num_rows).map{|r|ws[r,4] + ","}.join,
columns: columns_list.join(","),
columns_dq: columns_list.map{|c|"\"%s\"" % c}.join(","),
table: table_name,
raw_table: raw_table_name,
}
end
def build_table_name(log_name)
return log_name + '_logs'
end
def build_raw_table_name(log_name)
product_name, log_type = log_name.split("_")
return product_name + '_raw_' + log_type + '_logs'
end
def update_page(confluence, page_id, content)
confluence.execute(a: 'storePage', id: page_id, content: "'#{content}'")
end
def fetch_metadata_list(spreadsheet)
ws = spreadsheet.worksheet_by_title('confluence')
(2..ws.num_rows).map { |r|
{
log_name: ws[r,1],
sql_type: ws[r,2],
page_id: ws[r,3],
}
}
end
def update_page_by_metadata(confluence, spreadsheet, metadata)
ws = spreadsheet.worksheet_by_title(metadata[:log_name])
sql = case metadata[:sql_type]
when 'create_table' then
build_create_table(ws, build_table_nam
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 | require "google_drive"
require "./confluence"
def build_create_table(ws, table_name)
format = <<-EOS
create table %{table} (
%{rows}
minute int,
second int
)
partitioned by (year int, month int, day int, hour int)
stored as parquet
;
EOS
row_format = " %{name} %{type} comment \"%{comment}\","
rows = (2..ws.num_rows).map { |r|
row_format % {
name: ws[r,1].ljust(31),
type: ws[r,2].ljust(20),
comment: ws[r,3],
}
}.join("\n")
return format % {table: table_name, rows: rows}
end
def build_insert(ws, table_name, raw_table_name)
format = <<-EOS
insert into %{table}
partition (year = ${hiveconf:year}, month = ${hiveconf:month}, day = ${hiveconf:day}, hour = ${hiveconf:hour})
select
%{selects}
from_unixtime(nginx_time_stamp, "m"), from_unixtime(nginx_time_stamp, "s")
from %{raw_table}
lateral view json_tuple(json_data,
%{columns_dq}
) data as
%{columns}
;
EOS
columns_list = (2..ws.num_rows).map{|r|ws[r,3]}
return format % {
selects: (2..ws.num_rows).map{|r|ws[r,4] + ","}.join,
columns: columns_list.join(","),
columns_dq: columns_list.map{|c|"\"%s\"" % c}.join(","),
table: table_name,
raw_table: raw_table_name,
}
end
def build_table_name(log_name)
return log_name + '_logs'
end
def build_raw_table_name(log_name)
product_name, log_type = log_name.split("_")
return product_name + '_raw_' + log_type + '_logs'
end
def update_page(confluence, page_id, content)
confluence.execute(a: 'storePage', id: page_id, content: "'#{content}'")
end
def fetch_metadata_list(spreadsheet)
ws = spreadsheet.worksheet_by_title('confluence')
(2..ws.num_rows).map { |r|
{
log_name: ws[r,1],
sql_type: ws[r,2],
page_id: ws[r,3],
}
}
end
def update_page_by_metadata(confluence, spreadsheet, metadata)
ws = spreadsheet.worksheet_by_title(metadata[:log_name])
sql = case metadata[:sql_type]
when 'create_table' then
build_create_table(ws, build_table_name(metadata[:log_name]))
when 'insert' then
build_insert(ws, build_table_name(metadata[:log_name]), build_raw_table_name(metadata[:log_name]))
end
content = '{excerpt}{code:language=sql|theme=Django}%s{code}{excerpt}' % sql
update_page(confluence, metadata[:page_id], content)
end
session = GoogleDrive::Session.from_config("google_drive_config.json")
spreadsheet = session.file_by_id('1FVu3LahWtaW2nFoyn61ooJY8bqpb60SFXOnJDjwCwOI')
confluence = Confluence.new
metadata_list = []
if ARGV.size == 0 then
metadata_list = fetch_metadata_list(spreadsheet)
else
metadata_list = fetch_metadata_list(spreadsheet).select{|m|ARGV.include?(m[:log_name])}
end
metadata_list.each{|m|update_page_by_metadata(confluence, spreadsheet, m)}
|
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
/**
* @author <NAME> <<EMAIL>>
* @copyright City of Edinburgh Council & <NAME>
* @license Open Source under the 3-clause BSD License
* @url https://github.com/City-Outdoors/City-Outdoors-Web
*/
class FeatureCheckinQuestionHigherOrLower extends BaseFeatureCheckinQuestion {
public function __construct($data) {
parent::__construct($data);
}
/** @return FeatureCheckinQuestionHigherOrLower **/
public static function create(Feature $feature, $question, $answers) {
$db = getDB();
$stat = $db->prepare('INSERT INTO feature_checkin_question (feature_id, question, answers, created_at, question_type) '.
'VALUES (:feature_id, :question, :answers, :created_at, :type)');
$data = array(
'feature_id'=>$feature->getId(),
'question'=>$question,
'answers'=>$answers,
'created_at'=>date('Y-m-d H:i:s'),
'type'=>'HIGHERORLOWER',
);
$stat->execute($data);
$data['id'] = $db->lastInsertId();
return new FeatureCheckinQuestionHigherOrLower($data);
}
/** Takes string admin user has put in as the real answer, attemps to parse it to a sensible structure and return the results or NULL on failure **/
public function parseRealAnswer() {
if (strpos($this->answers, "-") > 0) {
list($min,$max) = explode("-", $this->answers);
if (is_numeric(trim($min)) && is_numeric(trim($max))) {
$min = floatval(trim($min));
$max = floatval(trim($max));
if ($max > $min) {
return array($min,$max);
}
}
} else {
// If it's one value only, must be an int.
// (If a float lots of problems with how many decimal places do you check to? bit unfair on player.)
// Hence we use ctype_digit, ctype_digit does not accept "." characters.
if (ctype_digit(trim($this->answers))) {
return intval(trim($this->answers));
}
}
return null;
}
/** Takes answer from user.
*
* @param type $answer
* @return int|null 0 if correct, -1 if answer is to low, 1 if answer is to high. null if error.
*/
public funct
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
/**
* @author <NAME> <<EMAIL>>
* @copyright City of Edinburgh Council & <NAME>
* @license Open Source under the 3-clause BSD License
* @url https://github.com/City-Outdoors/City-Outdoors-Web
*/
class FeatureCheckinQuestionHigherOrLower extends BaseFeatureCheckinQuestion {
public function __construct($data) {
parent::__construct($data);
}
/** @return FeatureCheckinQuestionHigherOrLower **/
public static function create(Feature $feature, $question, $answers) {
$db = getDB();
$stat = $db->prepare('INSERT INTO feature_checkin_question (feature_id, question, answers, created_at, question_type) '.
'VALUES (:feature_id, :question, :answers, :created_at, :type)');
$data = array(
'feature_id'=>$feature->getId(),
'question'=>$question,
'answers'=>$answers,
'created_at'=>date('Y-m-d H:i:s'),
'type'=>'HIGHERORLOWER',
);
$stat->execute($data);
$data['id'] = $db->lastInsertId();
return new FeatureCheckinQuestionHigherOrLower($data);
}
/** Takes string admin user has put in as the real answer, attemps to parse it to a sensible structure and return the results or NULL on failure **/
public function parseRealAnswer() {
if (strpos($this->answers, "-") > 0) {
list($min,$max) = explode("-", $this->answers);
if (is_numeric(trim($min)) && is_numeric(trim($max))) {
$min = floatval(trim($min));
$max = floatval(trim($max));
if ($max > $min) {
return array($min,$max);
}
}
} else {
// If it's one value only, must be an int.
// (If a float lots of problems with how many decimal places do you check to? bit unfair on player.)
// Hence we use ctype_digit, ctype_digit does not accept "." characters.
if (ctype_digit(trim($this->answers))) {
return intval(trim($this->answers));
}
}
return null;
}
/** Takes answer from user.
*
* @param type $answer
* @return int|null 0 if correct, -1 if answer is to low, 1 if answer is to high. null if error.
*/
public function checkAnswer($answer) {
if (!is_numeric($answer)) return null;
$realAnswer = $this->parseRealAnswer();
if (is_array($realAnswer)) {
list($min,$max) = $realAnswer;
$answer = floatval(trim($answer));
if (($answer >= $min) && ($answer <= $max)) {
return 0;
} else if ($answer < $min) {
return -1;
} else if ($answer > $max) {
return 1;
}
} else if (is_int($realAnswer)) {
$answer = intval(trim($answer));
if ($answer == $realAnswer) {
return 0;
} else if ($answer < $realAnswer) {
return -1;
} else if ($answer > $realAnswer) {
return 1;
}
} else {
return null;
}
}
public function checkAndSaveAnswer($attemptAnswer, User $useraccount, $userAgent = null, $ip=null) {
$db = getDB();
$answer = $this->checkAnswer($attemptAnswer);
if (is_null($answer)) {
return null;
} else if ($answer == 1 || $answer == -1) {
$stat = $db->prepare('INSERT INTO feature_checkin_failure (user_account_id, feature_checkin_question_id, answer_given, created_at, user_agent, ip) '.
'VALUES (:user_account_id, :feature_checkin_question_id, :answer_given, :created_at, :user_agent, :ip)');
$data = array(
'user_account_id'=>$useraccount->getId(),
'feature_checkin_question_id'=>$this->getId(),
'answer_given'=>$attemptAnswer,
'created_at'=>date('Y-m-d H:i:s'),
'user_agent'=>$userAgent,
'ip'=>$ip
);
$stat->execute($data);
return $answer;
} else if ($answer == 0) {
// how many wrong goes did they take?
$attempt = 1;
$stat = $db->prepare('SELECT id FROM feature_checkin_failure WHERE feature_checkin_question_id=:fciqid AND user_account_id=:uaid');
$stat->execute(array(
'fciqid'=>$this->getId(),
'uaid'=>$useraccount->getId()
));
while($d = $stat->fetch()) $attempt++;
// now insert the correct answer with the score based on how any goes it took
$stat = $db->prepare('INSERT INTO feature_checkin_success (user_account_id, feature_checkin_question_id, answer_given, score, created_at, user_agent, ip) '.
'VALUES (:user_account_id, :feature_checkin_question_id, :answer_given, :score, :created_at, :user_agent, :ip)');
$data = array(
'user_account_id'=>$useraccount->getId(),
'feature_checkin_question_id'=>$this->getId(),
'answer_given'=>$attemptAnswer,
'created_at'=>date('Y-m-d H:i:s'),
'user_agent'=>$userAgent,
'ip'=>$ip,
'score'=>$this->getScoreOnAttempt($attempt),
);
$stat->execute($data);
$useraccount->calculateAndCacheScore();
return 0;
}
}
public function getScoreOnAttempt($attempt) {
$scores = $this->getScores();
if (count($scores) > $attempt - 1) {
return $scores[$attempt - 1];
}
return 0;
}
public function getScores() { return $this->score ? $this->score->scores : 0; }
public function setScoresFromString($score = "10,5") {
$scores = array();
foreach(explode(",",$score) as $i) {
if (intval($i)) { // I suspose someone may want negative scores.
$scores[] = intval($i);
}
}
$this->setScores($scores);
}
public function setScores($score = array(10,5)) {
$scoreJSONObject = array('scores'=>$score);
$scoreJSONText = json_encode($scoreJSONObject);
$this->score = json_decode($scoreJSONText);
$db = getDB();
$stat = $db->prepare("UPDATE feature_checkin_question SET score=:s WHERE id=:id");
$stat->execute(array('s'=>$scoreJSONText,'id'=>$this->id));
}
}
|
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:
<h1><?=$category['Category']['name'] ?></h1>
<table class="product_listing">
<?
foreach ( $products as $product ){
?>
<tr>
<td class="image">
<?php
if ( !empty($product['Product']['Image']) ){
?>
<a href="/users/products/view/<?=$product['Product']['id']?>">
<img src="/product-images/small/<?php echo $product['Product']['Image'][0]['name']?>" />
</a>
<?php
} else {
echo ' ';
}
?>
</td>
<th valign="top">
<a href="/users/products/view/<?=$product['Product']['id']?>"><?=$product['Product']['name']?></a>
<br />
<a class="cart_button" href="/users/products/view/<?=$product['Product']['id']?>">objednat</a>
</th>
<td><p><?=$product['Product']['description']?></p></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<?
}
?>
</table>
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 | <h1><?=$category['Category']['name'] ?></h1>
<table class="product_listing">
<?
foreach ( $products as $product ){
?>
<tr>
<td class="image">
<?php
if ( !empty($product['Product']['Image']) ){
?>
<a href="/users/products/view/<?=$product['Product']['id']?>">
<img src="/product-images/small/<?php echo $product['Product']['Image'][0]['name']?>" />
</a>
<?php
} else {
echo ' ';
}
?>
</td>
<th valign="top">
<a href="/users/products/view/<?=$product['Product']['id']?>"><?=$product['Product']['name']?></a>
<br />
<a class="cart_button" href="/users/products/view/<?=$product['Product']['id']?>">objednat</a>
</th>
<td><p><?=$product['Product']['description']?></p></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<?
}
?>
</table> |
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.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Escuela_Api.Models
{
public class Materia
{
public int idmateria { get; set; }
public string nombre { get; set; }
public int idprofesor { get; set; }
public Profesor profesor { get; set; }
//public List<Calificacion> Calificaciones { get; set; }
public class Map {
public Map(EntityTypeBuilder<Materia> ebMateria)
{
ebMateria.HasKey(x => x.idmateria);
ebMateria.Property(x => x.nombre).HasColumnName("nombre").HasMaxLength(20);
ebMateria.Property(x => x.idprofesor).HasColumnName("idprofesor").HasColumnType("int");
ebMateria.HasOne(x => x.profesor);
}
}
}
}
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.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Escuela_Api.Models
{
public class Materia
{
public int idmateria { get; set; }
public string nombre { get; set; }
public int idprofesor { get; set; }
public Profesor profesor { get; set; }
//public List<Calificacion> Calificaciones { get; set; }
public class Map {
public Map(EntityTypeBuilder<Materia> ebMateria)
{
ebMateria.HasKey(x => x.idmateria);
ebMateria.Property(x => x.nombre).HasColumnName("nombre").HasMaxLength(20);
ebMateria.Property(x => x.idprofesor).HasColumnName("idprofesor").HasColumnType("int");
ebMateria.HasOne(x => x.profesor);
}
}
}
}
|
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 EmployeesController < ApplicationController
def index
@names = Employee.all
end
def show
@id=params['id'].to_i
data=Employee.all
@details = data.select{|a| a[:id].to_i==@id}
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 EmployeesController < ApplicationController
def index
@names = Employee.all
end
def show
@id=params['id'].to_i
data=Employee.all
@details = data.select{|a| a[:id].to_i==@id}
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:
//
// PolynomialFunction.swift
// Math
//
// Created by <NAME> on 31.07.16.
// Copyright © 2016 pauljohanneskraft. All rights reserved.
//
import Foundation
public struct PolynomialFunction: Function {
// stored properties
public var polynomial: Polynomial<Double>
// initializers
public init(_ poly: Polynomial<Double>) {
self.polynomial = poly
}
// computed properties
public var derivative: Function {
return PolynomialFunction(polynomial.derivative).reduced
}
public var integral: Function {
return PolynomialFunction(polynomial.integral).reduced
}
public var reduced: Function {
return degree == 0 ? Constant(polynomial[0]) : self
}
public var description: String {
return degree == 0 ? polynomial[0].reducedDescription : "(\(polynomial.reducedDescription))"
}
public var degree: Int {
return polynomial.degree
}
// functions
public func equals(to: Function) -> Bool {
guard let other = to as? PolynomialFunction else { return false }
return other.polynomial == polynomial
}
public func call(x: Double) -> Double {
return polynomial.call(x: x) ?? .nan
}
}
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 | //
// PolynomialFunction.swift
// Math
//
// Created by <NAME> on 31.07.16.
// Copyright © 2016 pauljohanneskraft. All rights reserved.
//
import Foundation
public struct PolynomialFunction: Function {
// stored properties
public var polynomial: Polynomial<Double>
// initializers
public init(_ poly: Polynomial<Double>) {
self.polynomial = poly
}
// computed properties
public var derivative: Function {
return PolynomialFunction(polynomial.derivative).reduced
}
public var integral: Function {
return PolynomialFunction(polynomial.integral).reduced
}
public var reduced: Function {
return degree == 0 ? Constant(polynomial[0]) : self
}
public var description: String {
return degree == 0 ? polynomial[0].reducedDescription : "(\(polynomial.reducedDescription))"
}
public var degree: Int {
return polynomial.degree
}
// functions
public func equals(to: Function) -> Bool {
guard let other = to as? PolynomialFunction else { return false }
return other.polynomial == polynomial
}
public func call(x: Double) -> Double {
return polynomial.call(x: x) ?? .nan
}
}
|
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:
git pull <EMAIL>:/spetum/SystemManagementScript.git
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 | git pull <EMAIL>:/spetum/SystemManagementScript.git
|
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 * as LRU from 'lru-cache';
import { Account } from 'klendathu-json-types';
import { ObservableAccount } from './ObservableAccount';
import { session } from '../models';
export class AccountStore {
private cacheById: LRU.Cache<string, ObservableAccount>;
private cacheByName: LRU.Cache<string, Account>;
constructor() {
this.cacheById = LRU({ max: 100, dispose: this.onDispose });
this.cacheByName = LRU({ max: 100 });
}
/** Look up an account by it's database id. Returns an observable object which changes in
response to database mutations. */
public byId(uid: string): ObservableAccount {
let account = this.cacheById.get(uid);
if (account) {
account.acquire();
return account;
}
const record = session.connection.record.getRecord(`accounts/${uid}`);
account = new ObservableAccount(record);
account.acquire();
this.cacheById.set(uid, account);
return account;
}
/** Look up an account by it's public name. Returns a raw JSON object. This is a
low-overhead method which does a single deepstream RPC call. */
public byName(uname: string): Promise<Account> {
return new Promise((resolve, reject) => {
const account = this.cacheByName.get(uname);
if (account) {
resolve(account);
return;
}
session.connection.rpc.make('accounts.get', { uname }, (error, resp) => {
if (error) {
reject(new Error(error));
} else {
this.cacheByName.set(uname, resp);
resolve(resp);
}
});
});
}
private onDispose(id: string, account: ObservableAccount) {
account.release();
}
}
export const accounts = new AccountStore();
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 * as LRU from 'lru-cache';
import { Account } from 'klendathu-json-types';
import { ObservableAccount } from './ObservableAccount';
import { session } from '../models';
export class AccountStore {
private cacheById: LRU.Cache<string, ObservableAccount>;
private cacheByName: LRU.Cache<string, Account>;
constructor() {
this.cacheById = LRU({ max: 100, dispose: this.onDispose });
this.cacheByName = LRU({ max: 100 });
}
/** Look up an account by it's database id. Returns an observable object which changes in
response to database mutations. */
public byId(uid: string): ObservableAccount {
let account = this.cacheById.get(uid);
if (account) {
account.acquire();
return account;
}
const record = session.connection.record.getRecord(`accounts/${uid}`);
account = new ObservableAccount(record);
account.acquire();
this.cacheById.set(uid, account);
return account;
}
/** Look up an account by it's public name. Returns a raw JSON object. This is a
low-overhead method which does a single deepstream RPC call. */
public byName(uname: string): Promise<Account> {
return new Promise((resolve, reject) => {
const account = this.cacheByName.get(uname);
if (account) {
resolve(account);
return;
}
session.connection.rpc.make('accounts.get', { uname }, (error, resp) => {
if (error) {
reject(new Error(error));
} else {
this.cacheByName.set(uname, resp);
resolve(resp);
}
});
});
}
private onDispose(id: string, account: ObservableAccount) {
account.release();
}
}
export const accounts = new AccountStore();
|
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:
//
// oscServer.cpp
// Orchids
//
// Created by <NAME> on 16/04/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#include "oscServer.h"
OSCListener::OSCListener(Session* sessObj)
{
try
{
s = new UdpListeningReceiveSocket( IpEndpointName(IpEndpointName::ANY_ADDRESS, LOCAL_PORT), this);
sSession = sessObj;
}
catch (std::runtime_error& e)
{
printf("OSC error: %s\n", e.what());
exit(1);
}
}
OSCListener::~OSCListener()
{
delete s;
}
void OSCListener::startThread()
{
m_Thread = boost::thread(&OSCListener::Run, this);
}
void OSCListener::Run()
{
printf("Running OSC server\n");
s->Run();
}
void OSCListener::Break()
{
printf("Exit OSC server\n");
s->AsynchronousBreak();
}
void OSCListener::Stop()
{
Break();
sleep(0.5);
sendOSCMessage("/Orchids/reply", "exit");
}
void OSCListener::join()
{
m_Thread.join();
}
void OSCListener::ProcessMessage(const osc::ReceivedMessage& m,
const IpEndpointName& remoteEndpoint )
{
try{
//---------------------ABORT---------------------
/*
if( strcmp( m.AddressPattern(), "/Orchids/abort" ) == 0 )
{
// Kill orchesration process
orchestrate_process->interrupt();
}
*/
//---------------------INIT---------------------
if( strcmp( m.AddressPattern(), "/Orchids/init" ) == 0 )
{
//initSession(m, sSession);
}
//---------------------STOP---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/stop" ) == 0 )
{
sSession->exitSession();
}
//---------------------SET CRITERIA---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/setCriteria" ) == 0 )
{
setCriteria(m, sSession);
}
//---------------------SET SEARCH MODE---------------------
else if
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 | //
// oscServer.cpp
// Orchids
//
// Created by <NAME> on 16/04/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#include "oscServer.h"
OSCListener::OSCListener(Session* sessObj)
{
try
{
s = new UdpListeningReceiveSocket( IpEndpointName(IpEndpointName::ANY_ADDRESS, LOCAL_PORT), this);
sSession = sessObj;
}
catch (std::runtime_error& e)
{
printf("OSC error: %s\n", e.what());
exit(1);
}
}
OSCListener::~OSCListener()
{
delete s;
}
void OSCListener::startThread()
{
m_Thread = boost::thread(&OSCListener::Run, this);
}
void OSCListener::Run()
{
printf("Running OSC server\n");
s->Run();
}
void OSCListener::Break()
{
printf("Exit OSC server\n");
s->AsynchronousBreak();
}
void OSCListener::Stop()
{
Break();
sleep(0.5);
sendOSCMessage("/Orchids/reply", "exit");
}
void OSCListener::join()
{
m_Thread.join();
}
void OSCListener::ProcessMessage(const osc::ReceivedMessage& m,
const IpEndpointName& remoteEndpoint )
{
try{
//---------------------ABORT---------------------
/*
if( strcmp( m.AddressPattern(), "/Orchids/abort" ) == 0 )
{
// Kill orchesration process
orchestrate_process->interrupt();
}
*/
//---------------------INIT---------------------
if( strcmp( m.AddressPattern(), "/Orchids/init" ) == 0 )
{
//initSession(m, sSession);
}
//---------------------STOP---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/stop" ) == 0 )
{
sSession->exitSession();
}
//---------------------SET CRITERIA---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/setCriteria" ) == 0 )
{
setCriteria(m, sSession);
}
//---------------------SET SEARCH MODE---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/setSearchMode" ) == 0 )
{
setSearchMode(m, sSession);
}
//---------------------ORCHESTRATE---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/orchestrate" ) == 0 )
{
//orchestrate_process = new boost::thread(orchestrate, m, sSession);
orchestrate(m, sSession);
}
//---------------------AUTOPILOT---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/autoPilot" ) == 0 )
{
launchAutoPilot(m, sSession);
}
//---------------------ADD SOUND DIRECTORIES---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/addSoundDirectories" ) == 0 )
{
addSoundDirectories(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------RECOVER DATABASE BACKUP---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/recoverDBBackup" ) == 0 )
{
addSoundDirectories(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------REMOVE SOUND DIRECTORY---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/removeSoundDirectory" ) == 0 )
{
removeSoundDirectory(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------REFRESH SOUND DIRECTORIES---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/refreshSoundDirectories" ) == 0 )
{
refreshSoundDirectories(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------REFRESH SOUND DIRECTORIES---------------------
else if( strcmp( m.AddressPattern(), "/Orchids/reanalyzeSoundDirectory" ) == 0 )
{
reanalyzeSoundDirectory(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET SYMBOLICS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getSymbolics" ) == 0 )
{
getSymbolics(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET SOUNDS QUERY---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getSoundsQuery" ) == 0 )
{
getSoundsQuery(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET DESCRIPTOR MIN MAX---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getDescriptorMinMax" ) == 0 )
{
getDescriptorMinMax(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET MULTIPLE DESCRIPTOR MIN MAX---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getMultipleDescriptorMinMax" ) == 0 )
{
getMultipleDescriptorMinMax(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET SINGLE---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getSingle" ) == 0 )
{
getSingle(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------GET INDEX LIST---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getIndexList" ) == 0 )
{
getIndexList(m, sSession->getKnowledge()->getBDBConnector());
}
//---------------------SET RESOLUTION---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setResolution" ) == 0 )
{
setResolution(m, sSession->getProduction());
}
//---------------------SET ORCHESTRA---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setOrchestra" ) == 0 )
{
setOrchestra(m, sSession->getProduction());
}
//---------------------SET FILTERS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setFilters" ) == 0 )
{
setFilters(m, sSession->getProduction());
}
//---------------------SET FILTERS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getNumFiltered" ) == 0 )
{
getNumFiltered(m, sSession);
}
//---------------------RESET FILTERS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/resetFilters" ) == 0 )
{
resetFilters(m, sSession->getProduction());
}
//---------------------SET HARMONIC FILTERING---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setHarmonicFiltering" ) == 0 )
{
setHarmonicFiltering(m, sSession->getProduction());
}
//---------------------SET STATIC MODE---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setStaticMode" ) == 0 )
{
setStaticMode(m, sSession->getProduction());
}
//---------------------GET SCORE ORDER---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getScoreOrder" ) == 0 )
{
getScoreOrder(m, sSession->getProduction());
}
//---------------------GET USER INSTRUS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getInstruments" ) == 0 )
{
getUserInstrus(m, sSession->getProduction());
}
//---------------------GET USER PLAYING STYLES---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getPlayingStyles" ) == 0 )
{
getUserPlayingStyles(m, sSession->getProduction());
}
//---------------------GET SOURCES---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getSources" ) == 0 )
{
getSources(m, sSession->getProduction());
}
//---------------------SET SOUNDFILE---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setSoundfile" ) == 0 )
{
setSoundfile(m, sSession);
}
//---------------------SET ANALYSIS PARAMETERS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setAnalysisParameters" ) == 0 )
{
setAnalysisParams(m, sSession);
}
//---------------------SET ABSTRACT TARGET---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setAbstractTarget" ) == 0 )
{
setAbstractTarget(m, sSession);
}
//---------------------SET MULTI TARGET---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setMultiTarget" ) == 0 )
{
setMultiTarget(m, sSession);
}
//---------------------SET MULTI TARGET---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/isInBase" ) == 0 )
{
isInBase(m, sSession->getProduction());
}
//---------------------SET TARGET SELECTION---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setTargetSelection" ) == 0 )
{
setLoopRegion(m, sSession->getTarget());
}
//---------------------SET MULTI TARGET MARKERS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setMarkers" ) == 0 )
{
setMarkers(m, sSession->getTarget());
}
//---------------------SET TARGET DURATION---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setTargetDuration" ) == 0 )
{
setTargetDuration(m, sSession->getTarget());
}
//---------------------SET TARGET FEATURE---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setTargetFeature" ) == 0 )
{
setTargetFeature(m, sSession->getTarget());
}
//---------------------GET TARGET FEATURE---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getTargetSingle" ) == 0 )
{
getTargetSingle(m, sSession->getTarget());
}
//---------------------GET TARGET SYMBOLICS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getTargetSymbolics" ) == 0 )
{
getTargetSymbolics(m, sSession->getTarget());
}
//---------------------GET TARGET SYMBOLICS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/freezeTargetFeature" ) == 0 )
{
freezeFeature(m, sSession->getTarget());
}
//---------------------SET TARGET PARTIALS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setTargetPartials" ) == 0 )
{
setTargetPartials(m, sSession->getTarget());
}
//---------------------SET SEARCH PARAMETER---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setSearchParameter" ) == 0 )
{
setSearchParameter(m, sSession->getSearch());
}
//---------------------SET SOLUTION AS TARGET---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/setSolutionAsTarget" ) == 0 )
{
setSolutionAsTarget(m, sSession);
}
//---------------------EXPORT SOUND SOLUTIONS---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/exportSoundSolutions" ) == 0 )
{
exportSolutions(m, sSession);
}
//---------------------EXPORT ONE WAV SOLUTION---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/exportOneWavSolution" ) == 0 )
{
exportOneWavSolution(m, sSession);
}
//---------------------EXPORT ONE SOLUTION---------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getSolution" ) == 0 )
{
exportOneSolution(m, sSession);
}
//---------------------GET DISTANCES----------------------------
else if ( strcmp( m.AddressPattern(), "/Orchids/getAllSolutionsDistancesFromTarget" ) == 0 )
{
getAllSolutionsDistancesFromTarget(m, sSession);
}
}
catch( osc::Exception& e )
{
// any parsing errors such as unexpected argument types, or
// missing arguments get thrown as exceptions.
std::cout << "error while parsing message: " << m.AddressPattern() << ": " << e.what() << "\n";
sendOSCMessageError(e.what());
}
} |
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:
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, <NAME>, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of <NAME>, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: <NAME>
* <NAME>!!
*********************************************************************/
#include <global_planner/planner_core.h>
#include <visualization_msgs/Marker.h>
#include <pluginlib/class_list_macros.h>
#include <costmap_2d/cost_values.h>
#in
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 | 0 | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, <NAME>, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of <NAME>, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: <NAME>
* <NAME>!!
*********************************************************************/
#include <global_planner/planner_core.h>
#include <visualization_msgs/Marker.h>
#include <pluginlib/class_list_macros.h>
#include <costmap_2d/cost_values.h>
#include <costmap_2d/costmap_2d.h>
#include <global_planner/dijkstra.h>
#include <global_planner/astar.h>
#include <global_planner/grid_path.h>
#include <global_planner/gradient_path.h>
#include <global_planner/quadratic_calculator.h>
#include <mbf_msgs/GetPathAction.h>
//register this planner as a MBF's CostmapPlanner plugin
PLUGINLIB_EXPORT_CLASS(global_planner::GlobalPlanner, mbf_costmap_core::CostmapPlanner)
namespace global_planner {
void GlobalPlanner::outlineMap(unsigned char* costarr, int nx, int ny, unsigned char value) {
unsigned char* pc = costarr;
for (int i = 0; i < nx; i++)
*pc++ = value;
pc = costarr + (ny - 1) * nx;
for (int i = 0; i < nx; i++)
*pc++ = value;
pc = costarr;
for (int i = 0; i < ny; i++, pc += nx)
*pc = value;
pc = costarr + nx - 1;
for (int i = 0; i < ny; i++, pc += nx)
*pc = value;
}
GlobalPlanner::GlobalPlanner() :
costmap_ros_(NULL), costmap_(NULL), initialized_(false), allow_unknown_(true),
p_calc_(NULL), planner_(NULL), path_maker_(NULL), orientation_filter_(NULL),
potential_array_(NULL) {
}
GlobalPlanner::GlobalPlanner(std::string name, costmap_2d::Costmap2D* costmap, std::string frame_id) :
GlobalPlanner() {
//initialize the planner
initialize(name, costmap, frame_id);
}
GlobalPlanner::~GlobalPlanner() {
if (p_calc_)
delete p_calc_;
if (planner_)
delete planner_;
if (path_maker_)
delete path_maker_;
if (dsrv_)
delete dsrv_;
}
void GlobalPlanner::initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros) {
costmap_ros_ = costmap_ros;
initialize(name, costmap_ros->getCostmap(), costmap_ros->getGlobalFrameID());
}
void GlobalPlanner::initialize(std::string name, costmap_2d::Costmap2D* costmap, std::string frame_id) {
if (!initialized_) {
ros::NodeHandle private_nh("~/" + name);
costmap_ = costmap;
frame_id_ = frame_id;
unsigned int cx = costmap->getSizeInCellsX(), cy = costmap->getSizeInCellsY();
private_nh.param("old_navfn_behavior", old_navfn_behavior_, false);
if(!old_navfn_behavior_)
convert_offset_ = 0.5;
else
convert_offset_ = 0.0;
bool use_quadratic;
private_nh.param("use_quadratic", use_quadratic, true);
if (use_quadratic)
p_calc_ = new QuadraticCalculator(cx, cy);
else
p_calc_ = new PotentialCalculator(cx, cy);
bool use_dijkstra;
private_nh.param("use_dijkstra", use_dijkstra, true);
if (use_dijkstra)
{
DijkstraExpansion* de = new DijkstraExpansion(p_calc_, cx, cy);
if(!old_navfn_behavior_)
de->setPreciseStart(true);
planner_ = de;
}
else
planner_ = new AStarExpansion(p_calc_, cx, cy);
bool use_grid_path;
private_nh.param("use_grid_path", use_grid_path, false);
if (use_grid_path)
path_maker_ = new GridPath(p_calc_);
else
path_maker_ = new GradientPath(p_calc_);
orientation_filter_ = new OrientationFilter();
plan_pub_ = private_nh.advertise<nav_msgs::Path>("plan", 1);
potential_pub_ = private_nh.advertise<nav_msgs::OccupancyGrid>("potential", 1);
fp_radii_pub_ = private_nh.advertise<visualization_msgs::Marker>("footprint_radii", 2);
private_nh.param("allow_unknown", allow_unknown_, true);
planner_->setHasUnknown(allow_unknown_);
private_nh.param("planner_window_x", planner_window_x_, 0.0);
private_nh.param("planner_window_y", planner_window_y_, 0.0);
private_nh.param("default_tolerance", default_tolerance_, 0.0);
private_nh.param("publish_scale", publish_scale_, 100);
private_nh.param("outline_map", outline_map_, true);
make_plan_srv_ = private_nh.advertiseService("make_plan", &GlobalPlanner::makePlanService, this);
dsrv_ = new dynamic_reconfigure::Server<global_planner::GlobalPlannerConfig>(ros::NodeHandle("~/" + name));
dynamic_reconfigure::Server<global_planner::GlobalPlannerConfig>::CallbackType cb = boost::bind(
&GlobalPlanner::reconfigureCB, this, _1, _2);
dsrv_->setCallback(cb);
initialized_ = true;
} else
ROS_WARN("This planner has already been initialized, you can't call it twice, doing nothing");
}
void GlobalPlanner::reconfigureCB(global_planner::GlobalPlannerConfig& config, uint32_t level) {
planner_->setLethalCost(config.lethal_cost);
path_maker_->setLethalCost(config.lethal_cost);
planner_->setNeutralCost(config.neutral_cost);
planner_->setFactor(config.cost_factor);
publish_potential_ = config.publish_potential;
show_footprint_radii_ = config.show_footprint_radii;
if (!show_footprint_radii_)
clearFootprintRadii();
orientation_filter_->setMode(config.orientation_mode);
orientation_filter_->setWindowSize(config.orientation_window_size);
}
void GlobalPlanner::clearRobotCell(const geometry_msgs::PoseStamped& global_pose, unsigned int mx, unsigned int my) {
if (!initialized_) {
ROS_ERROR(
"This planner has not been initialized yet, but it is being used, please call initialize() before use");
return;
}
//set the associated costs in the cost map to be free
costmap_->setCost(mx, my, costmap_2d::FREE_SPACE);
}
bool GlobalPlanner::makePlanService(nav_msgs::GetPlan::Request& req, nav_msgs::GetPlan::Response& resp) {
double cost;
std::string message;
makePlan(req.start, req.goal, 0.0, resp.plan.poses, cost, message);
resp.plan.header.stamp = ros::Time::now();
resp.plan.header.frame_id = frame_id_;
return true;
}
void GlobalPlanner::mapToWorld(double mx, double my, double& wx, double& wy) {
wx = costmap_->getOriginX() + (mx+convert_offset_) * costmap_->getResolution();
wy = costmap_->getOriginY() + (my+convert_offset_) * costmap_->getResolution();
}
bool GlobalPlanner::worldToMap(double wx, double wy, double& mx, double& my) {
double origin_x = costmap_->getOriginX(), origin_y = costmap_->getOriginY();
double resolution = costmap_->getResolution();
if (wx < origin_x || wy < origin_y)
return false;
mx = (wx - origin_x) / resolution;
my = (wy - origin_y) / resolution;
if (mx < costmap_->getSizeInCellsX() && my < costmap_->getSizeInCellsY())
return true;
return false;
}
uint32_t GlobalPlanner::makePlan(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal,
double tolerance, std::vector<geometry_msgs::PoseStamped>& plan, double& cost,
std::string& message) {
boost::mutex::scoped_lock lock(mutex_);
if (!initialized_) {
message = "This planner has not been initialized yet, but it is being used, please call initialize() before use";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::NOT_INITIALIZED;
}
//clear the plan, just in case
plan.clear();
ros::NodeHandle n;
std::string global_frame = frame_id_;
//until tf can handle transforming things that are way in the past... we'll require the goal to be in our global frame
if (goal.header.frame_id != global_frame) {
message = "The goal pose passed to this planner must be in the " + global_frame + " frame. It is instead in the " + goal.header.frame_id + " frame";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::INVALID_GOAL;
}
if (start.header.frame_id != global_frame) {
message = "The start pose passed to this planner must be in the " + global_frame + " frame. It is instead in the " + start.header.frame_id + " frame";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::INVALID_START;
}
double wx = start.pose.position.x;
double wy = start.pose.position.y;
unsigned int start_x_i, start_y_i, goal_x_i, goal_y_i;
double start_x, start_y, goal_x, goal_y;
if (!costmap_->worldToMap(wx, wy, start_x_i, start_y_i)) {
message = "The robot's start position is off the global costmap. Planning will always fail, are you sure the robot has been properly localized?";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::OUT_OF_MAP;
}
if(old_navfn_behavior_){
start_x = start_x_i;
start_y = start_y_i;
}else{
worldToMap(wx, wy, start_x, start_y);
}
wx = goal.pose.position.x;
wy = goal.pose.position.y;
if (!costmap_->worldToMap(wx, wy, goal_x_i, goal_y_i)) {
message = "The goal sent to the global planner is off the global costmap. Planning will always fail to this goal";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::OUT_OF_MAP;
}
if(old_navfn_behavior_){
goal_x = goal_x_i;
goal_y = goal_y_i;
}else{
worldToMap(wx, wy, goal_x, goal_y);
}
// check if either start or goal poses are in collision
if (costmap_->getCost(start_x_i, start_y_i) >= costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
message = "The start pose is in collision. Planning from this pose will always fail";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::BLOCKED_START;
}
if (tolerance == 0 && costmap_->getCost(goal_x_i, goal_y_i) >= costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
message = "The goal pose is in collision, and the tolerance is set to zero";
ROS_ERROR_STREAM(message);
return mbf_msgs::GetPathResult::BLOCKED_GOAL;
}
int nx = costmap_->getSizeInCellsX(), ny = costmap_->getSizeInCellsY();
//make sure to resize the underlying array that Navfn uses
p_calc_->setSize(nx, ny);
planner_->setSize(nx, ny);
path_maker_->setSize(nx, ny);
potential_array_ = new float[nx * ny];
if(outline_map_)
outlineMap(costmap_->getCharMap(), nx, ny, costmap_2d::LETHAL_OBSTACLE);
bool found_legal = planner_->calculatePotentials(costmap_->getCharMap(), start_x, start_y, goal_x, goal_y,
nx * ny * 2, potential_array_);
geometry_msgs::PoseStamped best_pose = goal;
bool goal_blocked = !found_legal;
if (!found_legal) {
// calculatePotentials did not result in a valid potential at the goal cell:
// Check if any cells within tolerance around the goal have a valid potential:
// - if so, set found_legal to true and displace the goal,
// such the getPlanFromPotential will generate a path to the displaced goal
// - if not, check whether any of the cells are even in free space (if not, report goal blocked)
double resolution = costmap_->getResolution();
geometry_msgs::PoseStamped p = goal;
double best_sdist = DBL_MAX;
// reduce tolerance to ensure all poses are clearly inside the tolerance
// TODO: use constexpr T max( std::initializer_list<T> ilist ); (since C++14)
const double tol_reduction = 1e-6 * std::max(std::max(1.0, tolerance), std::max(std::abs(p.pose.position.x), std::abs(p.pose.position.y)));
const double reduced_tolerance = tolerance - tol_reduction;
// sample denser than cell to not unnecessarily use up tolerance, and ensure at least 5 sampled points
const double step_size = std::min(0.5 * resolution, 0.999*reduced_tolerance);
unsigned int mx, my;
for(double dy = -reduced_tolerance; dy <= reduced_tolerance; dy += step_size){
p.pose.position.y = goal.pose.position.y + dy;
const double dx = std::sqrt(reduced_tolerance*reduced_tolerance - dy*dy);
for(p.pose.position.x = goal.pose.position.x - dx; p.pose.position.x <= goal.pose.position.x + dx; p.pose.position.x += step_size){
if(costmap_->worldToMap(p.pose.position.x, p.pose.position.y, mx, my)) {
unsigned int index = my * nx + mx;
double potential = potential_array_[index];
double sdist = sq_distance(p, goal);
ROS_FATAL_STREAM_COND(sdist > tolerance, "sampled pose is " << sdist << " away from the goal, which is above tolerance " << tolerance);
assert(sdist <= tolerance);
if(potential < POT_HIGH && sdist < best_sdist && sdist < tolerance){
best_sdist = sdist;
best_pose = p;
found_legal = true;
goal_blocked = false;
} else if (costmap_->getCost(goal_x_i, goal_y_i) < costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
goal_blocked = false;
}
}
}
}
if (found_legal) {
if(old_navfn_behavior_){
goal_x = goal_x_i;
goal_y = goal_y_i;
}else{
worldToMap(best_pose.pose.position.x, best_pose.pose.position.y, goal_x, goal_y);
}
}
}
if(!old_navfn_behavior_)
planner_->clearEndpoint(costmap_->getCharMap(), potential_array_, goal_x_i, goal_y_i, 2);
if(publish_potential_)
publishPotential(potential_array_);
if(show_footprint_radii_)
showFootprintRadii();
if (goal_blocked) {
message = "All cells around the goal within the tolerance are in collision";
ROS_ERROR_STREAM(message);
delete[] potential_array_;
return mbf_msgs::GetPathResult::BLOCKED_GOAL;
}
if (found_legal) {
//extract the plan
if (getPlanFromPotential(start_x, start_y, goal_x, goal_y, best_pose, plan)) {
//make sure the goal we push on has the same timestamp as the rest of the plan
best_pose.header.stamp = ros::Time::now();
plan.push_back(best_pose);
} else {
message = "Failed to get a plan from potential when a legal potential was found. This shouldn't happen";
ROS_ERROR_STREAM(message);
}
}else{
message = "Failed to get a plan";
ROS_ERROR_STREAM(message);
}
// add orientations if needed
orientation_filter_->processPath(start, plan);
//publish the plan for visualization purposes
publishPlan(plan);
delete[] potential_array_;
return plan.empty() ? mbf_msgs::GetPathResult::NO_PATH_FOUND : mbf_msgs::GetPathResult::SUCCESS;
}
void GlobalPlanner::publishPlan(const std::vector<geometry_msgs::PoseStamped>& path) {
if (!initialized_) {
ROS_ERROR(
"This planner has not been initialized yet, but it is being used, please call initialize() before use");
return;
}
//create a message for the plan
nav_msgs::Path gui_path;
gui_path.poses.resize(path.size());
gui_path.header.frame_id = frame_id_;
gui_path.header.stamp = ros::Time::now();
// Extract the plan in world co-ordinates, we assume the path is all in the same frame
for (unsigned int i = 0; i < path.size(); i++) {
gui_path.poses[i] = path[i];
}
plan_pub_.publish(gui_path);
}
bool GlobalPlanner::getPlanFromPotential(double start_x, double start_y, double goal_x, double goal_y,
const geometry_msgs::PoseStamped& goal,
std::vector<geometry_msgs::PoseStamped>& plan) {
if (!initialized_) {
ROS_ERROR(
"This planner has not been initialized yet, but it is being used, please call initialize() before use");
return false;
}
std::string global_frame = frame_id_;
//clear the plan, just in case
plan.clear();
std::vector<std::pair<float, float> > path;
if (!path_maker_->getPath(potential_array_, start_x, start_y, goal_x, goal_y, path)) {
ROS_ERROR("NO PATH!");
return false;
}
ros::Time plan_time = ros::Time::now();
for (int i = path.size() -1; i>=0; i--) {
std::pair<float, float> point = path[i];
//convert the plan to world coordinates
double world_x, world_y;
mapToWorld(point.first, point.second, world_x, world_y);
geometry_msgs::PoseStamped pose;
pose.header.stamp = plan_time;
pose.header.frame_id = global_frame;
pose.pose.position.x = world_x;
pose.pose.position.y = world_y;
pose.pose.position.z = 0.0;
pose.pose.orientation.x = 0.0;
pose.pose.orientation.y = 0.0;
pose.pose.orientation.z = 0.0;
pose.pose.orientation.w = 1.0;
plan.push_back(pose);
}
if(old_navfn_behavior_){
plan.push_back(goal);
}
return !plan.empty();
}
void GlobalPlanner::publishPotential(float* potential)
{
int nx = costmap_->getSizeInCellsX(), ny = costmap_->getSizeInCellsY();
double resolution = costmap_->getResolution();
nav_msgs::OccupancyGrid grid;
// Publish Whole Grid
grid.header.frame_id = frame_id_;
grid.header.stamp = ros::Time::now();
grid.info.resolution = resolution;
grid.info.width = nx;
grid.info.height = ny;
double wx, wy;
costmap_->mapToWorld(0, 0, wx, wy);
grid.info.origin.position.x = wx - resolution / 2;
grid.info.origin.position.y = wy - resolution / 2;
grid.info.origin.position.z = 0.0;
grid.info.origin.orientation.w = 1.0;
grid.data.resize(nx * ny);
float max = 0.0;
for (unsigned int i = 0; i < grid.data.size(); i++) {
float potential = potential_array_[i];
if (potential < POT_HIGH) {
if (potential > max) {
max = potential;
}
}
}
for (unsigned int i = 0; i < grid.data.size(); i++) {
if (potential_array_[i] >= POT_HIGH) {
grid.data[i] = -1;
} else {
if (fabs(max) < DBL_EPSILON) {
grid.data[i] = -1;
} else {
grid.data[i] = potential_array_[i] * publish_scale_ / max;
}
}
}
potential_pub_.publish(grid);
}
void GlobalPlanner::showFootprintRadii() const
{
if (!costmap_ros_)
return;
double inscribed_radius, circumscribed_radius;
costmap_2d::calculateMinAndMaxDistances(costmap_ros_->getRobotFootprint(), inscribed_radius, circumscribed_radius);
// show the inscribed radius (in blue)
visualization_msgs::Marker marker;
marker.header.frame_id = costmap_ros_->getBaseFrameID();
marker.header.stamp = ros::Time::now();
marker.ns = "inscribed_radius";
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.orientation.w = 1.0;
marker.points = costmap_2d::makeFootprintFromRadius(inscribed_radius);
marker.points.push_back(marker.points.front()); // close the polygon
marker.scale.x = 0.01;
marker.color.b = 1.0;
marker.color.a = 0.5;
fp_radii_pub_.publish(marker);
// repeat for the circumscribed radius (in red)
marker.ns = "circumscribed_radius";
marker.points = costmap_2d::makeFootprintFromRadius(circumscribed_radius);
marker.points.push_back(marker.points.front()); // close the polygon
marker.color.r = 1.0;
marker.color.b = 0.0;
fp_radii_pub_.publish(marker);
}
void GlobalPlanner::clearFootprintRadii() const
{
visualization_msgs::Marker marker;
marker.action = visualization_msgs::Marker::DELETEALL;
fp_radii_pub_.publish(marker);
}
} //end namespace global_planner
|
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:
// https://www.reddit.com/r/AlgoExpert/comments/etbi4o/day_4_20200124_problem_of_the_day_asked_by/
use std::cmp;
// SS: O(N log N)
fn merge_overlapping_ranges_1(ranges: &mut [(i64, i64)]) -> Vec<(i64, i64)> {
// SS: check for empty
if ranges.len() <= 1 {
ranges.to_vec()
} else {
// SS: O(N log N) to sort
ranges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let mut result = vec![];
let mut current_range = ranges[0];
// SS: O(N)
for i in 1..ranges.len() {
let r = ranges[i];
if r.0 <= current_range.1 {
// SS: overlap
current_range.1 = cmp::max(current_range.1, r.1);
} else {
// SS: no overlap
result.push(current_range);
current_range = r;
}
}
result.push(current_range);
result
}
}
#[cfg(test)]
mod tests {
use crate::merge_overlapping_ranges_1;
#[test]
fn test1() {
// Arrange
let mut input = [(1, 3), (4, 10), (5, 8), (20, 25)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 3), (4, 10), (20, 25)]);
}
#[test]
fn test2() {
// Arrange
let mut input = [(1, 3), (4, 10), (2, 12)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 12)]);
}
#[test]
fn test3() {
// Arrange
let mut input = [(1, 3), (4, 6), (2, 12), (20, 25)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 12), (20, 25)]);
}
}
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 | 5 | // https://www.reddit.com/r/AlgoExpert/comments/etbi4o/day_4_20200124_problem_of_the_day_asked_by/
use std::cmp;
// SS: O(N log N)
fn merge_overlapping_ranges_1(ranges: &mut [(i64, i64)]) -> Vec<(i64, i64)> {
// SS: check for empty
if ranges.len() <= 1 {
ranges.to_vec()
} else {
// SS: O(N log N) to sort
ranges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let mut result = vec![];
let mut current_range = ranges[0];
// SS: O(N)
for i in 1..ranges.len() {
let r = ranges[i];
if r.0 <= current_range.1 {
// SS: overlap
current_range.1 = cmp::max(current_range.1, r.1);
} else {
// SS: no overlap
result.push(current_range);
current_range = r;
}
}
result.push(current_range);
result
}
}
#[cfg(test)]
mod tests {
use crate::merge_overlapping_ranges_1;
#[test]
fn test1() {
// Arrange
let mut input = [(1, 3), (4, 10), (5, 8), (20, 25)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 3), (4, 10), (20, 25)]);
}
#[test]
fn test2() {
// Arrange
let mut input = [(1, 3), (4, 10), (2, 12)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 12)]);
}
#[test]
fn test3() {
// Arrange
let mut input = [(1, 3), (4, 6), (2, 12), (20, 25)];
// Act
let result = merge_overlapping_ranges_1(&mut input);
// Assert
assert_eq!(&result[..], &[(1, 12), (20, 25)]);
}
}
|
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:
### first we mince the ginger
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 | ### first we mince the ginger
|
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 cryptography.console.command
class CommandHide(
val message: String,
val password: String,
val inputFile: String,
val outputFile: String,
) : Command
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 cryptography.console.command
class CommandHide(
val message: String,
val password: String,
val inputFile: String,
val outputFile: String,
) : Command
|
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:
//
// GenreView.swift
// SwiftUI_Starter
//
// Created by <NAME> on 29/08/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
struct GenreView: View {
var body: some View {
return HStack(spacing: 15) {
Button(action: actionMethod) {
Text("Action")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
Button(action: actionMethod) {
Text("Biography")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
Button(action: actionMethod) {
Text("Drama")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
}.padding([.top], 10)
}
func actionMethod() {
}
}
struct GenreView_Previews: PreviewProvider {
static var previews: some View {
GenreView()
}
}
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 | //
// GenreView.swift
// SwiftUI_Starter
//
// Created by <NAME> on 29/08/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
struct GenreView: View {
var body: some View {
return HStack(spacing: 15) {
Button(action: actionMethod) {
Text("Action")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
Button(action: actionMethod) {
Text("Biography")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
Button(action: actionMethod) {
Text("Drama")
.padding([.leading,.trailing], 20)
.padding([.top,.bottom], 5)
.overlay(
Capsule(style: .continuous)
.stroke(Color.gray, lineWidth: 1)
)
}.accentColor(.black)
}.padding([.top], 10)
}
func actionMethod() {
}
}
struct GenreView_Previews: PreviewProvider {
static var previews: some View {
GenreView()
}
}
|
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 width_bucket(3.5::float8, 3.0::float8, 3.0::float8, 888);
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 width_bucket(3.5::float8, 3.0::float8, 3.0::float8, 888);
|
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:
//
// CountriesTableViewController.swift
// Weather
//
// Created by <NAME> on 9/26/20.
//
import UIKit
protocol CountriesTableViewControllerDelegate {
func filterVenues(by country: Country)
}
class CountriesTableViewController: UITableViewController {
//MARK: - Storyboard Connections
@IBOutlet var countriesTableView: UITableView!
//MARK: - Properties
var countries: [Country]?
private var filterCountry: Country?
var delegate: CountriesTableViewControllerDelegate?
//MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
configureCountriesTableView()
}
//MARK: - UI Configuration
private func configureNavigationBar() {
title = "Filter by Country"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissVC))
}
private func configureCountriesTableView() {
countriesTableView.register(UINib(nibName: CountriesTableViewCell.nibName, bundle: nil), forCellReuseIdentifier: CountriesTableViewCell.reuseIdentifier)
countriesTableView.tableFooterView = UIView() //hides empty rows
}
}
// MARK: - TableView DataSource
extension CountriesTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CountriesTableViewCell.reuseIdentifier, for: indexPath) as! CountriesTableViewCell
if let countries = self.countries {
let country = countries[indexPath.row]
cell.setContent(with: country)
}
return cell
}
}
//MARK: - TableView Delegate
extension CountriesTableViewController {
override func tableView(_ tableView: UITabl
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 | //
// CountriesTableViewController.swift
// Weather
//
// Created by <NAME> on 9/26/20.
//
import UIKit
protocol CountriesTableViewControllerDelegate {
func filterVenues(by country: Country)
}
class CountriesTableViewController: UITableViewController {
//MARK: - Storyboard Connections
@IBOutlet var countriesTableView: UITableView!
//MARK: - Properties
var countries: [Country]?
private var filterCountry: Country?
var delegate: CountriesTableViewControllerDelegate?
//MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationBar()
configureCountriesTableView()
}
//MARK: - UI Configuration
private func configureNavigationBar() {
title = "Filter by Country"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissVC))
}
private func configureCountriesTableView() {
countriesTableView.register(UINib(nibName: CountriesTableViewCell.nibName, bundle: nil), forCellReuseIdentifier: CountriesTableViewCell.reuseIdentifier)
countriesTableView.tableFooterView = UIView() //hides empty rows
}
}
// MARK: - TableView DataSource
extension CountriesTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CountriesTableViewCell.reuseIdentifier, for: indexPath) as! CountriesTableViewCell
if let countries = self.countries {
let country = countries[indexPath.row]
cell.setContent(with: country)
}
return cell
}
}
//MARK: - TableView Delegate
extension CountriesTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let countries = self.countries {
let country = countries[indexPath.row]
filterCountry = country
}
dismissVC()
}
}
//MARK: - Navigation
extension CountriesTableViewController {
@objc func dismissVC() {
if let country = filterCountry {
delegate?.filterVenues(by: country)
}
dismiss(animated: true, completion: nil)
}
}
|
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
#
# Author: jacob
# Email:
# Github: https://github.com/bavdu
# Date:
echo ---------------------$(date)------------------------
awk '{ R[$3]++ } END{ for(i in R){ print i,R[i] }}' $1 |sort -k2 -rn
awk -v number=0 '{ R[$3]++ } END{ for(i in R){ number=number+R[i] } print "总和为:"number }' $1
echo ------------------------finish--------------------------------------
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
#
# Author: jacob
# Email:
# Github: https://github.com/bavdu
# Date:
echo ---------------------$(date)------------------------
awk '{ R[$3]++ } END{ for(i in R){ print i,R[i] }}' $1 |sort -k2 -rn
awk -v number=0 '{ R[$3]++ } END{ for(i in R){ number=number+R[i] } print "总和为:"number }' $1
echo ------------------------finish--------------------------------------
|
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:
How to unmodify a modified file
Using tags for version control
Limiting log output by time
Search for commits by author
Remote repositories: fetching and pushing
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 | 0 | How to unmodify a modified file
Using tags for version control
Limiting log output by time
Search for commits by author
Remote repositories: fetching and pushing |
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 mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String,
required: true,
trim: true,
minlength: [3, 'Name should be at least 3 characters long'],
},
email: {
type: String,
required: true,
trim: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email',
},
},
password: {
type: String,
required: true,
minlength: [6, 'Password should be at least 6 characters long'],
},
});
UserSchema.statics.findByCredentials = function (email, password) {
const User = this;
return User.findOne({ email }).then((user) => {
if (!user) {
return Promise.reject();
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
if (res) {
resolve(user);
} else {
reject(err);
}
});
});
});
};
UserSchema.pre('save', function (next) {
const user = this;
const saltRounds = 10;
if (user.isModified('password')) {
bcrypt.hash(user.password, saltRounds, (err, hash) => {
if (err) {
return next(err);
}
user.password = <PASSWORD>;
return next();
});
} else {
next();
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
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 | const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String,
required: true,
trim: true,
minlength: [3, 'Name should be at least 3 characters long'],
},
email: {
type: String,
required: true,
trim: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email',
},
},
password: {
type: String,
required: true,
minlength: [6, 'Password should be at least 6 characters long'],
},
});
UserSchema.statics.findByCredentials = function (email, password) {
const User = this;
return User.findOne({ email }).then((user) => {
if (!user) {
return Promise.reject();
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
if (res) {
resolve(user);
} else {
reject(err);
}
});
});
});
};
UserSchema.pre('save', function (next) {
const user = this;
const saltRounds = 10;
if (user.isModified('password')) {
bcrypt.hash(user.password, saltRounds, (err, hash) => {
if (err) {
return next(err);
}
user.password = <PASSWORD>;
return next();
});
} else {
next();
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
|
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 { Base } from './base.js';
import { paramTypes } from './_types.js';
import { EJSON } from 'meteor/ejson';
export class Originate extends Base {
get params() {
return _.extend(super.params, {
timeout: {
type: paramTypes.uint
},
destination: {
type: paramTypes.string
},
endpoint: {
type: paramTypes.string
},
workflow: {
type: paramTypes.workflow
},
saveIn: {
type: paramTypes.saveVar
},
workflowParam: {
type: paramTypes.readVar
}
});
}
job () {
this.ari.Channel().originate({
timeout: this.node.params.timeout || 30000,
endpoint: (this.node.params.endpoint || 'SIP') + '/' + this.node.params.destination,
app: 'hello-world',
appArgs: new Buffer(EJSON.stringify({
workflow: this.node.params.workflow,
params: { [this.node.params.workflowParam]: this.vars[this.node.params.workflowParam]}
})).toString('base64')
}).then(channel => {
console.log('originate success');
this.resolve('success',{saveVar: {
[this.node.params.saveIn]: channel.id
}});
}).catch(err => {
console.log('originate error', err);
this.resolve('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 | 1 | import { Base } from './base.js';
import { paramTypes } from './_types.js';
import { EJSON } from 'meteor/ejson';
export class Originate extends Base {
get params() {
return _.extend(super.params, {
timeout: {
type: paramTypes.uint
},
destination: {
type: paramTypes.string
},
endpoint: {
type: paramTypes.string
},
workflow: {
type: paramTypes.workflow
},
saveIn: {
type: paramTypes.saveVar
},
workflowParam: {
type: paramTypes.readVar
}
});
}
job () {
this.ari.Channel().originate({
timeout: this.node.params.timeout || 30000,
endpoint: (this.node.params.endpoint || 'SIP') + '/' + this.node.params.destination,
app: 'hello-world',
appArgs: new Buffer(EJSON.stringify({
workflow: this.node.params.workflow,
params: { [this.node.params.workflowParam]: this.vars[this.node.params.workflowParam]}
})).toString('base64')
}).then(channel => {
console.log('originate success');
this.resolve('success',{saveVar: {
[this.node.params.saveIn]: channel.id
}});
}).catch(err => {
console.log('originate error', err);
this.resolve('error');
});
}
}
|
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:
/**
* \file main_test_commandline.cpp
* \brief This is the main file for the test commandline
*
* \date aug. 21, 2015
* \author alexander
*
* \ingroup autotest
**/
#include <iostream>
#include "gtest/gtest.h"
#include "core/utils/global.h"
#include "core/reflection/commandLineSetter.h"
#include "core/reflection/commandLineGetter.h"
#include "core/math/vector/vector3d.h"
using namespace corecvs;
using std::istream;
using std::ostream;
using std::cout;
TEST(CommandLine, testAdditionalFunction)
{
const char *argv[] = {"--bool", "--int=42", "--double=3.14", "--string=test1"};
int argc = CORE_COUNT_OF(argv);
CommandLineSetter setter(argc, argv);
bool boolVal = setter.getBool("bool");
int intVal = setter.getInt("int");
double dblVal = setter.getDouble("double");
string strVal = setter.getString("string", "");
//cout << "Bool:" << b << endl;
//cout << "Int:" << i << endl;
//cout << "Double:" << d << endl;
CORE_ASSERT_TRUE(boolVal == true, "Bool parsing problem");
CORE_ASSERT_TRUE(intVal == 42, "Int parsing problem");
CORE_ASSERT_TRUE(dblVal == 3.14, "Double parsing problem");
CORE_ASSERT_TRUE(strVal == "test1", "String parsing problem");
}
TEST(CommandLine, testVisitor)
{
const char *argv[] = {"--x=2.4", "--y=42", "--z=3.14"};
int argc = CORE_COUNT_OF(argv);
CommandLineSetter setter(argc, argv);
Vector3dd in (1.0,2.0,3.0);
cout << "Before Loading :" << in << std::endl;
in.accept<CommandLineSetter>(setter);
cout << "After Loading :" << in << std::endl;
CommandLineGetter getter;
in.accept<CommandLineGetter>(getter);
cout << getter.str() << std::endl;
CORE_ASSERT_TRUE(in.x() == 2.4, "Error in visitor x");
CORE_ASSERT_TRUE(in.y() == 42, "Error in visitor y");
CORE_ASSERT_TRUE(in.z() == 3.14, "Error in visitor z");
}
TEST(CommandLine, testSubstring)
{
const char *argv[] = {"./bin/test_cloud_match", "--icplis
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 | /**
* \file main_test_commandline.cpp
* \brief This is the main file for the test commandline
*
* \date aug. 21, 2015
* \author alexander
*
* \ingroup autotest
**/
#include <iostream>
#include "gtest/gtest.h"
#include "core/utils/global.h"
#include "core/reflection/commandLineSetter.h"
#include "core/reflection/commandLineGetter.h"
#include "core/math/vector/vector3d.h"
using namespace corecvs;
using std::istream;
using std::ostream;
using std::cout;
TEST(CommandLine, testAdditionalFunction)
{
const char *argv[] = {"--bool", "--int=42", "--double=3.14", "--string=test1"};
int argc = CORE_COUNT_OF(argv);
CommandLineSetter setter(argc, argv);
bool boolVal = setter.getBool("bool");
int intVal = setter.getInt("int");
double dblVal = setter.getDouble("double");
string strVal = setter.getString("string", "");
//cout << "Bool:" << b << endl;
//cout << "Int:" << i << endl;
//cout << "Double:" << d << endl;
CORE_ASSERT_TRUE(boolVal == true, "Bool parsing problem");
CORE_ASSERT_TRUE(intVal == 42, "Int parsing problem");
CORE_ASSERT_TRUE(dblVal == 3.14, "Double parsing problem");
CORE_ASSERT_TRUE(strVal == "test1", "String parsing problem");
}
TEST(CommandLine, testVisitor)
{
const char *argv[] = {"--x=2.4", "--y=42", "--z=3.14"};
int argc = CORE_COUNT_OF(argv);
CommandLineSetter setter(argc, argv);
Vector3dd in (1.0,2.0,3.0);
cout << "Before Loading :" << in << std::endl;
in.accept<CommandLineSetter>(setter);
cout << "After Loading :" << in << std::endl;
CommandLineGetter getter;
in.accept<CommandLineGetter>(getter);
cout << getter.str() << std::endl;
CORE_ASSERT_TRUE(in.x() == 2.4, "Error in visitor x");
CORE_ASSERT_TRUE(in.y() == 42, "Error in visitor y");
CORE_ASSERT_TRUE(in.z() == 3.14, "Error in visitor z");
}
TEST(CommandLine, testSubstring)
{
const char *argv[] = {"./bin/test_cloud_match", "--icplist", "test", "test"};
int argc = CORE_COUNT_OF(argv);
CommandLineSetter setter(argc, argv);
cout << setter.getBool("icp") << " " << setter.getBool("icplist") << std::endl;
CORE_ASSERT_TRUE(setter.getBool("icp") == false, "False positive");
CORE_ASSERT_TRUE(setter.getBool("icplist") == true, "False negative");
}
|
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 TrabajoTarjeta;
class TiempoFalso extends Tiempo implements TiempoInterface {
protected $tiempo;
public function __construct($tiempoInicial = 0) {
$this->tiempo = $tiempoInicial;
}
public function avanzar($segundos) {
$this->tiempo += $segundos;
}
public function time() {
return $this->tiempo;
}
}
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
namespace TrabajoTarjeta;
class TiempoFalso extends Tiempo implements TiempoInterface {
protected $tiempo;
public function __construct($tiempoInicial = 0) {
$this->tiempo = $tiempoInicial;
}
public function avanzar($segundos) {
$this->tiempo += $segundos;
}
public function time() {
return $this->tiempo;
}
} |
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:
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
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 | 0 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
#ifndef _MTK_CAMERA_FEATURE_PIPE_INTERFACE_DEPTH_MAP_PIPE_H_
#define _MTK_CAMERA_FEATURE_PIPE_INTERFACE_DEPTH_MAP_PIPE_H_
#include <utils/RefBase.h>
#include <mtkcam/def/common.h>
#include <mtkcam/feature/effectHalBase/EffectRequest.h>
namespace NSCam {
namespace NSCamFeature {
namespace NSFeaturePipe {
#define VSDOF_PARAMS_METADATA_KEY "Metadata"
#define DEPTHMAP_COMPLETE_KEY "onComplete"
#define DEPTHMAP_FLUSH_KEY "onFlush"
#define DEPTHMAP_ERROR_KEY "onError"
#define DEPTHMAP_REQUEST_STATE_KEY "ReqStatus"
#define DEPTHMAP_REQUEST_TIMEKEY "TimeStamp"
typedef enum DepthMapNode_BufferDataTypes{
BID_DEPTHMAPPIPE_INVALID = 0,
// P2A input raw
BID_P2AFM_IN_FSRAW1,
BID_P2AFM_IN_FSRAW2,
BID_P2AFM_IN_RSRAW1,
BID_P2AFM_IN_RSRAW2,
// internal P2A buffers
BID_P2AFM_FE1B_INPUT,
BID_P2AFM_FE2B_INPUT,
BID_P2AFM_FE1C_INPUT,
BID_P2AFM_FE2C_INPUT,
// p2a output
BID_P2AFM_OUT_FDIMG,
BID_P2AFM_OUT_FE1BO,//10
BID_P2AFM_OUT_FE2BO,
BID_P2AFM_OUT_FE1CO,
BID_P2AFM_OUT_FE2CO,
BID_P2AFM_OUT_RECT_IN1,
BID_P2AFM_OUT_RECT_IN2,
BID_P2AFM_OUT_RECT_IN1_CAP,
BID_P2AFM_OUT_RECT_IN2_CAP,
BID_P2AFM_OUT_CC_IN1,
BID_P2AFM_OUT_CC_IN2,
BID_P2AFM_OUT_FMBO_LR,//20
BID_P2AFM_OUT_FMBO_RL,
BID_P2AFM_OUT_FMCO_LR,
BID_P2AFM_OUT_FMCO_RL,
BID_P2AFM_OUT_MV_F,
BID_P2AFM_OUT_MV_F_CAP,
// N3D output
BID_N3D_OUT_MV_Y,
BID_N3D_OUT_MASK_M,
BID_N3D_OUT_SV_Y,
BID_N3D_OUT_MASK_S,
BID_N3D_OUT_LDC,//30
BID_N3D_OUT_JPS_MAIN1,
BID_N3D_OUT_JPS_MAIN2,
// DPE output
BID_DPE_OUT_CFM_L,
BID_DPE_OUT_CFM_R,
BID_DPE_OUT_DMP_L,
BID_DPE_OUT_DMP_R,
BID_DPE_OUT_RESPO_L,
BID_DPE_OUT_RESPO_R,
// OCC output
BID_OCC_OUT_DMH,
BID_OCC_OUT_MY_S,//40
// WMF
BID_WMF_OUT_DMW,
BID_WMF_DMW_INTERNAL,
// GF
BID_GF_INTERAL_DEPTHMAP,
BID_GF_OUT_DMBG,
BID_GF_OUT_DEPTHMAP,
// FD
BID_FD_OUT_EXTRADATA,
// metadata
BID_META_IN_APP,
BID_META_IN_HAL,
BID_META_IN_HAL_MAIN2,
BID_META_OUT_APP,
BID_META_OUT_HAL,
// queued meta
BID_META_IN_APP_QUEUED,
BID_META_IN_HAL_QUEUED,
BID_META_IN_HAL_MAIN2_QUEUED,
BID_META_OUT_APP_QUEUED,
BID_META_OUT_HAL_QUEUED,
#ifdef GTEST
// UT output
BID_FE2_HWIN_MAIN1,
BID_FE2_HWIN_MAIN2,
BID_FE3_HWIN_MAIN1,
BID_FE3_HWIN_MAIN2,
#endif
// alias section(must be placed bottom)
BID_TO_GF_MY_SLL = BID_P2AFM_FE1B_INPUT,
BID_TO_GF_MY_SL = BID_P2AFM_FE1C_INPUT,
BID_P2AFM_OUT_MY_S = BID_OCC_OUT_MY_S
} DepthMapBufferID;
typedef enum eDepthNodeOpState {
eSTATE_NORMAL = 1,
eSTATE_CAPTURE = 2
} DepthNodeOpState;
typedef enum eDepthFlowType {
eDEPTH_FLOW_TYPE_STANDARD,
eDEPTH_FLOW_TYPE_QUEUED_DEPTH
} DepthFlowType;
const MUINT8 DEPTH_FLOW_QUEUE_SIZE = 3;
const DepthMapBufferID INPUT_METADATA_BID_LIST[] = {BID_META_IN_APP, BID_META_IN_HAL, BID_META_IN_HAL_MAIN2};
const DepthMapBufferID OUTPUT_METADATA_BID_LIST[] = {BID_META_OUT_APP, BID_META_OUT_HAL};
/******************************************************************************
* The Interface of DepthMapNode's FeaturePipe
******************************************************************************/
class IDepthMapPipe
{
public:
/**
* @brief DepthMapPipe creation
* @param [in] flowType controlling depth flow
* @param [in] iSensorIdx_Main1 sensor index of main1
* @param [in] iSensorIdx_Main2 sensor index of main2
* @return
* - MTRUE indicates success
* - MFALSE indicates failure
*/
static IDepthMapPipe* createInstance(
DepthFlowType flowType,
MINT32 iSensorIdx_Main1,
MINT32 iSensorIdx_Main2);
MBOOL destroyInstance();
// destructor
virtual ~IDepthMapPipe() {};
public:
virtual MBOOL init() = 0;
virtual MBOOL uninit() = 0;
virtual MBOOL enque(android::sp<EffectRequest>& request) = 0;
virtual MVOID flush() = 0;
virtual MVOID setFlushOnStop(MBOOL flushOnStop) = 0;
};
}; // NSFeaturePipe
}; // NSCamFeature
}; // NSCam
#endif |
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:
//
// AdidasChallenge
//
// Created by <NAME> on 05/12/2017.
// Copyright © 2017 ERISCO. All rights reserved.
//
import Foundation
public class Forecast {
// MARK: - Properties
var time: Date!
var summary: String!
var icon: String!
var precipitation_probability: Double!
var precipitation_type: String!
var temperature: Double!
var temperature_high: Double!
var temperature_low: Double!
var temperature_aparent: Double!
var temperature_aparent_high: Double!
var temperature_aparent_low: Double!
var wind_speed: Double!
// MARK: - Init
init(time: Date,
summary: String,
icon: String,
precipitation_probability: Double,
precipitation_type: String,
temperature: Double,
temperature_aparent: Double,
wind_speed: Double){
self.time = time
self.summary = summary
self.icon = icon
self.precipitation_type = precipitation_type
self.precipitation_probability = precipitation_probability
self.temperature = temperature
self.temperature_aparent = temperature_aparent
self.wind_speed = wind_speed
}
convenience init(){
self.init(time: Date(), summary: "", icon: "", precipitation_probability: 0, precipitation_type: "", temperature: 0, temperature_aparent: 0, wind_speed: 0)
}
// MARK: - View Getters
var timeConverted : String {
get {
guard let time = self.time else {
return ""
}
return Date.toString(date: time, dateFormat: "dd/MM/YYYY HH:mm")
}
}
var temperatureCelsius : String{
get {
guard let _ = self.temperature else {
guard let _ = self.temperature_high else {
return ""
}
return "\(Double(self.temperature_high).toInt()!)ºC"
}
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 | //
// AdidasChallenge
//
// Created by <NAME> on 05/12/2017.
// Copyright © 2017 ERISCO. All rights reserved.
//
import Foundation
public class Forecast {
// MARK: - Properties
var time: Date!
var summary: String!
var icon: String!
var precipitation_probability: Double!
var precipitation_type: String!
var temperature: Double!
var temperature_high: Double!
var temperature_low: Double!
var temperature_aparent: Double!
var temperature_aparent_high: Double!
var temperature_aparent_low: Double!
var wind_speed: Double!
// MARK: - Init
init(time: Date,
summary: String,
icon: String,
precipitation_probability: Double,
precipitation_type: String,
temperature: Double,
temperature_aparent: Double,
wind_speed: Double){
self.time = time
self.summary = summary
self.icon = icon
self.precipitation_type = precipitation_type
self.precipitation_probability = precipitation_probability
self.temperature = temperature
self.temperature_aparent = temperature_aparent
self.wind_speed = wind_speed
}
convenience init(){
self.init(time: Date(), summary: "", icon: "", precipitation_probability: 0, precipitation_type: "", temperature: 0, temperature_aparent: 0, wind_speed: 0)
}
// MARK: - View Getters
var timeConverted : String {
get {
guard let time = self.time else {
return ""
}
return Date.toString(date: time, dateFormat: "dd/MM/YYYY HH:mm")
}
}
var temperatureCelsius : String{
get {
guard let _ = self.temperature else {
guard let _ = self.temperature_high else {
return ""
}
return "\(Double(self.temperature_high).toInt()!)ºC"
}
return "\(Double(self.temperature).toInt()!)ºC"
}
}
var apparentTemperatureCelsius : String{
get {
guard let _ = self.temperature_aparent else {
guard let _ = self.temperature_low else {
return ""
}
return "Lowest: \(Double(self.temperature_low).toInt()!)ºC"
}
return "Apparent: \(Double(self.temperature_aparent).toInt()!)ºC"
}
}
var precipitationPhrase : String{
get {
guard let type = precipitation_type, let probability = self.precipitation_probability else {
return ""
}
let perc = Double(probability * 100).rounded(toPlaces: 2)
return "Probability to \(type): \(perc)%"
}
}
var windSpeedInternational: String {
get {
guard let wind_speed = self.wind_speed else {
return ""
}
return "Wind speed: \(Double(wind_speed).rounded(toPlaces: 2))km/h"
}
}
var imageUrl: String {
get {
guard let _ = self.icon else {
return ""
}
let absoluteUrl = ReadConfig.value(keyname: ConfigKeys.ICONS_URL.rawValue)
return absoluteUrl.replacingOccurrences(of: "<<ICON_NAME>>", with: icon!)
}
}
}
|
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"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/fatih/color"
)
var (
workDir = "."
workDirBasepath = ""
)
func main() {
fmt.Print("Checking your Ginkgo Installation...")
cmd := exec.Command("ginkgo", "help")
if err := cmd.Run(); err != nil {
color.Red("ERROR")
log.Fatal("Please install ginkgo \n`go get github.com/onsi/ginkgo/ginkgo && go get github.com/onsi/gomega`")
} else {
color.Green("OK!")
}
err := os.Chdir(".")
if err != nil {
log.Fatal(err)
}
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
workDirBasepath = filepath.Base(wd)
fInfos, err := ioutil.ReadDir(workDir)
if err != nil {
log.Fatal(err)
}
suiteFound := false
fmt.Println("Generating specs")
for _, finfo := range fInfos {
if !finfo.IsDir() && validFilename(finfo.Name()) {
cmd := exec.Command("ginkgo", "generate", finfo.Name())
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
if isSuite(finfo.Name()) {
suiteFound = true
}
}
if !suiteFound {
fmt.Println("Generating suite")
cmd := exec.Command("ginkgo", "bootstrap", workDirBasepath)
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
}
func validFilename(filename string) bool {
return !strings.Contains(filename, "_test") && strings.Contains(filename, ".go")
}
func isSuite(currFile string) bool {
return strings.Contains(currFile, fmt.Sprintf("%s_suite", workDirBasepath))
}
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"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/fatih/color"
)
var (
workDir = "."
workDirBasepath = ""
)
func main() {
fmt.Print("Checking your Ginkgo Installation...")
cmd := exec.Command("ginkgo", "help")
if err := cmd.Run(); err != nil {
color.Red("ERROR")
log.Fatal("Please install ginkgo \n`go get github.com/onsi/ginkgo/ginkgo && go get github.com/onsi/gomega`")
} else {
color.Green("OK!")
}
err := os.Chdir(".")
if err != nil {
log.Fatal(err)
}
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
workDirBasepath = filepath.Base(wd)
fInfos, err := ioutil.ReadDir(workDir)
if err != nil {
log.Fatal(err)
}
suiteFound := false
fmt.Println("Generating specs")
for _, finfo := range fInfos {
if !finfo.IsDir() && validFilename(finfo.Name()) {
cmd := exec.Command("ginkgo", "generate", finfo.Name())
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
if isSuite(finfo.Name()) {
suiteFound = true
}
}
if !suiteFound {
fmt.Println("Generating suite")
cmd := exec.Command("ginkgo", "bootstrap", workDirBasepath)
err := cmd.Run()
if err != nil {
log.Println(err)
}
}
}
func validFilename(filename string) bool {
return !strings.Contains(filename, "_test") && strings.Contains(filename, ".go")
}
func isSuite(currFile string) bool {
return strings.Contains(currFile, fmt.Sprintf("%s_suite", workDirBasepath))
}
|
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 raytracer
import kotlin.math.PI
fun degreesToRadians(degrees: Double) = degrees * PI / 180.0
fun Double.clamp(min: Double, max: Double): Double = when {
this < min -> min
this > max -> max
else -> this
}
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 raytracer
import kotlin.math.PI
fun degreesToRadians(degrees: Double) = degrees * PI / 180.0
fun Double.clamp(min: Double, max: Double): Double = when {
this < min -> min
this > max -> max
else -> this
}
|
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 servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import beans.Client;
import beans.Jeu;
import beans.Panier;
/**
* Servlet implementation class ShowPanier
*/
@WebServlet("/ShowPanier")
public class ShowPanier extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowPanier() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper();
Client client = (Client) request.getSession().getAttribute("client");
String data = APIContact.getDataFromAPI("http://localhost:8080/sr03_project_server/Panier?object=Panier&client="+client.getId());
Panier[]paniers = (Panier[]) mapper.readValue(data,Panier[].class);
request.getSession().setAttribute("panier", paniers);
if(paniers.length == 0)
request.getSession().setAttribute("total", 0);
if(paniers.length >=1){
double total =0 ;
for (int i = 0; i < paniers.length; i++) {
total = total + paniers[i].getJeu().getPrix();
}
request.getSession().setAttribute("total", total);
}
data = APIContact.getDataFromAPI("http://localhost:8080/sr03_project_server/Panier?object=Achats&client="+client.getId());
paniers = (Panier[]) mapper.readValue(data,Panier[].class);
request.getSession().setAttribute("achats", paniers);
request.getRequestDi
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 servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import beans.Client;
import beans.Jeu;
import beans.Panier;
/**
* Servlet implementation class ShowPanier
*/
@WebServlet("/ShowPanier")
public class ShowPanier extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowPanier() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper();
Client client = (Client) request.getSession().getAttribute("client");
String data = APIContact.getDataFromAPI("http://localhost:8080/sr03_project_server/Panier?object=Panier&client="+client.getId());
Panier[]paniers = (Panier[]) mapper.readValue(data,Panier[].class);
request.getSession().setAttribute("panier", paniers);
if(paniers.length == 0)
request.getSession().setAttribute("total", 0);
if(paniers.length >=1){
double total =0 ;
for (int i = 0; i < paniers.length; i++) {
total = total + paniers[i].getJeu().getPrix();
}
request.getSession().setAttribute("total", total);
}
data = APIContact.getDataFromAPI("http://localhost:8080/sr03_project_server/Panier?object=Achats&client="+client.getId());
paniers = (Panier[]) mapper.readValue(data,Panier[].class);
request.getSession().setAttribute("achats", paniers);
request.getRequestDispatcher("PanierView.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
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.androiddevs.githubjobsclient.repository
import com.androiddevs.githubjobsclient.api.RetrofitInstance
import com.androiddevs.githubjobsclient.db.JobsDatabase
import com.androiddevs.githubjobsclient.models.JobsItem
class NewsRepository(
val db: JobsDatabase
) {
suspend fun getBreakingNews() =
RetrofitInstance.api.getJobs()
suspend fun searchNews(searchQuery: String, pageNumber: Int) =
RetrofitInstance.api.searchJobs(searchQuery, pageNumber)
suspend fun getJob(id: String) =
RetrofitInstance.api.getJob(id)
suspend fun upsert(job: JobsItem) = db.getArticleDao().upsert(job)
fun getSaveJobs() = db.getArticleDao().getAllArticles()
suspend fun deleteArticle(job: JobsItem) = db.getArticleDao().deleteArticle(job)
}
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.androiddevs.githubjobsclient.repository
import com.androiddevs.githubjobsclient.api.RetrofitInstance
import com.androiddevs.githubjobsclient.db.JobsDatabase
import com.androiddevs.githubjobsclient.models.JobsItem
class NewsRepository(
val db: JobsDatabase
) {
suspend fun getBreakingNews() =
RetrofitInstance.api.getJobs()
suspend fun searchNews(searchQuery: String, pageNumber: Int) =
RetrofitInstance.api.searchJobs(searchQuery, pageNumber)
suspend fun getJob(id: String) =
RetrofitInstance.api.getJob(id)
suspend fun upsert(job: JobsItem) = db.getArticleDao().upsert(job)
fun getSaveJobs() = db.getArticleDao().getAllArticles()
suspend fun deleteArticle(job: JobsItem) = db.getArticleDao().deleteArticle(job)
} |
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:
#ifndef CAMERA_HPP
#define CAMERA_HPP
#include <array>
#include "GeomUtils.h"
class Frustum
{
public:
Frustum(const float4x4 mvp);
bool isContainedWithin(const float4& point) const;
bool isContainedWithin(const float3& point) const;
Intersection isContainedWithin(const AABB& aabb) const;
private:
Plane mNearPlane;
Plane mFarPlane;
Plane mLeftPlane;
Plane mRightPLane;
Plane mTopPlane;
Plane mBottomPlane;
};
enum class CameraMode
{
InfinitePerspective = 0,
Perspective,
Orthographic
};
class Camera
{
public:
Camera(const float3& position,
const float3& direction,
const float aspect,
float nearPlaneDistance = 0.1f,
float farPlaneDistance = 10.0f,
float fieldOfView = 90.0f,
const CameraMode mode = CameraMode::InfinitePerspective)
: mMode(mode),
mPosition{ position },
mDirection{ direction },
mUp{ 0.0f, -1.0f, 0.0f },
mAspect{ aspect },
mNearPlaneDistance{nearPlaneDistance},
mFarPlaneDistance{farPlaneDistance},
mFieldOfView{fieldOfView} {}
void moveForward(const float distance);
void moveBackward(const float distance);
void moveLeft(const float distance);
void moveRight(const float distance);
void moveUp(const float distance);
void moveDown(const float distance);
void rotatePitch(const float);
void rotateYaw(const float);
void rotateWorldUp(const float);
void setMode(const CameraMode mode)
{
mMode = mode;
}
CameraMode getMode() const
{
return mMode;
}
void setOrthographicSize(const float2 size)
{ mOrthographicSize = size; }
const float2& getOrthographicSize() const
{
return mOrthographicSize;
}
const float3& getPosition() const
{ return mPosition; }
void setPosition(const float3& pos)
{ mPosition = pos; }
const float3& getDirect
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 | #ifndef CAMERA_HPP
#define CAMERA_HPP
#include <array>
#include "GeomUtils.h"
class Frustum
{
public:
Frustum(const float4x4 mvp);
bool isContainedWithin(const float4& point) const;
bool isContainedWithin(const float3& point) const;
Intersection isContainedWithin(const AABB& aabb) const;
private:
Plane mNearPlane;
Plane mFarPlane;
Plane mLeftPlane;
Plane mRightPLane;
Plane mTopPlane;
Plane mBottomPlane;
};
enum class CameraMode
{
InfinitePerspective = 0,
Perspective,
Orthographic
};
class Camera
{
public:
Camera(const float3& position,
const float3& direction,
const float aspect,
float nearPlaneDistance = 0.1f,
float farPlaneDistance = 10.0f,
float fieldOfView = 90.0f,
const CameraMode mode = CameraMode::InfinitePerspective)
: mMode(mode),
mPosition{ position },
mDirection{ direction },
mUp{ 0.0f, -1.0f, 0.0f },
mAspect{ aspect },
mNearPlaneDistance{nearPlaneDistance},
mFarPlaneDistance{farPlaneDistance},
mFieldOfView{fieldOfView} {}
void moveForward(const float distance);
void moveBackward(const float distance);
void moveLeft(const float distance);
void moveRight(const float distance);
void moveUp(const float distance);
void moveDown(const float distance);
void rotatePitch(const float);
void rotateYaw(const float);
void rotateWorldUp(const float);
void setMode(const CameraMode mode)
{
mMode = mode;
}
CameraMode getMode() const
{
return mMode;
}
void setOrthographicSize(const float2 size)
{ mOrthographicSize = size; }
const float2& getOrthographicSize() const
{
return mOrthographicSize;
}
const float3& getPosition() const
{ return mPosition; }
void setPosition(const float3& pos)
{ mPosition = pos; }
const float3& getDirection() const
{ return mDirection; }
void setDirection(const float3& dir)
{ mDirection = dir; }
void setUp(const float3& up)
{ mUp = up; }
const float3 getUp() const
{ return mUp; }
// Get the vector perpendicular to the direction vector (rotated 90 degrees clockwise)
float3 getRight() const
{ return glm::cross(glm::normalize(mDirection), mUp); }
void setNearPlane(const float nearDistance)
{ mNearPlaneDistance = nearDistance; }
void setFarPlane(const float farDistance)
{ mFarPlaneDistance = farDistance; }
void setFOVDegrees(const float fov)
{ mFieldOfView = fov; }
void setAspect(const float aspect)
{ mAspect = aspect; }
float getAspect() const
{ return mAspect; }
float4x4 getViewMatrix() const;
float4x4 getProjectionMatrix() const;
float4x4 getProjectionMatrixOverride(const CameraMode) const;
float getNearPlane() const
{ return mNearPlaneDistance; }
float getFarPlane() const
{ return mFarPlaneDistance; }
float getFOV() const
{ return mFieldOfView; }
Frustum getFrustum() const;
AABB getFrustumAABB() const;
private:
CameraMode mMode;
float2 mOrthographicSize;
float3 mPosition;
float3 mDirection;
float3 mUp;
float mAspect;
float mNearPlaneDistance;
float mFarPlaneDistance;
float mFieldOfView;
};
#endif
|
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 toc2
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
println("job: I'm running finally")
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
/**
* Closing resources with finally
*
취소가 가능한 suspending function 의 경우, CancellationException 이 발생되므로
일반적인 방법을 통해 처리가 가능합니다. 예를들어, 코틀린의 `try {...} finally {...}` 표현은
코루틴이 취소될 때 정상적으로 실행할 수 있습니다.
join() 및 cancelAndJoin() 함수 모두 작업이 완료될 때 까지 기다리기 때문에,
위의 예시 실행 결과는 아래와 같이 출력됩니다.
------------------------------------
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
main: Now I can quit.
------------------------------------
참조) 위 코드에서 만약 cancel() 만 호출할 경우, 아래와 같이 finally 블록이 나중에 실행되는 것을
확인할 수 있습니다. cancel 이 후, 해당 코루틴은 메인 코루틴에서 join 상태가 해제되어 별개로 동작이 실행되기 때문에,
실행 순서가 메인코루틴이 먼저 실행되는 것을 확인할 수 있습니다.
(finally 구문 역시 코루틴에 포함되는 코드블록으로 이해하면 될 거 같습니다.)
따라서, 코루틴이 취소될 경우 자원해제나 추가 처리가 필요한 상황이라면 cancelAndJoin 을 사용하는 것을 추천합니다.
(cancel 과 cancelAndJoin 이 함께 공존할 경우, 생각보다 혼선이 있을 것으로 조심스레 예측합니다.)
이 부분은 다음 예시와 함께 확인하면 더욱 좋습니다.
------------------------------------
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
> main: Now I can quit.
> job: I'm running finally
------------------------------------
*/
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 | 5 | package toc2
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
println("job: I'm running finally")
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
/**
* Closing resources with finally
*
취소가 가능한 suspending function 의 경우, CancellationException 이 발생되므로
일반적인 방법을 통해 처리가 가능합니다. 예를들어, 코틀린의 `try {...} finally {...}` 표현은
코루틴이 취소될 때 정상적으로 실행할 수 있습니다.
join() 및 cancelAndJoin() 함수 모두 작업이 완료될 때 까지 기다리기 때문에,
위의 예시 실행 결과는 아래와 같이 출력됩니다.
------------------------------------
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
main: Now I can quit.
------------------------------------
참조) 위 코드에서 만약 cancel() 만 호출할 경우, 아래와 같이 finally 블록이 나중에 실행되는 것을
확인할 수 있습니다. cancel 이 후, 해당 코루틴은 메인 코루틴에서 join 상태가 해제되어 별개로 동작이 실행되기 때문에,
실행 순서가 메인코루틴이 먼저 실행되는 것을 확인할 수 있습니다.
(finally 구문 역시 코루틴에 포함되는 코드블록으로 이해하면 될 거 같습니다.)
따라서, 코루틴이 취소될 경우 자원해제나 추가 처리가 필요한 상황이라면 cancelAndJoin 을 사용하는 것을 추천합니다.
(cancel 과 cancelAndJoin 이 함께 공존할 경우, 생각보다 혼선이 있을 것으로 조심스레 예측합니다.)
이 부분은 다음 예시와 함께 확인하면 더욱 좋습니다.
------------------------------------
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
> main: Now I can quit.
> job: I'm running finally
------------------------------------
*/ |
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 Node;
using UnityEngine;
using UnityEngine.UI;
namespace Events
{
public class Reviewprefab : MonoBehaviour
{
public Text Headline;
public Text Effect;
public Text Content;
public void ChangeText(string headline,string preInsert,string effect)
{
Headline.text = headline;
Content.text = preInsert;
Effect.text = effect;
}
public void ChangeText(string headline,string preInsert,NodeState.FieldTypeEnum fieldTypeEnum, string afterInsert,string effect)
{
//Headline.text = headline;
Content.text = preInsert + " " + GetInsert(fieldTypeEnum) + " " + afterInsert;
Effect.text = effect;
}
public static string GetInsert(NodeState.FieldTypeEnum fieldType)
{
switch (fieldType)
{
case NodeState.FieldTypeEnum.Apple:
return "appel";
case NodeState.FieldTypeEnum.Blackberries:
return "braam";
case NodeState.FieldTypeEnum.Carrot:
return "wortel";
case NodeState.FieldTypeEnum.Corn:
return "mais";
case NodeState.FieldTypeEnum.Grapes:
return "druif";
case NodeState.FieldTypeEnum.Tomato:
return "tomaat";
}
return "";
}
}
}
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 Node;
using UnityEngine;
using UnityEngine.UI;
namespace Events
{
public class Reviewprefab : MonoBehaviour
{
public Text Headline;
public Text Effect;
public Text Content;
public void ChangeText(string headline,string preInsert,string effect)
{
Headline.text = headline;
Content.text = preInsert;
Effect.text = effect;
}
public void ChangeText(string headline,string preInsert,NodeState.FieldTypeEnum fieldTypeEnum, string afterInsert,string effect)
{
//Headline.text = headline;
Content.text = preInsert + " " + GetInsert(fieldTypeEnum) + " " + afterInsert;
Effect.text = effect;
}
public static string GetInsert(NodeState.FieldTypeEnum fieldType)
{
switch (fieldType)
{
case NodeState.FieldTypeEnum.Apple:
return "appel";
case NodeState.FieldTypeEnum.Blackberries:
return "braam";
case NodeState.FieldTypeEnum.Carrot:
return "wortel";
case NodeState.FieldTypeEnum.Corn:
return "mais";
case NodeState.FieldTypeEnum.Grapes:
return "druif";
case NodeState.FieldTypeEnum.Tomato:
return "tomaat";
}
return "";
}
}
}
|
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:
/*********************************************************************************************/
/* Problem: Misere Nim (HR) ********/
/*********************************************************************************************/
/*
--Problem statement:
Two people are playing game of Misère Nim. The basic rules for this game are as follows:
a. The game starts with 'n' piles of stones indexed from 0 to 'n-1'. Each pile 'i' (where
0<=i<n) has 'si' stones.
b. The players move in alternating turns. During each move, the current player must remove
one or more stones from a single pile.
c. The player who removes the last stone loses the game.
Given the value of 'n' and the number of stones in each pile, determine whether the person who
wins the game is the first or second person to move. If the first player to move wins, print
'First' on a new line; otherwise, print 'Second'. Assume both players move optimally.
> Example:
a. s = [1,1,1]:
In this case, player 1 picks a pile, player 2 picks a pile and player 1 has to choose the
last pile. Player 2 wins so return 'Second'.
b. s = [1,2,2]:
There is no permutation of optimal moves where player 2 wins. For example, player 1 chooses
the first pile. If player 2 chooses 1 from another pile, player 1 will choose the pile with
2 left. If player 2 chooses a pile of 2, player 1 chooses 1 from the remaining pile leaving
the last stone for player 2. Return 'First'.
--Inputs:
- int s[n]: the number of stones in each pile.
--Output:
- string: either 'First' or 'Second'.
--Reasoning:
More about the Nim game: https://en.wikipedia.org/wiki/Nim#Mathematical_theory
(1) In case we have a single pile, if there is more than one stone, then the first player will always win by leaving the last stone for the second player.
(2) In case the sum of all the stones is equal to the number of piles, that means that every pile has only one sto
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 | /*********************************************************************************************/
/* Problem: Misere Nim (HR) ********/
/*********************************************************************************************/
/*
--Problem statement:
Two people are playing game of Misère Nim. The basic rules for this game are as follows:
a. The game starts with 'n' piles of stones indexed from 0 to 'n-1'. Each pile 'i' (where
0<=i<n) has 'si' stones.
b. The players move in alternating turns. During each move, the current player must remove
one or more stones from a single pile.
c. The player who removes the last stone loses the game.
Given the value of 'n' and the number of stones in each pile, determine whether the person who
wins the game is the first or second person to move. If the first player to move wins, print
'First' on a new line; otherwise, print 'Second'. Assume both players move optimally.
> Example:
a. s = [1,1,1]:
In this case, player 1 picks a pile, player 2 picks a pile and player 1 has to choose the
last pile. Player 2 wins so return 'Second'.
b. s = [1,2,2]:
There is no permutation of optimal moves where player 2 wins. For example, player 1 chooses
the first pile. If player 2 chooses 1 from another pile, player 1 will choose the pile with
2 left. If player 2 chooses a pile of 2, player 1 chooses 1 from the remaining pile leaving
the last stone for player 2. Return 'First'.
--Inputs:
- int s[n]: the number of stones in each pile.
--Output:
- string: either 'First' or 'Second'.
--Reasoning:
More about the Nim game: https://en.wikipedia.org/wiki/Nim#Mathematical_theory
(1) In case we have a single pile, if there is more than one stone, then the first player will always win by leaving the last stone for the second player.
(2) In case the sum of all the stones is equal to the number of piles, that means that every pile has only one stone. If this is the case, for an even number of piles the first player will win, since the last pile containing exactly one stone will be left to the second player.
(3) For all remaining cases, the XOR value between all the piles determines the winner. If the XOR value is 0, that means that the piles can be paired and the second player will be the winner.
--Constraints:
1<=T<=100; 1<=n<=100; 1<=s[i]<=10^9
--Time complexity: O(N), where N is the length of the input array.
--Space complexity: O(1), no input-dependent space is allocated.
*/
#include <iostream>
#include <string>
#include <vector>
std::string misereNim(std::vector<int> s)
{
int total_sum{0}, nim_sum{0};
for (const auto &pile : s)
{
total_sum += pile;
nim_sum ^= pile;
}
bool all_piles_have_one_stone = (total_sum == s.size());
if (all_piles_have_one_stone)
{
if (s.size() % 2 == 0)
{
return "First";
}
return "Second";
}
else
{
if (nim_sum == 0)
{
return "Second";
}
return "First";
}
}
int main()
{
std::vector<int> vec{1, 1, 1};
std::cout << "The winner is: " << misereNim(vec) << "\n"; // Expected: Second
vec = {1, 2, 2};
std::cout << "The winner is: " << misereNim(vec) << "\n"; // Expected: First
return 0;
} |
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:
#ifndef __MOTOR_H
#define __MOTOR_H
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "delay.h"
#include "sg90.h"
#include "blue.h"
#include "hcsr04.h"
#include "red.h"
void TIM4_PWM_Init(void);
void Motor_Init(void);
void CarGo(int);
void CarStop(void);
void CarBack(int);
void CarLeft(int); //×óת
void CarRight(int); //ÓÒת
void CarForwardLeft(int);
void CarForwardRight(int);
void CarBackLeft(int);
void CarBackRight(int);
void CarTest(void);
#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>"
| c | 1 | #ifndef __MOTOR_H
#define __MOTOR_H
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "delay.h"
#include "sg90.h"
#include "blue.h"
#include "hcsr04.h"
#include "red.h"
void TIM4_PWM_Init(void);
void Motor_Init(void);
void CarGo(int);
void CarStop(void);
void CarBack(int);
void CarLeft(int); //×óת
void CarRight(int); //ÓÒת
void CarForwardLeft(int);
void CarForwardRight(int);
void CarBackLeft(int);
void CarBackRight(int);
void CarTest(void);
#endif
|
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 interface Device {
id: string,
title: string,
headers: Label[],
rows: string[][]
}
export interface Label {
label: string,
full_label: string
}
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 | export interface Device {
id: string,
title: string,
headers: Label[],
rows: string[][]
}
export interface Label {
label: string,
full_label: 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:
#Start thetvdb client
$tvdb = $config['tvdb'] && $config['tvdb']['api_key'] ? TvdbParty::Search.new($config['tvdb']['api_key']) : 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>"
| ruby | 1 | #Start thetvdb client
$tvdb = $config['tvdb'] && $config['tvdb']['api_key'] ? TvdbParty::Search.new($config['tvdb']['api_key']) : nil |
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:
/**
* Write a description of class BootTest here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class BoolTest
{
private int one;
public BoolTest(int newOne)
{
one = newOne;
}
public int getOne()
{
return one;
}
public boolean isGreater1(BoolTest other)
{
System.out.println(one > other.one);
return one > other.one;
}
public boolean isGreater2(BoolTest other)
{
System.out.println( one > other.getOne());
return one > other.getOne();
}
public boolean isGreater3(BoolTest other)
{
System.out.println(getOne() > other.one);
return getOne() > other.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>"
| java | 3 |
/**
* Write a description of class BootTest here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class BoolTest
{
private int one;
public BoolTest(int newOne)
{
one = newOne;
}
public int getOne()
{
return one;
}
public boolean isGreater1(BoolTest other)
{
System.out.println(one > other.one);
return one > other.one;
}
public boolean isGreater2(BoolTest other)
{
System.out.println( one > other.getOne());
return one > other.getOne();
}
public boolean isGreater3(BoolTest other)
{
System.out.println(getOne() > other.one);
return getOne() > other.one;
}
} |
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
###############################################################################
#
# This file generated by Jython installer
# Created on XXX by ian
"/Users/ian/javadev/lib/jython-2.1/jython" "/Users/ian/javadev/lib/jython-2.1/Tools/jythonc/jythonc.py" "$@"
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 | #!/bin/sh
###############################################################################
#
# This file generated by Jython installer
# Created on XXX by ian
"/Users/ian/javadev/lib/jython-2.1/jython" "/Users/ian/javadev/lib/jython-2.1/Tools/jythonc/jythonc.py" "$@"
|
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:
CREATE OR REPLACE VIEW dga_employment_data_get_list(
dga_employment_data_id,
dga_employment_data_report_date,
dga_employment_data_prepared_by,
dga_employment_data_quarter,
dga_employment_data_year,
dga_employment_data_phone,
dga_employment_data_company_id,
dga_employment_data_company_name,
dga_employment_data_company_address,
dga_employment_data_company_city,
dga_employment_data_company_state_code,
dga_employment_data_company_phone,
dga_employment_data_company_website,
dga_employment_data_production_id,
dga_employment_data_production_title,
dga_employment_data_director_name,
dga_employment_data_director_first_number,
dga_employment_data_director_gender,
dga_employment_data_director_caucasion,
dga_employment_data_director_afro_american,
dga_employment_data_director_latino,
dga_employment_data_director_asian,
dga_employment_data_director_native,
dga_employment_data_director_unknown,
dga_employment_data_unit_production_name,
dga_employment_data_unit_production_gender,
dga_employment_data_unit_production_caucasion,
dga_employment_data_unit_production_afro_american,
dga_employment_data_unit_production_latino,
dga_employment_data_unit_production_asian,
dga_employment_data_unit_production_native,
dga_employment_data_unit_production_unknown,
dga_employment_data_first_assistant_name,
dga_employment_data_first_assistant_gender,
dga_employment_data_first_assistant_caucasion,
dga_employment_data_first_assistant_afro_american,
dga_employment_data_first_assistant_latino,
dga_employment_data_first_assistant_asian,
dga_employment_data_first_assistant_native,
dga_employment_data_first_assistant_unknown,
dga_employment_data_second_assistant_name,
dga_employment_data_second_assistant_gender,
dga_employment_data_second_assistant_caucasion,
dga_employment_data_second_assistant_afro_american,
dga_employment_dat
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 | 2 | CREATE OR REPLACE VIEW dga_employment_data_get_list(
dga_employment_data_id,
dga_employment_data_report_date,
dga_employment_data_prepared_by,
dga_employment_data_quarter,
dga_employment_data_year,
dga_employment_data_phone,
dga_employment_data_company_id,
dga_employment_data_company_name,
dga_employment_data_company_address,
dga_employment_data_company_city,
dga_employment_data_company_state_code,
dga_employment_data_company_phone,
dga_employment_data_company_website,
dga_employment_data_production_id,
dga_employment_data_production_title,
dga_employment_data_director_name,
dga_employment_data_director_first_number,
dga_employment_data_director_gender,
dga_employment_data_director_caucasion,
dga_employment_data_director_afro_american,
dga_employment_data_director_latino,
dga_employment_data_director_asian,
dga_employment_data_director_native,
dga_employment_data_director_unknown,
dga_employment_data_unit_production_name,
dga_employment_data_unit_production_gender,
dga_employment_data_unit_production_caucasion,
dga_employment_data_unit_production_afro_american,
dga_employment_data_unit_production_latino,
dga_employment_data_unit_production_asian,
dga_employment_data_unit_production_native,
dga_employment_data_unit_production_unknown,
dga_employment_data_first_assistant_name,
dga_employment_data_first_assistant_gender,
dga_employment_data_first_assistant_caucasion,
dga_employment_data_first_assistant_afro_american,
dga_employment_data_first_assistant_latino,
dga_employment_data_first_assistant_asian,
dga_employment_data_first_assistant_native,
dga_employment_data_first_assistant_unknown,
dga_employment_data_second_assistant_name,
dga_employment_data_second_assistant_gender,
dga_employment_data_second_assistant_caucasion,
dga_employment_data_second_assistant_afro_american,
dga_employment_data_second_assistant_latino,
dga_employment_data_second_assistant_asian,
dga_employment_data_second_assistant_native,
dga_employment_data_second_assistant_unknown,
dga_employment_data_technical_coordinator_name,
dga_employment_data_technical_coordinator_gender,
dga_employment_data_technical_coordinator_caucasion,
dga_employment_data_technical_coordinator_afro_american,
dga_employment_data_technical_coordinator_latino,
dga_employment_data_technical_coordinator_asian,
dga_employment_data_technical_coordinator_native,
dga_employment_data_technical_coordinator_unknown,
dga_employment_data_associate_director_name,
dga_employment_data_associate_director_gender,
dga_employment_data_associate_director_caucasion,
dga_employment_data_associate_director_afro_american,
dga_employment_data_associate_director_latino,
dga_employment_data_associate_director_asian,
dga_employment_data_associate_director_native,
dga_employment_data_associate_director_unknown,
dga_employment_data_stage_manager_name,
dga_employment_data_stage_manager_gender,
dga_employment_data_stage_manager_caucasion,
dga_employment_data_stage_manager_afro_american,
dga_employment_data_stage_manager_latino,
dga_employment_data_stage_manager_asian,
dga_employment_data_stage_manager_native,
dga_employment_data_stage_manager_unknown,
dga_employment_data_created,
dga_employment_data_created_by,
dga_employment_data_updated,
dga_employment_data_updated_by,
dga_employment_data_status
) AS
SELECT dga_employment_data.id AS dga_employment_data_id,
DATE_FORMAT(dga_employment_data.report_date,'%m/%d/%Y') AS dga_employment_data_report_date,
dga_employment_data.prepared_by AS dga_employment_data_prepared_by,
dga_employment_data.quarter AS dga_employment_data_quarter,
dga_employment_data.year AS dga_employment_data_year,
dga_employment_data.phone AS dga_employment_data_phone,
dga_employment_data.company_id AS dga_employment_data_company_id,
company.name AS dga_employment_data_company_name,
company.address AS dga_employment_data_company_address,
company.city AS dga_employment_data_company_city,
company.state_code AS dga_employment_data_company_state_code,
company.phone AS dga_employment_data_company_phone,
company.website AS dga_employment_data_company_website,
dga_employment_data.production_id AS dga_employment_data_production_id,
production.title AS dga_employment_data_production_title,
dga_employment_data.director_name AS dga_employment_data_director_name,
dga_employment_data.director_first_number AS dga_employment_data_director_first_number,
dga_employment_data.director_gender AS dga_employment_data_director_gender,
dga_employment_data.director_caucasion AS dga_employment_data_director_caucasion,
dga_employment_data.director_afro_american AS dga_employment_data_director_afro_american,
dga_employment_data.director_latino AS dga_employment_data_director_latino,
dga_employment_data.director_asian AS dga_employment_data_director_asian,
dga_employment_data.director_native AS dga_employment_data_director_native,
dga_employment_data.director_unknown AS dga_employment_data_director_unknown,
dga_employment_data.unit_production_name AS dga_employment_data_unit_production_name,
dga_employment_data.unit_production_gender AS dga_employment_data_unit_production_gender,
dga_employment_data.unit_production_caucasion AS dga_employment_data_unit_production_caucasion,
dga_employment_data.unit_production_afro_american AS dga_employment_data_unit_production_afro_american,
dga_employment_data.unit_production_latino AS dga_employment_data_unit_production_latino,
dga_employment_data.unit_production_asian AS dga_employment_data_unit_production_asian,
dga_employment_data.unit_production_native AS dga_employment_data_unit_production_native,
dga_employment_data.unit_production_unknown AS dga_employment_data_unit_production_unknown,
dga_employment_data.first_assistant_name AS dga_employment_data_first_assistant_name,
dga_employment_data.first_assistant_gender AS dga_employment_data_first_assistant_gender,
dga_employment_data.first_assistant_caucasion AS dga_employment_data_first_assistant_caucasion,
dga_employment_data.first_assistant_afro_american AS dga_employment_data_first_assistant_afro_american,
dga_employment_data.first_assistant_latino AS dga_employment_data_first_assistant_latino,
dga_employment_data.first_assistant_asian AS dga_employment_data_first_assistant_asian,
dga_employment_data.first_assistant_native AS dga_employment_data_first_assistant_native,
dga_employment_data.first_assistant_unknown AS dga_employment_data_first_assistant_unknown,
dga_employment_data.second_assistant_name AS dga_employment_data_second_assistant_name,
dga_employment_data.second_assistant_gender AS dga_employment_data_second_assistant_gender,
dga_employment_data.second_assistant_caucasion AS dga_employment_data_second_assistant_caucasion,
dga_employment_data.second_assistant_afro_american AS dga_employment_data_second_assistant_afro_american,
dga_employment_data.second_assistant_latino AS dga_employment_data_second_assistant_latino,
dga_employment_data.second_assistant_asian AS dga_employment_data_second_assistant_asian,
dga_employment_data.second_assistant_native AS dga_employment_data_second_assistant_native,
dga_employment_data.second_assistant_unknown AS dga_employment_data_second_assistant_unknown,
dga_employment_data.technical_coordinator_name AS dga_employment_data_technical_coordinator_name,
dga_employment_data.technical_coordinator_gender AS dga_employment_data_technical_coordinator_gender,
dga_employment_data.technical_coordinator_caucasion AS dga_employment_data_technical_coordinator_caucasion,
dga_employment_data.technical_coordinator_afro_american AS dga_employment_data_technical_coordinator_afro_american,
dga_employment_data.technical_coordinator_latino AS dga_employment_data_technical_coordinator_latino,
dga_employment_data.technical_coordinator_asian AS dga_employment_data_technical_coordinator_asian,
dga_employment_data.technical_coordinator_native AS dga_employment_data_technical_coordinator_native,
dga_employment_data.technical_coordinator_unknown AS dga_employment_data_technical_coordinator_unknown,
dga_employment_data.associate_director_name AS dga_employment_data_associate_director_name,
dga_employment_data.associate_director_gender AS dga_employment_data_associate_director_gender,
dga_employment_data.associate_director_caucasion AS dga_employment_data_associate_director_caucasion,
dga_employment_data.associate_director_afro_american AS dga_employment_data_associate_director_afro_american,
dga_employment_data.associate_director_latino AS dga_employment_data_associate_director_latino,
dga_employment_data.associate_director_asian AS dga_employment_data_associate_director_asian,
dga_employment_data.associate_director_native AS dga_employment_data_associate_director_native,
dga_employment_data.associate_director_unknown AS dga_employment_data_associate_director_unknown,
dga_employment_data.stage_manager_name AS dga_employment_data_stage_manager_name,
dga_employment_data.stage_manager_gender AS dga_employment_data_stage_manager_gender,
dga_employment_data.stage_manager_caucasion AS dga_employment_data_stage_manager_caucasion,
dga_employment_data.stage_manager_afro_american AS dga_employment_data_stage_manager_afro_american,
dga_employment_data.stage_manager_latino AS dga_employment_data_stage_manager_latino,
dga_employment_data.stage_manager_asian AS dga_employment_data_stage_manager_asian,
dga_employment_data.stage_manager_native AS dga_employment_data_stage_manager_native,
dga_employment_data.stage_manager_unknown AS dga_employment_data_stage_manager_unknown,
DATE_FORMAT(dga_employment_data.created,'%m/%d/%Y %H:%i:%S') AS dga_employment_data_created,
dga_employment_data.created_by AS dga_employment_data_created_by,
DATE_FORMAT(dga_employment_data.updated,'%m/%d/%Y %H:%i:%S') AS dga_employment_data_updated,
dga_employment_data.updated_by AS dga_employment_data_updated_by,
dga_employment_data.status AS dga_employment_data_status
FROM dga_employment_data AS dga_employment_data INNER JOIN company AS company ON company.id = dga_employment_data.company_id
INNER JOIN production AS production ON production.id = dga_employment_data.production_id; |
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 invoice i
JOIN invoice_line il ON il.invoice_id = i.invoice_id
WHERE il.unit_price > 0.99
SELECT i.invoice_date, c.first_name, c.last_name, i.total
FROM invoice i
JOIN customer c ON i.customer_id = c.customer_id;
SELECT c.first_name, c.last_name, e.first_name, e.last_name
FROM customer c
JOIN employee e ON c.support_rep_id = e.employee_id;
SELECT al.title, ar.name
FROM album al
JOIN artist ar ON al.artist_id = ar.artist_id;
SELECT pt.track_id
FROM playlist_track pt
JOIN playlist p ON p.playlist_id = pt.playlist_id
WHERE p.name = 'Music';
SELECT t.name
FROM track t
JOIN playlist_track pt ON pt.track_id = t.track_id
WHERE pt.playlist_id = 5;
SELECT t.name, p.name
FROM track t
JOIN playlist_track pt ON t.track_id = pt.track_id
JOIN playlist p ON pt.playlist_id = p.playlist_id;
SELECT t.name, a.title
FROM track t
JOIN album a ON t.album_id = a.album_id
JOIN genre g ON g.genre_id = t.gengre_id
WHERE g.name = 'Alternative & Punk';
SELECT *
FROM invoice
WHERE invoice_id IN (SELECT invoice_id
FROM invoice_line
WHERE unit_price > 0.99);
SELECT *
FROM playlist_track
WHERE playlist_id IN ( SELECT playlist_id
FROM playlist
WHERE name = 'Music');
SELECT name
FROM track
WHERE track_id IN ( SELECT track_id
FROM playlist_track
WHERE playlist_id = 5);
SELECT *
FROM track
WHERE genre_id IN ( SELECT genre_id
FROM genre
WHERE name = 'Comedy');
SELECT *
FROM track
WHERE album_id IN ( SELECT album_id
FROM album
WHERE title = 'Fireball');
SELECT *
FROM track
WHERE album_id IN (
SELECT album_id
FROM album
WHERE artist_id IN (
SELect artist_id
FROM artist
WHERE name ='Queen'
)
);
UPDATE customer
SET fax = NULL
WHERE fax IS NOT NULL;
UPDATE customer
SET company = 'Self'
WHERE company IS NULL;
UPDATE customer
SET last_name = 'Thompson'
WHERE first_name = 'Julia' AND last_name = 'Barnett';
UPDATE customer
SET support_rep_id = 4
WHERE email = '<EMAIL>';
UPDATE track
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>"
| sql | 4 | SELECT *
FROM invoice i
JOIN invoice_line il ON il.invoice_id = i.invoice_id
WHERE il.unit_price > 0.99
SELECT i.invoice_date, c.first_name, c.last_name, i.total
FROM invoice i
JOIN customer c ON i.customer_id = c.customer_id;
SELECT c.first_name, c.last_name, e.first_name, e.last_name
FROM customer c
JOIN employee e ON c.support_rep_id = e.employee_id;
SELECT al.title, ar.name
FROM album al
JOIN artist ar ON al.artist_id = ar.artist_id;
SELECT pt.track_id
FROM playlist_track pt
JOIN playlist p ON p.playlist_id = pt.playlist_id
WHERE p.name = 'Music';
SELECT t.name
FROM track t
JOIN playlist_track pt ON pt.track_id = t.track_id
WHERE pt.playlist_id = 5;
SELECT t.name, p.name
FROM track t
JOIN playlist_track pt ON t.track_id = pt.track_id
JOIN playlist p ON pt.playlist_id = p.playlist_id;
SELECT t.name, a.title
FROM track t
JOIN album a ON t.album_id = a.album_id
JOIN genre g ON g.genre_id = t.gengre_id
WHERE g.name = 'Alternative & Punk';
SELECT *
FROM invoice
WHERE invoice_id IN (SELECT invoice_id
FROM invoice_line
WHERE unit_price > 0.99);
SELECT *
FROM playlist_track
WHERE playlist_id IN ( SELECT playlist_id
FROM playlist
WHERE name = 'Music');
SELECT name
FROM track
WHERE track_id IN ( SELECT track_id
FROM playlist_track
WHERE playlist_id = 5);
SELECT *
FROM track
WHERE genre_id IN ( SELECT genre_id
FROM genre
WHERE name = 'Comedy');
SELECT *
FROM track
WHERE album_id IN ( SELECT album_id
FROM album
WHERE title = 'Fireball');
SELECT *
FROM track
WHERE album_id IN (
SELECT album_id
FROM album
WHERE artist_id IN (
SELect artist_id
FROM artist
WHERE name ='Queen'
)
);
UPDATE customer
SET fax = NULL
WHERE fax IS NOT NULL;
UPDATE customer
SET company = 'Self'
WHERE company IS NULL;
UPDATE customer
SET last_name = 'Thompson'
WHERE first_name = 'Julia' AND last_name = 'Barnett';
UPDATE customer
SET support_rep_id = 4
WHERE email = '<EMAIL>';
UPDATE track
SET composer = 'the darkness around us'
WHERE genre_id = ( SELECT genre_id
FROM genre
WHERE name = 'Metal')
AND composer IS NULL;
SELECT COUNT(*), g.name
FROM track
JOIN genre g ON t.genre_id = g.genre_id
GROUP BY g.name;
SELECT COUNT(*), g.name
FROM track t
JOIN genre g ON g.genre_id = t.genre_id
WHERE g.name = 'pop' OR g.name = 'Rock'
GROUP BY g.name;
SELECT ar.name, COUNT(*)
FROM album al
JOIN artist ar ON ar.artist_id = al.artist_id
GROUP BY ar.name;
SELECT DISTINCT composer
FROM track;
SELECT DISTINCT billing_postal_code
FROM invoice;
SELECT DISTINCT company
FROM customer;
DELETE
FROM practice_delete
WHERE type = 'bronze';
DELETE
FROM practice_delete
WHERE type = 'silver';
DELETE
FROM practice_delete
WHERE value = 150;
CREATE TABLE users
(
id SERIAL PRIMARY KEY,
name VARCHAR (50),
email VARCHAR(355)
);
INSERT INTO users
(email, name)
VALUES
('<EMAIL>', 'Tom'),
('<EMAIL>', 'Kev'),
('<EMAIL>', 'steve');
CREATE TABLE products
(
id SERIAL PRIMARY KEY,
name VARCHAR (50),
price INTEGER
);
INSERT INTO products
(price, name)
VALUES
(17, 'hat'),
( 21 , 'shirt'),
( 13, 'beanie');
CREATE TABLE orders
(
id SERIAL PRIMARY KEY,
name VARCHAR (50),
price VARCHAR(50),
FOREIGN KEY (id) REFERENCES products(id)
);
INSERT INTO orders
( id, price, name, total)
VALUES
(1, 17, 'hat', 17),
(2 , 21 , 'shirt', 21),
(2, 13, 'beanie', 13);
SELECT *
FROM orders;
SELECT *
FROM products
WHERE id = 1;
SELECT *
FROM orders
WHERE users.id = 1;
SELECT SUM(total)
FROM orders
WHERE users.id = 2
SELECT COUNT(*)
FROM ORDERS
where users.id = 3;
|
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:
TRUNCATE darksky_cards RESTART IDENTITY CASCADE;
TRUNCATE darksky_folders RESTART IDENTITY CASCADE;
INSERT INTO darksky_folders (title)
VALUES
('Folder 1'),
('Folder 2');
INSERT INTO darksky_cards (title, modified, folder_id, details, favorited)
VALUES
(
'Card 1',
'02-27-2021',
1,
'This is test card 1',
false
),
(
'Card 2',
'02-25-2021',
2,
'This is test card 2',
true
),
(
'Card 3',
'02-26-2021',
1,
'This is test card 3',
false
),
(
'Card 4',
'02-22-2021',
2,
'This is test card 4',
true
);
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 | 3 | TRUNCATE darksky_cards RESTART IDENTITY CASCADE;
TRUNCATE darksky_folders RESTART IDENTITY CASCADE;
INSERT INTO darksky_folders (title)
VALUES
('Folder 1'),
('Folder 2');
INSERT INTO darksky_cards (title, modified, folder_id, details, favorited)
VALUES
(
'Card 1',
'02-27-2021',
1,
'This is test card 1',
false
),
(
'Card 2',
'02-25-2021',
2,
'This is test card 2',
true
),
(
'Card 3',
'02-26-2021',
1,
'This is test card 3',
false
),
(
'Card 4',
'02-22-2021',
2,
'This is test card 4',
true
); |
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
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize variables with default values
output="output" # Directory where output should be stored.
samplesheet="SampleSheet.csv" # Path to the samplesheet file.
base_path="" # Base path for the sequencer produced files.
lane='.*' # Regular expression for processing only a subset of the lanes or tiles.
# Parse parameters from the command line.
while getopts "i:o:s:l:" opt; do
case "$opt" in
i) base_path=$OPTARG
;;
s) samplesheet=$OPTARG
;;
o) output=$OPTARG
;;
l) lane=$OPTARG
esac
done
shift $((OPTIND-1))
# STEP 1 DEMULTIPLEXING #######################################################
# Name and create demultiplexing input and output directories.
mkdir -p $output
current_date=$(date +%Y-%m-%d)
dir_input=$base_path/Data/Intensities/BaseCalls
dir_output=$output/Demultiplexed_"${current_date}"
base_mask="Y*,I6n*,Y*"
# Generate the make files which will do the demultiplexing.
/home/nanuq-admin/nanuq-programs/software/bcl2fastq-1.8.4/bin/configureBclToFastq.pl \
--input-dir ${dir_input} \
--output-dir ${dir_output} \
--sample-sheet ${samplesheet} \
--use-bases-mask ${base_mask} \
--mismatches 1 \
--tiles 's_'$lane'_.*' \
--fastq-cluster-count 0
# Preform demultiplexing.
pushd ${dir_output}
make -j 8
popd# STEP 2 TRIMMING #############################################################
mkdir $output/trim
FILE_ADAPTORS=adaptors.fa
# Trim all demultiplexed files in parrallel, then wait on the jobs to complete.
for file in $(ls $output/Demultiplexed_*/Project_*/*/*_R1_001.fastq.gz)
do
sampleID=$(basename $file _R1_001.fastq.gz)
java -XX:ParallelGCThreads=1 -jar /home/nanuq-admin/nanuq-programs/software/trimmomatic/Trimmomatic-0.32/trimmomatic-0.32.jar \
PE -phred33 -threads 8 \
$output/Demultiplexed_*/Project_*/*/${sampleID}_R1_001.fastq.gz \
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 | 4 | #!/bin/bash
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Initialize variables with default values
output="output" # Directory where output should be stored.
samplesheet="SampleSheet.csv" # Path to the samplesheet file.
base_path="" # Base path for the sequencer produced files.
lane='.*' # Regular expression for processing only a subset of the lanes or tiles.
# Parse parameters from the command line.
while getopts "i:o:s:l:" opt; do
case "$opt" in
i) base_path=$OPTARG
;;
s) samplesheet=$OPTARG
;;
o) output=$OPTARG
;;
l) lane=$OPTARG
esac
done
shift $((OPTIND-1))
# STEP 1 DEMULTIPLEXING #######################################################
# Name and create demultiplexing input and output directories.
mkdir -p $output
current_date=$(date +%Y-%m-%d)
dir_input=$base_path/Data/Intensities/BaseCalls
dir_output=$output/Demultiplexed_"${current_date}"
base_mask="Y*,I6n*,Y*"
# Generate the make files which will do the demultiplexing.
/home/nanuq-admin/nanuq-programs/software/bcl2fastq-1.8.4/bin/configureBclToFastq.pl \
--input-dir ${dir_input} \
--output-dir ${dir_output} \
--sample-sheet ${samplesheet} \
--use-bases-mask ${base_mask} \
--mismatches 1 \
--tiles 's_'$lane'_.*' \
--fastq-cluster-count 0
# Preform demultiplexing.
pushd ${dir_output}
make -j 8
popd# STEP 2 TRIMMING #############################################################
mkdir $output/trim
FILE_ADAPTORS=adaptors.fa
# Trim all demultiplexed files in parrallel, then wait on the jobs to complete.
for file in $(ls $output/Demultiplexed_*/Project_*/*/*_R1_001.fastq.gz)
do
sampleID=$(basename $file _R1_001.fastq.gz)
java -XX:ParallelGCThreads=1 -jar /home/nanuq-admin/nanuq-programs/software/trimmomatic/Trimmomatic-0.32/trimmomatic-0.32.jar \
PE -phred33 -threads 8 \
$output/Demultiplexed_*/Project_*/*/${sampleID}_R1_001.fastq.gz \
$output/Demultiplexed_*/Project_*/*/${sampleID}_R2_001.fastq.gz \
$output/trim/${sampleID}_trim_R1.fastq.gz $output/trim/${sampleID}_trim_R1_unpaired.fastq.gz \
$output/trim/${sampleID}_trim_R2.fastq.gz $output/trim/${sampleID}_trim_R2_unpaired.fastq.gz \
ILLUMINACLIP:${FILE_ADAPTORS}:2:30:10 \
TRAILING:30 MINLEN:36 &
done
wait
# STEP 3 ALIGNMENT ############################################################
mkdir -p $output/STAR/Log
mkdir -p $output/STAR/Within
mkdir -p $output/STAR/Unsorted
# STAR 1st pass
for file in $(ls $output/trim/*_trim_R1.fastq.gz)
do
sampleID=$(basename $file _trim_R1.fastq.gz)
mkdir -p $output/STAR/alignment_1stPass/${sampleID}/
/software/STAR/STAR-2.5.2a/bin/Linux_x86_64/STAR --runMode alignReads \
--genomeDir /is1/commonDatasets/STAR/Homo_sapiens.GRCh38/genome/star_index/Ensembl77.sjdbOverhang99 \
--readFilesIn \
$output/trim/${sampleID}_trim_R1.fastq.gz \
$output/trim/${sampleID}_trim_R2.fastq.gz \
--runThreadN 32 \
--readFilesCommand zcat \
--outStd Log \
--outSAMunmapped Within \
--outSAMtype BAM Unsorted \
--outFileNamePrefix $output/STAR/alignment_1stPass/${sampleID}/ \
--outSAMattrRGline ID:"${sampleID}" PL:"ILLUMINA" SM:"${sampleID}" CN:"CRCHUQ" \
--limitGenomeGenerateRAM 70000000000 \
--limitIObufferSize 1000000000
done
# Create new splice junction database containing the splice junctions of all samples
cat $output/STAR/alignment_1stPass/*/SJ.out.tab | \
awk 'BEGIN {OFS="\t"; strChar[0]="."; strChar[1]="+"; strChar[2]="-"} {if($5>0){print $1,$2,$3,strChar[$4]}}' | sort -k1,1h -k2,2n > $output/STAR/alignment_1stPass/AllSamples.SJ.out.tab && \
mkdir -p $output/STAR/reference.Merged && \
/software/STAR/STAR-2.5.2a/bin/Linux_x86_64/STAR --runMode genomeGenerate \
--genomeDir $output/STAR/reference.Merged \
--genomeFastaFiles /is1/commonDatasets/STAR/Homo_sapiens.GRCh38/genome/Homo_sapiens.GRCh38.fa \
--runThreadN 32 \
--limitGenomeGenerateRAM 50000000000 \
--sjdbFileChrStartEnd $output/STAR/alignment_1stPass/AllSamples.SJ.out.tab \
--limitIObufferSize 1000000000 \
--sjdbOverhang 99
# STAR 2nd pass.
for file in $(ls $output/trim/*_trim_R1.fastq.gz)
do
sampleID=$(basename $file _trim_R1.fastq.gz)
mkdir -p $output/alignment/${sampleID}
/software/STAR/STAR-2.5.2a/bin/Linux_x86_64/STAR --runMode alignReads \
--genomeDir $output/STAR/reference.Merged \
--readFilesIn \
$output/trim/${sampleID}_trim_R1.fastq.gz \
$output/trim/${sampleID}_trim_R2.fastq.gz \
--runThreadN 32 \
--readFilesCommand zcat \
--outStd Log \
--outSAMunmapped Within \
--outSAMtype BAM SortedByCoordinate \
--outFileNamePrefix $output/alignment/${sampleID}/ \
--limitGenomeGenerateRAM 70000000000 \
--limitBAMsortRAM 70000000000 \
--limitIObufferSize 1000000000 \
--outWigType wiggle read1_5p --outWigStrand Stranded --outWigReferencesPrefix chr
done
# Perform QC ##################################################################
module add fastqc/0.11.2
mkdir $output/fastqc
for file in $(ls $output/trim/*_R?.fastq.gz)
do
sequenceFile=`basename $file .fastq.gz`
mkdir -p $output/fastqc/$sequenceFile
fastqc $file -o $output/fastqc/$sequenceFile &
done
wait
# Count reads ##################################################################
module add python/2.7.8
mkdir $output/counts
for bamFile in $output/alignment/*/Aligned.sortedByCoord.out.bam
do
sampleDir=`dirname $bamFile`
sampleID=`basename sampleDir`
/home/foueri01/.local/bin/htseq-count -s reverse --order pos -f bam $bamFile /is1/commonDatasets/STAR/Homo_sapiens.GRCh38/annotations/Homo_sapiens.GRCh38.Ensembl77.gtf > $output/counts/$sampleID.counts &
done
Rscript summary_table.R $output |
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:
// 程序清单14.7.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Worker0.h"
const int LIM = 4;
int main()
{
{
Waiter bob("<NAME>", 314L, 5);
Singer bev("<NAME>", 522L, 3);
Waiter w_temp;
Singer s_temp;
Worker * pw[LIM] = {&bob, &bev, &w_temp, &s_temp};
int i;
for ( i = 2; i < LIM; i++)
{
pw[i]->Set();
}
for ( i = 0; i < LIM; i++)
{
pw[i]->Show();
printf("\n");
}
}
system("pause");
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 | 1 | // 程序清单14.7.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Worker0.h"
const int LIM = 4;
int main()
{
{
Waiter bob("<NAME>", 314L, 5);
Singer bev("<NAME>", 522L, 3);
Waiter w_temp;
Singer s_temp;
Worker * pw[LIM] = {&bob, &bev, &w_temp, &s_temp};
int i;
for ( i = 2; i < LIM; i++)
{
pw[i]->Set();
}
for ( i = 0; i < LIM; i++)
{
pw[i]->Show();
printf("\n");
}
}
system("pause");
return 0;
}
|
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:
//Classe de estrutura PRODUTO que contem: Nome, Departamento, Preço e Código de Barras
public class Produto {
private int codBarras;
private String nome;
private String departamento;
double preco;
// Já que meus atributos estão blindados (encapsulados) com "private" antes do atributo, precisamos de mecanismos para acessá-los
// Isso implica em uma funcionalidade (método) para modificar seu valor e outro método para consultar o seu valor.
// Para isso, basta ir em SOURCE --> Generate Getter and Setter --> Select all e Clica em finish;
public int getCodBarras() {
return codBarras;
}
public void setCodBarras(int codBarras) {
this.codBarras = codBarras;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
//Metodo para mostrar os produto
public String mostrarProduto() {
String resultado = "Nome: "+nome+ "\nPreço: R$ "+preco+"\nCódigo de Barras: "+codBarras+ "\nDepartamento: "+departamento+"\n";
return resultado;
}
//Metodo para aplicar desconto
public double aplicarDesconto (double desconto) {
double precodesconto;
precodesconto = preco - (preco*desconto/100);
return precodesconto;
}
}
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 | //Classe de estrutura PRODUTO que contem: Nome, Departamento, Preço e Código de Barras
public class Produto {
private int codBarras;
private String nome;
private String departamento;
double preco;
// Já que meus atributos estão blindados (encapsulados) com "private" antes do atributo, precisamos de mecanismos para acessá-los
// Isso implica em uma funcionalidade (método) para modificar seu valor e outro método para consultar o seu valor.
// Para isso, basta ir em SOURCE --> Generate Getter and Setter --> Select all e Clica em finish;
public int getCodBarras() {
return codBarras;
}
public void setCodBarras(int codBarras) {
this.codBarras = codBarras;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
//Metodo para mostrar os produto
public String mostrarProduto() {
String resultado = "Nome: "+nome+ "\nPreço: R$ "+preco+"\nCódigo de Barras: "+codBarras+ "\nDepartamento: "+departamento+"\n";
return resultado;
}
//Metodo para aplicar desconto
public double aplicarDesconto (double desconto) {
double precodesconto;
precodesconto = preco - (preco*desconto/100);
return precodesconto;
}
}
|
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:
# Use Neovim instead of vim.
# alias vim="nvim"
# alias v="nvim"
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 | # Use Neovim instead of vim.
# alias vim="nvim"
# alias v="nvim"
|
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 common
import (
. "ray-tracing/pkg/vec3"
)
// Probability density function
type PDF interface {
Value(direction Vec3) float64
Generate() Vec3
}
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 | package common
import (
. "ray-tracing/pkg/vec3"
)
// Probability density function
type PDF interface {
Value(direction Vec3) float64
Generate() Vec3
}
|
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:
/***************************************************************
*
* @file: nty_timer.h
* @author: wilson
* @version: 1.0
* @date: 2021-08-21 13:54:25
* @license: MIT
* @brief:
* (1) 计时器(Timer)管理多个计时任务(TimerTask),
* 每个计时任务(TimerTask)拥有独立的计时周期, 周期循环次数和回调函数
* (2) 采用红黑树维护计时任务结点
* (3) Thread unsafety. 因此多线程编程时, 让每个线程独自持有一份Timer对象
* (4) 支持linux\Windows\MacOS平台.
* 其中MacOS_10.12之前版本时间精度为微妙级,
* 而MacOS_10.12以后\linux\Windows平台下, 时间精度均可达纳秒级
*
***************************************************************/
#ifndef _NTY_TIMER_H_
#define _NTY_TIMER_H_
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include "ngx_rbtree.h"
#ifdef __cpluscplus
extern "C" {
#endif
typedef ngx_rbtree_node_t TimerTaskNode;
typedef struct TimerTask {
void (*cb_func)(struct TimerTask*); //[ 触发事件回调函数 ]
void* func_arg; //[ 回调函数补充传参 ]
uint32_t next_trigger_time; //[ 下次触发的时间点 ]
uint32_t interval; //[ 触发周期 ]
int32_t rest_loop_count; //[ 剩余触发周期次数 ]
} TimerTask;
typedef struct Timer {
ngx_rbtree_t tasktree; //[ 计时任务红黑树 ]
ngx_rbtree_node_t sentinel; //[ 红黑树哨兵节点 ]
uint32_t tree_size; //[ 红黑树节点数 ]
} Timer;
/* ============================ API ============================ */
/**
* @brief 初始化计时器, 获取其句柄
*
* @return Timer* -- 成功返回计时器句柄, 失败返回NULL
*/
Timer* nty_InitTimer();
/**
* @brief 构造计时器任务
*
* @param cb_func[in] 计时任务触发回调函数
* @param cb_func_arg[in] 回调函数传参
* @param interval[in] 计时任务触发周期(ms)
* @param loop_count[in] 计时任务周期的循环次数. loop_count为正数时, 表示执行loop_count次循环以后, 计时任务自动销毁. loop_count为负数时, 表示endless-loop. loop_count为0时, 循环将执行1次后销毁.
* @return TimerTask* -- 成功返回计时任务句柄, 失败返回NULL;
*/
TimerTask* nty_CreateTimerTask(void (*cb_func)(struct TimerTask*), void* cb_func_arg, uint32_t interval, int32_t loop_count);
/**
* @brief 向计时器中添加计时任务
*
* @param timer[in] 计时器句柄
* @param task[in] 计时任务句柄
* @return int -- 0 on success, -1 otherwise
*/
int nty_AddTimerTask(Timer* timer, TimerTask* task);
/**
* @brief 获取计时器中的计时任务数量
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 | 4 | /***************************************************************
*
* @file: nty_timer.h
* @author: wilson
* @version: 1.0
* @date: 2021-08-21 13:54:25
* @license: MIT
* @brief:
* (1) 计时器(Timer)管理多个计时任务(TimerTask),
* 每个计时任务(TimerTask)拥有独立的计时周期, 周期循环次数和回调函数
* (2) 采用红黑树维护计时任务结点
* (3) Thread unsafety. 因此多线程编程时, 让每个线程独自持有一份Timer对象
* (4) 支持linux\Windows\MacOS平台.
* 其中MacOS_10.12之前版本时间精度为微妙级,
* 而MacOS_10.12以后\linux\Windows平台下, 时间精度均可达纳秒级
*
***************************************************************/
#ifndef _NTY_TIMER_H_
#define _NTY_TIMER_H_
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include "ngx_rbtree.h"
#ifdef __cpluscplus
extern "C" {
#endif
typedef ngx_rbtree_node_t TimerTaskNode;
typedef struct TimerTask {
void (*cb_func)(struct TimerTask*); //[ 触发事件回调函数 ]
void* func_arg; //[ 回调函数补充传参 ]
uint32_t next_trigger_time; //[ 下次触发的时间点 ]
uint32_t interval; //[ 触发周期 ]
int32_t rest_loop_count; //[ 剩余触发周期次数 ]
} TimerTask;
typedef struct Timer {
ngx_rbtree_t tasktree; //[ 计时任务红黑树 ]
ngx_rbtree_node_t sentinel; //[ 红黑树哨兵节点 ]
uint32_t tree_size; //[ 红黑树节点数 ]
} Timer;
/* ============================ API ============================ */
/**
* @brief 初始化计时器, 获取其句柄
*
* @return Timer* -- 成功返回计时器句柄, 失败返回NULL
*/
Timer* nty_InitTimer();
/**
* @brief 构造计时器任务
*
* @param cb_func[in] 计时任务触发回调函数
* @param cb_func_arg[in] 回调函数传参
* @param interval[in] 计时任务触发周期(ms)
* @param loop_count[in] 计时任务周期的循环次数. loop_count为正数时, 表示执行loop_count次循环以后, 计时任务自动销毁. loop_count为负数时, 表示endless-loop. loop_count为0时, 循环将执行1次后销毁.
* @return TimerTask* -- 成功返回计时任务句柄, 失败返回NULL;
*/
TimerTask* nty_CreateTimerTask(void (*cb_func)(struct TimerTask*), void* cb_func_arg, uint32_t interval, int32_t loop_count);
/**
* @brief 向计时器中添加计时任务
*
* @param timer[in] 计时器句柄
* @param task[in] 计时任务句柄
* @return int -- 0 on success, -1 otherwise
*/
int nty_AddTimerTask(Timer* timer, TimerTask* task);
/**
* @brief 获取计时器中的计时任务数量
*
* @param timer[in] 计时器句柄
* @return int -- 执行正确返回任务数量, -1表示执行错误
*/
int nty_GetNumTimerTask(Timer* timer);
/**
* @brief 清空计时器中所有计时任务, 并释放计时器本身
*
* @return int -- 0 on success, -1 otherwise
*/
int nty_DestroyTimer(Timer* timer);
/**
* @brief 获取最接近触发的Timertask的触发事件
*
* @return uint32_t -- 触发事件
*/
uint32_t nty_GetNearestTriggerTime(Timer* timer);
/**
* @brief 更新计时器时间戳
*
* @param timer[in] 计时器句柄
*/
void nty_TimerTicks(Timer* timer);
/**
* @brief 获取当前时间戳(ms)
*
* @return uint32_t -- 当前时间戳
*/
uint32_t nty_GetCurrentTime();
#ifdef __cpluscplus
}
#endif
#endif // _NTY_TIMER_H_
|
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.veronica.idn.foodiest.login
class LoginViewModel {
}
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.veronica.idn.foodiest.login
class LoginViewModel {
} |
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:
/* Run on e-sim as:
* e-sim -r 1 -c 2 manual_message_pass.elf
*/
#include <stdio.h>
#include "e_lib.h"
int main(void) {
e_coreid_t coreid = e_get_coreid();
unsigned i;
if (coreid == 0x808) {
volatile int *p;
p = (int *) 0x80880000;
while ((*p) == 0); /* Wait until message has been written. */
printf("Received message.\n");
return 0;
}
else {
int i;
int *p;
p = (int *) 0x80880000;
*p = 0;
for (i = 0; i < 1000; i++);
*p = (int)coreid;
return 0;
}
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>"
| c | 2 | /* Run on e-sim as:
* e-sim -r 1 -c 2 manual_message_pass.elf
*/
#include <stdio.h>
#include "e_lib.h"
int main(void) {
e_coreid_t coreid = e_get_coreid();
unsigned i;
if (coreid == 0x808) {
volatile int *p;
p = (int *) 0x80880000;
while ((*p) == 0); /* Wait until message has been written. */
printf("Received message.\n");
return 0;
}
else {
int i;
int *p;
p = (int *) 0x80880000;
*p = 0;
for (i = 0; i < 1000; i++);
*p = (int)coreid;
return 0;
}
return 0;
}
|
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 "GeometryComponentSerializer.h"
using namespace ticpp;
#include "../../Maths/MathVector3.hpp"
#include "../../Maths/MathQuaternion.hpp"
using namespace Maths;
#include "../../System/SystemTypeMapper.hpp"
using namespace System;
namespace Serialization
{
ISystemComponent* GeometryComponentSerializer::DeSerialize( const std::string entityName, ticpp::Element* componentElement, const ISystemScene::SystemSceneMap& systemScenes )
{
std::string system;
componentElement->GetAttribute( System::Attributes::SystemType, &system );
ISystemScene::SystemSceneMap::const_iterator systemScene = systemScenes.find( SystemTypeMapper::StringToType( system ) );
std::string type;
componentElement->GetAttribute( System::Attributes::ComponentType, &type );
ISystemComponent* systemComponent = ( *systemScene ).second->CreateComponent( entityName, type );
ticpp::Element* attributesElement = componentElement->FirstChildElement( "attributes" );
for( Iterator< Element > attribute = attributesElement->FirstChildElement( false ); attribute != attribute.end( ); attribute++ )
{
std::string key;
attribute->GetAttribute( "key", &key );
float x, y, z, w;
if ( key == System::Attributes::Position )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
systemComponent->SetAttribute( System::Attributes::Position, MathVector3( x, y, z ) );
}
if ( key == System::Attributes::Scale )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
systemComponent->SetAttribute( System::Attributes::Scale, MathVector3( x, y, z ) );
}
if ( key == System::Attributes::Orientation )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
attribute->GetAttribute( "v4", &w );
systemComponent->SetAttribute( System::Attributes::Orien
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 | #include "GeometryComponentSerializer.h"
using namespace ticpp;
#include "../../Maths/MathVector3.hpp"
#include "../../Maths/MathQuaternion.hpp"
using namespace Maths;
#include "../../System/SystemTypeMapper.hpp"
using namespace System;
namespace Serialization
{
ISystemComponent* GeometryComponentSerializer::DeSerialize( const std::string entityName, ticpp::Element* componentElement, const ISystemScene::SystemSceneMap& systemScenes )
{
std::string system;
componentElement->GetAttribute( System::Attributes::SystemType, &system );
ISystemScene::SystemSceneMap::const_iterator systemScene = systemScenes.find( SystemTypeMapper::StringToType( system ) );
std::string type;
componentElement->GetAttribute( System::Attributes::ComponentType, &type );
ISystemComponent* systemComponent = ( *systemScene ).second->CreateComponent( entityName, type );
ticpp::Element* attributesElement = componentElement->FirstChildElement( "attributes" );
for( Iterator< Element > attribute = attributesElement->FirstChildElement( false ); attribute != attribute.end( ); attribute++ )
{
std::string key;
attribute->GetAttribute( "key", &key );
float x, y, z, w;
if ( key == System::Attributes::Position )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
systemComponent->SetAttribute( System::Attributes::Position, MathVector3( x, y, z ) );
}
if ( key == System::Attributes::Scale )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
systemComponent->SetAttribute( System::Attributes::Scale, MathVector3( x, y, z ) );
}
if ( key == System::Attributes::Orientation )
{
attribute->GetAttribute( "v1", &x );
attribute->GetAttribute( "v2", &y );
attribute->GetAttribute( "v3", &z );
attribute->GetAttribute( "v4", &w );
systemComponent->SetAttribute( System::Attributes::Orientation, MathQuaternion( x, y, z, w ) );
}
}
return systemComponent;
}
}
|
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 docker
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
type NetworkConfig struct {
Name string
Labels map[string]string
AttachIfExist bool
}
type Network struct {
ID string
NetworkConfig
cli *client.Client
}
func NewNetwork(client *Docker, config NetworkConfig) (*Network, error) {
if result, err := client.cli.NetworkInspect(context.Background(), config.Name); err == nil && config.AttachIfExist {
return &Network{
ID: result.ID,
NetworkConfig: config,
cli: client.cli,
}, nil
}
result, err := client.cli.NetworkCreate(context.Background(), config.Name, types.NetworkCreate{
CheckDuplicate: true,
Labels: config.Labels,
})
if err != nil {
return nil, err
}
return &Network{
NetworkConfig: config,
ID: result.ID,
cli: client.cli,
}, nil
}
func (n *Network) Close() error {
return n.cli.NetworkRemove(context.Background(), n.ID)
}
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 | 2 | package docker
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
type NetworkConfig struct {
Name string
Labels map[string]string
AttachIfExist bool
}
type Network struct {
ID string
NetworkConfig
cli *client.Client
}
func NewNetwork(client *Docker, config NetworkConfig) (*Network, error) {
if result, err := client.cli.NetworkInspect(context.Background(), config.Name); err == nil && config.AttachIfExist {
return &Network{
ID: result.ID,
NetworkConfig: config,
cli: client.cli,
}, nil
}
result, err := client.cli.NetworkCreate(context.Background(), config.Name, types.NetworkCreate{
CheckDuplicate: true,
Labels: config.Labels,
})
if err != nil {
return nil, err
}
return &Network{
NetworkConfig: config,
ID: result.ID,
cli: client.cli,
}, nil
}
func (n *Network) Close() error {
return n.cli.NetworkRemove(context.Background(), n.ID)
}
|
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
sed -i -e "\#::KIBANA_HOST::# s#::KIBANA_HOST::#${KIBANA_HOST}#g" /kibana/config/kibana.yml
sed -i -e "\#::KIBANA_PORT::# s#::KIBANA_PORT::#${KIBANA_PORT}#g" /kibana/config/kibana.yml
sed -i -e "\#::ES_URL::# s#::ES_URL::#${ES_URL}#g" /kibana/config/kibana.yml
sed -i -e "\#::KIBANA_INDEX::# s#::KIBANA_INDEX::#${KIBANA_INDEX}#g" /kibana/config/kibana.yml
sed -i -e "\#::APP_ID::# s#::APP_ID::#${APP_ID}#g" /kibana/config/kibana.yml
sed -i -e "\#::REQUEST_TIMEOUT::# s#::REQUEST_TIMEOUT::#${REQUEST_TIMEOUT}#g" /kibana/config/kibana.yml
sed -i -e "\#::SHARD_TIMEOUT::# s#::SHARD_TIMEOUT::#${SHARD_TIMEOUT}#g" /kibana/config/kibana.yml
sed -i -e "\#::VERIFY_SSL::# s#::VERIFY_SSL::#${VERIFY_SSL}#g" /kibana/config/kibana.yml
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 | #!/bin/bash
sed -i -e "\#::KIBANA_HOST::# s#::KIBANA_HOST::#${KIBANA_HOST}#g" /kibana/config/kibana.yml
sed -i -e "\#::KIBANA_PORT::# s#::KIBANA_PORT::#${KIBANA_PORT}#g" /kibana/config/kibana.yml
sed -i -e "\#::ES_URL::# s#::ES_URL::#${ES_URL}#g" /kibana/config/kibana.yml
sed -i -e "\#::KIBANA_INDEX::# s#::KIBANA_INDEX::#${KIBANA_INDEX}#g" /kibana/config/kibana.yml
sed -i -e "\#::APP_ID::# s#::APP_ID::#${APP_ID}#g" /kibana/config/kibana.yml
sed -i -e "\#::REQUEST_TIMEOUT::# s#::REQUEST_TIMEOUT::#${REQUEST_TIMEOUT}#g" /kibana/config/kibana.yml
sed -i -e "\#::SHARD_TIMEOUT::# s#::SHARD_TIMEOUT::#${SHARD_TIMEOUT}#g" /kibana/config/kibana.yml
sed -i -e "\#::VERIFY_SSL::# s#::VERIFY_SSL::#${VERIFY_SSL}#g" /kibana/config/kibana.yml
|
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.example.tmdbdemo.data
import com.example.tmdbdemo.BuildConfig
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object Networking {
lateinit var api_key: String
fun retrofitInstance(baseUrl: String, apiKey: String): NetworkService {
api_key = apiKey
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(
OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor()
.apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE
})
.build()
)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(NetworkService::class.java)
}
}
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.example.tmdbdemo.data
import com.example.tmdbdemo.BuildConfig
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object Networking {
lateinit var api_key: String
fun retrofitInstance(baseUrl: String, apiKey: String): NetworkService {
api_key = apiKey
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(
OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor()
.apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE
})
.build()
)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(NetworkService::class.java)
}
} |
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("database.php");
//THIS PAGE SHOULD BE RUN EVERYDAY TO SEND OUT REMINDERS
$due_books = "SELECT account.account_id,account.name, book.title, borrowed_books.due_date, "
. "DATEDIFF(`due_date`,CURRENT_DATE) AS DateDiff from borrowed_books ,"
. " account, uploaded_books, book where account.account_id=borrowed_books.account_id "
. "and uploaded_books.uploaded_book_id=borrowed_books.uploaded_book_id and uploaded_books.book_id=book.book_id and returned=0 ; ";
$statement = $db->prepare($due_books);
$statement->execute();
$due_books_array = $statement->fetchAll();
$statement->closeCursor();
function updateNotifications($notification,$account_id) {
global $db;
$insertQuery = "INSERT INTO `notifications`(`account_id`, `notification`)VALUES (:np_account_id,:np_notification)"; //not sure how to get the uploaded_book id from selecting borrow
$statement = $db->prepare($insertQuery);
$statement->bindValue(":np_notification", $notification);
$statement->bindValue(":np_account_id", $account_id);
$statement->execute();
$statement->closeCursor();
}
?>
<?php foreach ($due_books_array as $due_books) : ?>
<?php
if($due_books['DateDiff']==1)
{
$notification= $due_books['title'].', is due to be returned tomorrow.';
updateNotifications($notification,$due_books['account_id']);
}
else if($due_books['DateDiff']==3)
{
$notification= $due_books['title'].',is due to be returned in 3 days.';
updateNotifications($notification,$due_books['account_id']);
}
else if($due_books['DateDiff']<1)
{
$notification= $due_books['title'].',your book is over due, please return to the owner asap.';
updateNotifications($notification,$due_books['account_id']);
}
?>
<?php 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>"
| php | 2 | <?php
require("database.php");
//THIS PAGE SHOULD BE RUN EVERYDAY TO SEND OUT REMINDERS
$due_books = "SELECT account.account_id,account.name, book.title, borrowed_books.due_date, "
. "DATEDIFF(`due_date`,CURRENT_DATE) AS DateDiff from borrowed_books ,"
. " account, uploaded_books, book where account.account_id=borrowed_books.account_id "
. "and uploaded_books.uploaded_book_id=borrowed_books.uploaded_book_id and uploaded_books.book_id=book.book_id and returned=0 ; ";
$statement = $db->prepare($due_books);
$statement->execute();
$due_books_array = $statement->fetchAll();
$statement->closeCursor();
function updateNotifications($notification,$account_id) {
global $db;
$insertQuery = "INSERT INTO `notifications`(`account_id`, `notification`)VALUES (:np_account_id,:np_notification)"; //not sure how to get the uploaded_book id from selecting borrow
$statement = $db->prepare($insertQuery);
$statement->bindValue(":np_notification", $notification);
$statement->bindValue(":np_account_id", $account_id);
$statement->execute();
$statement->closeCursor();
}
?>
<?php foreach ($due_books_array as $due_books) : ?>
<?php
if($due_books['DateDiff']==1)
{
$notification= $due_books['title'].', is due to be returned tomorrow.';
updateNotifications($notification,$due_books['account_id']);
}
else if($due_books['DateDiff']==3)
{
$notification= $due_books['title'].',is due to be returned in 3 days.';
updateNotifications($notification,$due_books['account_id']);
}
else if($due_books['DateDiff']<1)
{
$notification= $due_books['title'].',your book is over due, please return to the owner asap.';
updateNotifications($notification,$due_books['account_id']);
}
?>
<?php endforeach; ?>
<html>
notifications sent
</html>
|
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:
# Creating-a-modern-blog-with-Django-and-Python
This is a modern blog which contains features like:
1. Commenting Systems with Discus
2. SEO Friendly slugs
3. Modern and User-friendly interface
4. Advanced Text Editor
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 | # Creating-a-modern-blog-with-Django-and-Python
This is a modern blog which contains features like:
1. Commenting Systems with Discus
2. SEO Friendly slugs
3. Modern and User-friendly interface
4. Advanced Text Editor
|
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:
//
// ZTOAuthViewController.swift
// SinaWeibo
//
// Created by sharayuki on 2017/1/8.
// Copyright © 2017年 sharayuki. All rights reserved.
//
import UIKit
import SVProgressHUD
class ZTOAuthViewController: UIViewController{
let webView = UIWebView()
override func loadView() {
view = webView
//MARK: webView的代理
webView.delegate = self
}
func clickClose() {
navigationController?.dismiss(animated: true, completion: nil)
}
func clickFull() {
webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '<EMAIL>'")
webView.stringByEvaluatingJavaScript(from: "document.getElementById('passwd').value = '<PASSWORD>'")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imgName: nil, target: self, action: #selector(clickClose))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imgName: nil, target: self, action: #selector(clickFull))
loadPage()
}
//MARK: 加载授权页面
func loadPage() {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
let req = URLRequest(url: URL(string: urlString)!)
webView.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: WebView代理
extension ZTOAuthViewController:UIWebViewDelegate{
//MARK: HUD展示
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
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 | //
// ZTOAuthViewController.swift
// SinaWeibo
//
// Created by sharayuki on 2017/1/8.
// Copyright © 2017年 sharayuki. All rights reserved.
//
import UIKit
import SVProgressHUD
class ZTOAuthViewController: UIViewController{
let webView = UIWebView()
override func loadView() {
view = webView
//MARK: webView的代理
webView.delegate = self
}
func clickClose() {
navigationController?.dismiss(animated: true, completion: nil)
}
func clickFull() {
webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '<EMAIL>'")
webView.stringByEvaluatingJavaScript(from: "document.getElementById('passwd').value = '<PASSWORD>'")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imgName: nil, target: self, action: #selector(clickClose))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imgName: nil, target: self, action: #selector(clickFull))
loadPage()
}
//MARK: 加载授权页面
func loadPage() {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
let req = URLRequest(url: URL(string: urlString)!)
webView.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: WebView代理
extension ZTOAuthViewController:UIWebViewDelegate{
//MARK: HUD展示
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
//MARK: webView的代理方法
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlString = request.url?.absoluteString ?? ""
let flag = "code="
//判断是否是我们需要的授权返回页面
if urlString.contains(flag) {
let quary = request.url?.query ?? ""
let code = (quary as NSString).substring(from: flag.characters.count)
print(code)
//获取令牌
ZTUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isLogin) in
if !isLogin{
print("登录失败")
}
print("登录成功")
//切换到欢迎页面
//通知appdelegate切换根视图
NotificationCenter.default.post(name: NSNotification.Name.AppChangeRootViewController, object: "ZTWelcomeViewController")
})
//在截取到code后 不让webView继续加载网页 阻止用户进一步乱跳网页
return false
}
return true
}
}
|
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:
//
// WarmUp.swift
// HRSwift
//
// Created by <NAME> on 2015-11-24.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
// https://www.hackerrank.com/challenges/angry-professor
public class AngryProfessor {
public init() {}
func solution() -> Void {
let TN = Int(getLine())!
for _ in 0..<TN {
let infoArray = getLineToArray().map {Int($0)!}
let K = infoArray[1]
let arrives = getLineToArray().map {Int($0)!}
// use filter to filter out unsatisfied elements
let earlyBirds = arrives.filter {$0 <= 0}
if earlyBirds.count >= K {
print("YES")
} else {
print("NO")
}
}
}
}
// https://www.hackerrank.com/challenges/sherlock-and-the-beast
public class SherlockAndTheBeast {
public init() {}
func solution() -> Void {
let TN = Int(getLine())!
for _ in 0..<TN {
let N = Int(getLine())!
print(cypherOutput(N))
}
}
public func cypherOutput(cypher: Int) -> String {
for i in SRange(start: cypher/3*3, end:-1, step:-3) {
if (cypher - i) % 5 == 0 {
let fives = String(count: i, repeatedValue: Character("5"))
let threes = String(count: cypher-i, repeatedValue: Character("3"))
return fives + threes
}
}
return "-1"
}
}
public class UtopianTree {
var heights:[Int]
static func generatesHeights() -> [Int] {
var heights = [1]
var h = 1
for i in 0..<60 {
// Normal remainder operator
//if (i%2 == 0) {
if (i & 1 == 0) {
h = h*2
} else {
h = h+1
}
heights.append(h)
}
return heights
}
public init() {
heights = UtopianTree.generatesHeights()
}
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 | //
// WarmUp.swift
// HRSwift
//
// Created by <NAME> on 2015-11-24.
// Copyright © 2015 <NAME>. All rights reserved.
//
import Foundation
// https://www.hackerrank.com/challenges/angry-professor
public class AngryProfessor {
public init() {}
func solution() -> Void {
let TN = Int(getLine())!
for _ in 0..<TN {
let infoArray = getLineToArray().map {Int($0)!}
let K = infoArray[1]
let arrives = getLineToArray().map {Int($0)!}
// use filter to filter out unsatisfied elements
let earlyBirds = arrives.filter {$0 <= 0}
if earlyBirds.count >= K {
print("YES")
} else {
print("NO")
}
}
}
}
// https://www.hackerrank.com/challenges/sherlock-and-the-beast
public class SherlockAndTheBeast {
public init() {}
func solution() -> Void {
let TN = Int(getLine())!
for _ in 0..<TN {
let N = Int(getLine())!
print(cypherOutput(N))
}
}
public func cypherOutput(cypher: Int) -> String {
for i in SRange(start: cypher/3*3, end:-1, step:-3) {
if (cypher - i) % 5 == 0 {
let fives = String(count: i, repeatedValue: Character("5"))
let threes = String(count: cypher-i, repeatedValue: Character("3"))
return fives + threes
}
}
return "-1"
}
}
public class UtopianTree {
var heights:[Int]
static func generatesHeights() -> [Int] {
var heights = [1]
var h = 1
for i in 0..<60 {
// Normal remainder operator
//if (i%2 == 0) {
if (i & 1 == 0) {
h = h*2
} else {
h = h+1
}
heights.append(h)
}
return heights
}
public init() {
heights = UtopianTree.generatesHeights()
}
func solution() -> Void {
let T = Int(getLine())!
for _ in 0..<T {
let N = Int(getLine())!
print(heights[N])
}
}
}
public class FindDigits {
public init() {}
public func countN(n: String) {
let N = Int(n)!
var count = 0
for c in n.characters {
let digit = Int(String(c))!
if digit == 0 {
continue
}
if N%digit == 0 {
count += 1
}
}
print(count)
}
func solution() -> Void {
let T = getInt()
for _ in 0..<T {
countN(getLine())
}
}
}
public class FindLargestSmallerOrEqual {
/**
* Input arr: A sorted array e.g: 1, 10, 16, 18, 20
* targe: The target to find e.g: 19
* Output : The largest smaller number's index if not equal e.g 3
* or -1, if something wrong.
*/
public func ysBinarySearch(arr: [Int], target: Int) -> Int {
if arr.count == 0 { return -1 }
var low = 0
var high = arr.count - 1
while (low < high && arr[(low + high)/2] != target) {
if arr[(low + high)/2] < target {
low = (low + high)/2 + 1
} else {
high = (low + high)/2 - 1
}
}
if arr[(low + high)/2] == target {
return (low + high)/2
}
if arr[low] < target {
return low
} else {
return low - 1
}
}
}
|
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 userController = require("../controllers").user;
const messageController = require("../controllers").message;
// strategy for checking logged in status before delivering requested assets
const checkAuthentication = (req, res, next) => {
if (req.isAuthenticated()) {
next();
} else {
res.status(401).send({ message: "Unauthorized" });
}
};
// routes
module.exports = (app, passport) => {
app.get("/api", (req, res) =>
res.status(200).send({
message: "Welcome to the /api path"
})
);
app.get("/api/users", userController.list);
// dev option
app.delete("/api/messages", messageController.destroyAll);
//
app.post("/api/messages", checkAuthentication, messageController.create);
app.get("/api/messages", checkAuthentication, messageController.list);
app.delete(
"/api/messages/:messageId",
checkAuthentication,
messageController.destroy
);
app.post("/api/register", passport.authenticate("local-signup"), (req, res) =>
res.status(200).json({ username: req.user.username })
);
app.post("/api/login", passport.authenticate("local-signin"), (req, res) =>
res.status(200).json({ username: req.user.username })
);
app.post("/api/logout", (req, res) => {
req.logout();
res.status(200).send({ message: "OK" });
});
app.get("/api/isLoggedIn", checkAuthentication, (req, res) =>
res.json({ username: req.user.username })
);
};
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 userController = require("../controllers").user;
const messageController = require("../controllers").message;
// strategy for checking logged in status before delivering requested assets
const checkAuthentication = (req, res, next) => {
if (req.isAuthenticated()) {
next();
} else {
res.status(401).send({ message: "Unauthorized" });
}
};
// routes
module.exports = (app, passport) => {
app.get("/api", (req, res) =>
res.status(200).send({
message: "Welcome to the /api path"
})
);
app.get("/api/users", userController.list);
// dev option
app.delete("/api/messages", messageController.destroyAll);
//
app.post("/api/messages", checkAuthentication, messageController.create);
app.get("/api/messages", checkAuthentication, messageController.list);
app.delete(
"/api/messages/:messageId",
checkAuthentication,
messageController.destroy
);
app.post("/api/register", passport.authenticate("local-signup"), (req, res) =>
res.status(200).json({ username: req.user.username })
);
app.post("/api/login", passport.authenticate("local-signin"), (req, res) =>
res.status(200).json({ username: req.user.username })
);
app.post("/api/logout", (req, res) => {
req.logout();
res.status(200).send({ message: "OK" });
});
app.get("/api/isLoggedIn", checkAuthentication, (req, res) =>
res.json({ username: req.user.username })
);
};
|
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 Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Infrastructure.Interception
{
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Utilities;
internal class DbConfigurationDispatcher
{
private readonly InternalDispatcher<IDbConfigurationInterceptor> _internalDispatcher
= new InternalDispatcher<IDbConfigurationInterceptor>();
public InternalDispatcher<IDbConfigurationInterceptor> InternalDispatcher
{
get { return _internalDispatcher; }
}
public virtual void Loaded(DbConfigurationLoadedEventArgs loadedEventArgs, DbInterceptionContext interceptionContext)
{
DebugCheck.NotNull(loadedEventArgs);
DebugCheck.NotNull(interceptionContext);
var clonedInterceptionContext = new DbConfigurationInterceptionContext(interceptionContext);
_internalDispatcher.Dispatch(i => i.Loaded(loadedEventArgs, clonedInterceptionContext));
}
}
}
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 Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Infrastructure.Interception
{
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Utilities;
internal class DbConfigurationDispatcher
{
private readonly InternalDispatcher<IDbConfigurationInterceptor> _internalDispatcher
= new InternalDispatcher<IDbConfigurationInterceptor>();
public InternalDispatcher<IDbConfigurationInterceptor> InternalDispatcher
{
get { return _internalDispatcher; }
}
public virtual void Loaded(DbConfigurationLoadedEventArgs loadedEventArgs, DbInterceptionContext interceptionContext)
{
DebugCheck.NotNull(loadedEventArgs);
DebugCheck.NotNull(interceptionContext);
var clonedInterceptionContext = new DbConfigurationInterceptionContext(interceptionContext);
_internalDispatcher.Dispatch(i => i.Loaded(loadedEventArgs, clonedInterceptionContext));
}
}
}
|
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>
<head>
<meta charset="utf-8">
<title>campfirecoffee.com</title>
</head>
<body>
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire-coffee.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire-family.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campsite-tent-night.jpg">
<h1>Locations and Hours</h1>
<ul>
<li>Monday 7:00am - 9:00pm</li>
<li>Tuesday 7:00am - 9:00pm</li>
<li>Wednesday 7:00am - 9:00pm</li>
<li>Thursday 7:00am - 9:00pm</li>
<li>Friday 7:00am - 9:00pm</li>
<li>Saturday 7:00am - 9:00pm</li>
<li>Sunday 7:00am - 9:00pm</li>
</ul>
</body>
</html>
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 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>campfirecoffee.com</title>
</head>
<body>
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire-coffee.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire-family.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campfire.jpg">
<img src="https://github.com/codefellows/seattle-201n6/blob/master/class-06-dom--objects--domain_modeling/lab/assets/campsite-tent-night.jpg">
<h1>Locations and Hours</h1>
<ul>
<li>Monday 7:00am - 9:00pm</li>
<li>Tuesday 7:00am - 9:00pm</li>
<li>Wednesday 7:00am - 9:00pm</li>
<li>Thursday 7:00am - 9:00pm</li>
<li>Friday 7:00am - 9:00pm</li>
<li>Saturday 7:00am - 9:00pm</li>
<li>Sunday 7:00am - 9:00pm</li>
</ul>
</body>
</html>
|
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 backend
import (
"Pushsystem/src/protocol"
"net"
"Pushsystem/src/utils"
"sync"
"time"
"math"
"fmt"
)
type Session struct {
//ProtoCheck *protocol.ProtoCheck //负责粘包处理
ManagerID [32]byte // 解析服务器的唯一ID
ManagerIDC uint16 // 解析服务的机房
Connection net.Conn // 连接handle
State bool // 当前状态
RegisterTime int64 // 注册时间
HbTimeCount int64 // 心跳时间戳
}
/*
获取客户端的ip和端口
*/
func (session *Session) remoteAddr() string {
addr := session.Connection.RemoteAddr()
return addr.String()
}
func (session *Session) uniqueId() string {
return utils.UniqueId(int32(session.ManagerIDC),string(session.ManagerID[:]))
}
var sessionManagerInstance *SessionManager
var sessionOnce sync.Once
func GetFrontSessionInstance() *SessionManager {
sessionOnce.Do(func(){
sessionManagerInstance = &SessionManager{}
})
return sessionManagerInstance
}
type SessionManager struct{
//Map sync.Map
Map SafeMap
}
func (handle * SessionManager) Add (uniqueId string,session *Session) {
handle.Map.Set(uniqueId,session)
}
func (handle * SessionManager) Get (uniqueId string ) interface{} {
return handle.Map.Get(uniqueId)
}
func (handle * SessionManager) Delete(uniqueId string) {
handle.Map.Delete(uniqueId)
}
func (handle * SessionManager) HBCheckBySlot(slot int, dur int64) {
handle.Map.Range(func (key,value interface{}) bool{
uniqueId := key.(string)
session := key.(Session)
curCount := time.Now().Unix()
if session.HbTimeCount == 0 {
session.HbTimeCount = curCount
}else {
if math.Abs(float64(curCount - session.HbTimeCount)) > float64(dur) {
fmt.Println("client",uniqueId,"break by hbcheck")
ipKey := session.remoteAddr()
obj := GetFrontSessionByIpInstance() //同时
obj.Delete(ipKey)
}
}
return true
})
}
type SessionByIp struct {
ManagerID [32]byte // 解析服务器的唯一ID
ManagerIDC uint16 // 解析服务的机房
ProtoCheck *protocol.ProtoCheck //协议检测
Conn net.Conn
}
func (obj *SessionByIp)Init(){
obj.ProtoCheck = &protocol.ProtoCh
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 backend
import (
"Pushsystem/src/protocol"
"net"
"Pushsystem/src/utils"
"sync"
"time"
"math"
"fmt"
)
type Session struct {
//ProtoCheck *protocol.ProtoCheck //负责粘包处理
ManagerID [32]byte // 解析服务器的唯一ID
ManagerIDC uint16 // 解析服务的机房
Connection net.Conn // 连接handle
State bool // 当前状态
RegisterTime int64 // 注册时间
HbTimeCount int64 // 心跳时间戳
}
/*
获取客户端的ip和端口
*/
func (session *Session) remoteAddr() string {
addr := session.Connection.RemoteAddr()
return addr.String()
}
func (session *Session) uniqueId() string {
return utils.UniqueId(int32(session.ManagerIDC),string(session.ManagerID[:]))
}
var sessionManagerInstance *SessionManager
var sessionOnce sync.Once
func GetFrontSessionInstance() *SessionManager {
sessionOnce.Do(func(){
sessionManagerInstance = &SessionManager{}
})
return sessionManagerInstance
}
type SessionManager struct{
//Map sync.Map
Map SafeMap
}
func (handle * SessionManager) Add (uniqueId string,session *Session) {
handle.Map.Set(uniqueId,session)
}
func (handle * SessionManager) Get (uniqueId string ) interface{} {
return handle.Map.Get(uniqueId)
}
func (handle * SessionManager) Delete(uniqueId string) {
handle.Map.Delete(uniqueId)
}
func (handle * SessionManager) HBCheckBySlot(slot int, dur int64) {
handle.Map.Range(func (key,value interface{}) bool{
uniqueId := key.(string)
session := key.(Session)
curCount := time.Now().Unix()
if session.HbTimeCount == 0 {
session.HbTimeCount = curCount
}else {
if math.Abs(float64(curCount - session.HbTimeCount)) > float64(dur) {
fmt.Println("client",uniqueId,"break by hbcheck")
ipKey := session.remoteAddr()
obj := GetFrontSessionByIpInstance() //同时
obj.Delete(ipKey)
}
}
return true
})
}
type SessionByIp struct {
ManagerID [32]byte // 解析服务器的唯一ID
ManagerIDC uint16 // 解析服务的机房
ProtoCheck *protocol.ProtoCheck //协议检测
Conn net.Conn
}
func (obj *SessionByIp)Init(){
obj.ProtoCheck = &protocol.ProtoCheck{}
obj.ProtoCheck.Init()
}
func (session *SessionByIp) remoteAddr() string {
addr := session.Conn.RemoteAddr()
return addr.String()
}
func (session *SessionByIp) uniqueId() string {
return utils.UniqueId(int32(session.ManagerIDC),string(session.ManagerID[:]))
}
var sessionManagerByIpInstance *SessionManagerByIp
var sessionByIpOnce sync.Once
func GetFrontSessionByIpInstance() *SessionManagerByIp {
sessionByIpOnce.Do(func(){
sessionManagerByIpInstance = &SessionManagerByIp{}
})
return sessionManagerByIpInstance
}
type SessionManagerByIp struct{
Map sync.Map
}
func (handle * SessionManagerByIp) Add (addr string,session SessionByIp) {
handle.Map.Store(addr,session)
}
func (handle * SessionManagerByIp) Get (addr string ) (interface{} ,bool) {
return handle.Map.Load(addr)
}
func (handle * SessionManagerByIp) Delete(addr string) {
handle.Map.Delete(addr)
}
|
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:
<?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">@media screen { h1,h2,h3,h4,h5,p,a,br,li,td, .underline {font-family:Arial, Helvetica, sans-serif;text-align:justify} body {font-size:11pt;line-height:1.3em} h1 {font-size:18pt} h2 {font-size:15pt} h3 {font-size:13pt} h4 {font-size:12pt} h5 {font-size:11pt} hr {text-align:center;height:1px;border:none;background:black} ol,ul,p,table {margin-left:3em;margin-right:3em} a {text-decoration:none} a:hover {text-decoration:underline} img {} .defword {width:25%} .defexplain {} .defexplain p {padding:0em;margin:0em} .deftablepara {} .deftable {width:85%;padding-left:1em;border-style:none;vertical-align:top} .deftable td {text-align:left;vertical-align:top} .deftablefaq {border-style:solid;border-width:thin} .stdtable {border:1px solid;background:black} .stdtable th {padding:0.5em;background:#EEEEEE;font-family:Arial, Helvetica, sans-serif;font-weight:bold;text-align:center} .stdtable td {padding:0.5em;background:white;text-align:left;vertical-align:top} .end {font-size:8pt} .example {margin-left:3em;margin-right:3em;border:1px solid;padding:1em;background-color:#EEEEEE} .header {margin-left:3em;margin-right:3em;border:1px solid;padding:1em;background-color:#FFFFEE} .indented {margin-left: 50px} .litable {text-align:left} .new {border-right:10px solid;padding-right:10px;font-family:Arial} .note {margin:0.5em 3em 0.5em 3em;border:1px solid;padding:0em;background-color:#F0F0A0} .note .title {font-family:sans-serif;font-weight:bold;margin:0.5em} .note .message {margin:0.5em 1.5em 0.5em 1.5em;padding:0em} .note .message p {padding:0em;margin:1em 0em 1em 0em} .reference {} .caption {font-size:10pt;text-align:center;font-style:italic} .todolist {padding:0.5em
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 | <?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">@media screen { h1,h2,h3,h4,h5,p,a,br,li,td, .underline {font-family:Arial, Helvetica, sans-serif;text-align:justify} body {font-size:11pt;line-height:1.3em} h1 {font-size:18pt} h2 {font-size:15pt} h3 {font-size:13pt} h4 {font-size:12pt} h5 {font-size:11pt} hr {text-align:center;height:1px;border:none;background:black} ol,ul,p,table {margin-left:3em;margin-right:3em} a {text-decoration:none} a:hover {text-decoration:underline} img {} .defword {width:25%} .defexplain {} .defexplain p {padding:0em;margin:0em} .deftablepara {} .deftable {width:85%;padding-left:1em;border-style:none;vertical-align:top} .deftable td {text-align:left;vertical-align:top} .deftablefaq {border-style:solid;border-width:thin} .stdtable {border:1px solid;background:black} .stdtable th {padding:0.5em;background:#EEEEEE;font-family:Arial, Helvetica, sans-serif;font-weight:bold;text-align:center} .stdtable td {padding:0.5em;background:white;text-align:left;vertical-align:top} .end {font-size:8pt} .example {margin-left:3em;margin-right:3em;border:1px solid;padding:1em;background-color:#EEEEEE} .header {margin-left:3em;margin-right:3em;border:1px solid;padding:1em;background-color:#FFFFEE} .indented {margin-left: 50px} .litable {text-align:left} .new {border-right:10px solid;padding-right:10px;font-family:Arial} .note {margin:0.5em 3em 0.5em 3em;border:1px solid;padding:0em;background-color:#F0F0A0} .note .title {font-family:sans-serif;font-weight:bold;margin:0.5em} .note .message {margin:0.5em 1.5em 0.5em 1.5em;padding:0em} .note .message p {padding:0em;margin:1em 0em 1em 0em} .reference {} .caption {font-size:10pt;text-align:center;font-style:italic} .todolist {padding:0.5em;font-size:10pt} .todolist p {margin:0em 3em 0em 3em} .todo {margin:1em 3em 1em 3em;padding:0.5em;border:solid 2px black;background:#FFAAAA;font-size:8pt} .todo p {margin:0.2em 1em 0.2em 1em} .inline {margin:0.5em 3em 0.5em 3em;border:solid 1px;padding:0em;background-color:#EEEEEE} .inline .title {font-family:sans-serif;font-weight:bold;margin:0.5em} .inline .elements {font-size:10pt;margin:0em 0em 0.5em 0em;padding:0em 1em 0em 1em} .inline .elements p {display:inline-table;margin:0.25em 0.5em 0.25em 0.5em} .tocindent {margin-left: 2em} .top {font-size:8pt;text-align:right} .underline {text-decoration:underline} } @media print { h1,h2,h3,h4,h5,p,a,br,li, #underline {font-family:Arial;text-align:justify;orphans:5;widows:5} p,li,td {font-size:10pt} ul,ol {page-break-after:avoid;orphans:5;widows:5} }</style><title>R3-GUI Getting Started</title></head><body onload="window.location.hash = window.location.hash"><a id="top" name="top"></a><h2>R3-GUI Getting Started</h2><pre class="header"><strong>Author: <NAME>, Saphirion AG
Date: 19-Jan-2013
Version: $Id$</strong></pre><hr /><h2>Contents</h2><div class="tocindent"><a href="#sect1"><strong>1. Introduction</strong></a><br /><div class="tocindent"><a href="#sect1.1"><strong>1.1 Where does R3-GUI fit with respect to the other GUI libs?</strong></a><br /><a href="#sect1.2"><strong>1.2 Available Documentation</strong></a><br /><a href="#sect1.3"><strong>1.3 Getting Ready</strong></a><br /></div><a href="#sect2"><strong>2. Minimal Example</strong></a><br /><div class="tocindent"><a href="#sect2.1"><strong>2.1 Summary</strong></a><br /></div><a href="#sect3"><strong>3. How do things fit together?</strong></a><br /><a href="#sect4"><strong>4. What to read next?</strong></a><br /></div><div class="note"><div class="message"><p>The docs are work in progress.</p></div></div><h2><a id="sect1" name="sect1">1. Introduction</a></h2><p>R3-GUI is a framework for building GUI applications with Rebol-3.</p><p>R3-GUI is inspired by the Rebol-2 GUI framework VID in terms of ease of use and using a dialect to specify your GUI.</p><p>R3-GUI is designed for real-world applications and can be used to create simple tests up to even big commercial applications.</p><h3><a id="sect1.1" name="sect1.1">1.1 Where does R3-GUI fit with respect to the other GUI libs?</a></h3><p>R3-GUI is not compatible (anymore) with the GUI done by <NAME> for Rebol 3 in the past. We forked R3-GUI and extended & changed it. This was due to some limitations we hit and to some design decisions that we think are not fitting our goal to make enterprise applications with R3-GUI.</p><h3><a id="sect1.2" name="sect1.2">1.2 Available Documentation</a></h3><p>Different aspects of R3-GUI are documented. Some high-level stuff but although some very deep low-level stuff. The documentation is still in an early stage. We are working one it.</p><p>We provide some older documentation as well. This documentation is based on the former GUI framework (before our fork) and still give some hintsight. Nevertheless, most examples etc. won't work with our version.</p><p>We are going to clean-up this situation over time.</p><h3><a id="sect1.3" name="sect1.3">1.3 Getting Ready</a></h3><p>R3-GUI is not part of the R3 interpreter. The R3 interpreter just contains the underlaying things like the graphics engine and basic graphic building blocks.</p><p>To use R3-GUI you first have to load it. This can be done by downloading R3-GUI to your local directory. An other option is to use Saphirion's latest release and have it downloaded from our web-site. To do this use:</p><pre class="example">load-gui</pre><p>Saphirion's R3 version has the URL to the R3-GUI source code hard-coded into R3, so you don't have to care.</p><div class="note"><div class="message"><p>At the moment you can load only one version. We are going to add more fine grain options so that you can load the latest, stable, or a specific version using the load-gui command.</p></div></div><div class="top">[ <a href="#top">back to top</a> ]</div><hr /><h2><a id="sect2" name="sect2">2. Minimal Example</a></h2><p>The following example creates a window that displays a text and has a button to close the window.</p><pre class="example">view [
text "Example window."
button "Close" on-action [close-window face]
]</pre><p>Let's walk through the different parts of the code.</p><pre class="example">view <layout block></pre><p>The VIEW function displays a window with a content that is specfied by a so called layout block. The layout block is the part that is written in R3-GUI language. In this block you specify how the GUI should be build and act.</p><p>Hence, the layout block is a classical Rebol dialect. A specialized domain specific language to describe GUIs.</p><p>The next two lines already use two widgets, which are called styles in the Rebol world. These are provided and implemented by the R3-GUI code you loaded.</p><pre class="example">text <string>
button <caption> on-action <action-block></pre><p>TEXT obviously shows the text given by the string. And BUTTON shows a button. So far pretty easy.</p><p>The interesting part is how we define an action. Something that should be executed when the user uses the widget. This is done by specifying an ON-ACTION action-block. R3-GUI knows for each widget, when the on-action should be executed. This is defined by the person who implemented the widget. Depending on the widget an ON-ACTION can be executed on different user actions. For the button this is the case, when you press the button. For a complex widget, this might be something totally different.</p><p>Let's take a look at the action itself.</p><pre class="example">on-action [close-window face]</pre><p>The CLOSE-WINDOW function is quite easy to understand. But what's this FACE word? Where does it come from? When R3-GUI executes the action-block it actually does this:</p><pre class="example">do-actor face 'on-action any [arg-value get-face face]</pre><p>Here the FACE word is actually our BUTTON. So, it uses our button object, looks up the ON-ACTION actor and executes the found code like a function call. And, as for normal functions, the function is called with some parameters. In our case with FACE which refers to our button widget. And since you can access function parameters in the function code, you can of course use the FACE word to get access to the button object.</p><p>So, there are some implicit words you can use. These are always the same for all widgets.</p><p>Hmm, but how do you close the window of the BUTTON widget? Well, CLOSE-WINDOW doesn't close the windows specified by FACE but it's parent. Which is, in our case, the main window. Hence, the program terminates.</p><h3><a id="sect2.1" name="sect2.1">2.1 Summary</a></h3><p>You see that it's quite easy to do GUIs with R3-GUI. You need to know a couple of concepts and that's it. Here is a list of things to remember:</p><ol><li>Use VIEW to transform the R3-GUI dialect into some internal form and display it.</li><li>All code that should be executed because of an action by the user is put in an ON-ACTIOn action-block. This is a <strong>major</strong> difference to older R3-GUI implementations where the action-block wasn't preceded by the ON-ACTION word.</li><li>You can access implicit words inside the action-block. One that is always available is FACE which referes to the widget in which context the action is executed.</li></ol><div class="top">[ <a href="#top">back to top</a> ]</div><hr /><h2><a id="sect3" name="sect3">3. How do things fit together?</a></h2><p>Since R3-GUI is a bit different than normal GUI libraries you might know from the C, Java, etc. world, let's see how things fit together.</p><p>You already learned that the Rebol widgets are called styles. These are prototype definitions, that define default values for most attributes of a widget. Something like a class.</p><p>From such styles, you create a specific FACE that uses a STYLE as base. The FACE is the actual concrete widget on the screen. You can change all values of its attributes. A FACE object offers a lot of information you can inspect.</p><p>A group of faces is managed through a layout. Layouts are collections of faces used for specific parts of a user interface. You specify the layout by using special layout words in the layout-block of the VIEW function.</p><p>R3-GUI system has been designed to make layouts very easy to create, debug, and maintain. One of the main goals was for simple GUI definitions to be able to create a wide range of simple, predictable layouts, but also to allow more sophisticated and elaborate results to be produced using the same set of basic rules.</p><p>Basically, layouts provide a way to:</p><ol><li>Group a number of faces together</li><li>Arrange faces into a desired layout</li><li>Display a 2D layer, with background or other effects</li><li>Update and resize those faces when events occur</li></ol><div class="top">[ <a href="#top">back to top</a> ]</div><hr /><h2><a id="sect4" name="sect4">4. What to read next?</a></h2><p>To get a good understanding, we suggest that you read things in the following order:</p><ol><li>FACES to understand the basic building blocks and how these looks like.</li><li>LAYOUTS to understand how you can build GUIs consisting of many widgets and how these are managed.</li><li>ACTORS bring life to your GUI. This is where all the interaction comes from.</li><li>STYLES to understand how new widgets can be defined.</li></ol><p>END OF DOCUMENT</p><div class="top">[ <a href="#top">back to top</a> ]</div><hr /><p class="end">Document formatter copyright <a href="http://www.robertmuench.de"><NAME>ünch</a>. All Rights Reserved.<br />XHTML 1.0 Transitional formatted with Make-Doc-Pro Version:1.3.0 on 20-Jan-2013 at 1:27:16</p></body></html> |
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:
CREATE TABLE IF NOT EXISTS customer (
customer_id serial,
customer_info jsonb -- {name, contacts: {email, number}, age, nationality}
-- we need name & contacts to inform customers about fests they might like;
-- age and/or nationality can be used to make further statistics (if we want)
);
CREATE TABLE IF NOT EXISTS fest (
fest_id serial,
ratings int[10], -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}', -- ratings[i] is number ratings 'i'
prices int[10], -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}', -- prices is const for every fest; => trigger on upd?
-- if number of prices = n < 8 then prices[n] = .. = prices[n]
-- and in that case we can use only one function
-- (e. g calculate total price) for all the fests
n_tickets int[10] -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0}', -- n_tickets[i] tickets for price prices[i]
-- genres int[]
);
-- main statistics is here
CREATE TABLE IF NOT EXISTS genre (
genre_id serial,
genre_name varchar(30),
-- fest_ids int[], -- trigger on upd => change ratings & totals
ratings int[10] DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}',
total_revenue int,
total_tickets int
-- ratings & totals are recalculated once a hour/day/month/...
);
CREATE TABLE IF NOT EXISTS genre_fest (
genre_fest_id serial,
genre_id int,
fest_id int
);
CREATE TABLE IF NOT EXISTS ticket (
ticket_id serial,
customer_id int,
fest_id int,
price_id int -- in [1, 10]
-- trigger on insert => upd fest.n_tickets
);
CREATE TABLE IF NOT EXISTS rewiew (
rewiew_id serial,
customer_id int,
fest_id int,
rating int,
content text
-- trigger on insert => upd fest.ratings
);
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 | 3 | CREATE TABLE IF NOT EXISTS customer (
customer_id serial,
customer_info jsonb -- {name, contacts: {email, number}, age, nationality}
-- we need name & contacts to inform customers about fests they might like;
-- age and/or nationality can be used to make further statistics (if we want)
);
CREATE TABLE IF NOT EXISTS fest (
fest_id serial,
ratings int[10], -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}', -- ratings[i] is number ratings 'i'
prices int[10], -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}', -- prices is const for every fest; => trigger on upd?
-- if number of prices = n < 8 then prices[n] = .. = prices[n]
-- and in that case we can use only one function
-- (e. g calculate total price) for all the fests
n_tickets int[10] -- DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0}', -- n_tickets[i] tickets for price prices[i]
-- genres int[]
);
-- main statistics is here
CREATE TABLE IF NOT EXISTS genre (
genre_id serial,
genre_name varchar(30),
-- fest_ids int[], -- trigger on upd => change ratings & totals
ratings int[10] DEFAULT '{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}',
total_revenue int,
total_tickets int
-- ratings & totals are recalculated once a hour/day/month/...
);
CREATE TABLE IF NOT EXISTS genre_fest (
genre_fest_id serial,
genre_id int,
fest_id int
);
CREATE TABLE IF NOT EXISTS ticket (
ticket_id serial,
customer_id int,
fest_id int,
price_id int -- in [1, 10]
-- trigger on insert => upd fest.n_tickets
);
CREATE TABLE IF NOT EXISTS rewiew (
rewiew_id serial,
customer_id int,
fest_id int,
rating int,
content text
-- trigger on insert => upd fest.ratings
);
|
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:
export const FETCH_PLAYLIST_REQUEST = 'FETCH_PLAYLIST_REQUEST';
export const FETCH_PLAYLIST_SUCCESS = 'FETCH_PLAYLIST_SUCCESS';
export const FETCH_PLAYLIST_FAILED = 'FETCH_PLAYLIST_FAILED';
export const FETCH_PLAYLIST_ABORT = 'FETCH_PLAYLIST_ABORT';
export const UPDATE_PLAYLIST_NAME_SUCCESS = 'UPDATE_PLAYLIST_NAME_SUCCESS';
export const UPDATE_PLAYLIST_NAME_FAILED = 'UPDATE_PLAYLIST_NAME_FAILED';
export const UPDATE_PLAYLIST_IMAGE_SUCCESS = 'UPDATE_PLAYLIST_IMAGE_SUCCESS';
export const UPDATE_PLAYLIST_IMAGE_FAILED = 'UPDATE_PLAYLIST_IMAGE_FAILED';
export const ADD_TRACK_TO_PLAYLIST_SUCCESS = 'ADD_TRACK_TO_PLAYLIST_SUCCESS';
export const ADD_TRACK_TO_PLAYLIST_FAILED = 'ADD_TRACK_TO_PLAYLIST_FAILED';
export const REMOVE_TRACK_FROM_PLAYLIST_SUCCESS = 'REMOVE_TRACK_FROM_PLAYLIST_SUCCESS';
export const REMOVE_TRACK_FROM_PLAYLIST_FAILED = 'REMOVE_TRACK_FROM_PLAYLIST_FAILED';
export const CREATE_PLAYLIST_SUCCESS = 'CREATE_PLAYLIST_SUCCESS';
export const CREATE_PLAYLIST_FAILED = 'CREAT_PLAYLIST_FAILED';
export const STORE_USER_FOLLOWING_PLAYLIST = 'STORE_USER_FOLLOWING_PLAYLIST';
export const STORE_PLAYLIST_TRACK_IDS = 'STORE_PLAYLIST_TRACK_IDS';
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 | 1 | export const FETCH_PLAYLIST_REQUEST = 'FETCH_PLAYLIST_REQUEST';
export const FETCH_PLAYLIST_SUCCESS = 'FETCH_PLAYLIST_SUCCESS';
export const FETCH_PLAYLIST_FAILED = 'FETCH_PLAYLIST_FAILED';
export const FETCH_PLAYLIST_ABORT = 'FETCH_PLAYLIST_ABORT';
export const UPDATE_PLAYLIST_NAME_SUCCESS = 'UPDATE_PLAYLIST_NAME_SUCCESS';
export const UPDATE_PLAYLIST_NAME_FAILED = 'UPDATE_PLAYLIST_NAME_FAILED';
export const UPDATE_PLAYLIST_IMAGE_SUCCESS = 'UPDATE_PLAYLIST_IMAGE_SUCCESS';
export const UPDATE_PLAYLIST_IMAGE_FAILED = 'UPDATE_PLAYLIST_IMAGE_FAILED';
export const ADD_TRACK_TO_PLAYLIST_SUCCESS = 'ADD_TRACK_TO_PLAYLIST_SUCCESS';
export const ADD_TRACK_TO_PLAYLIST_FAILED = 'ADD_TRACK_TO_PLAYLIST_FAILED';
export const REMOVE_TRACK_FROM_PLAYLIST_SUCCESS = 'REMOVE_TRACK_FROM_PLAYLIST_SUCCESS';
export const REMOVE_TRACK_FROM_PLAYLIST_FAILED = 'REMOVE_TRACK_FROM_PLAYLIST_FAILED';
export const CREATE_PLAYLIST_SUCCESS = 'CREATE_PLAYLIST_SUCCESS';
export const CREATE_PLAYLIST_FAILED = 'CREAT_PLAYLIST_FAILED';
export const STORE_USER_FOLLOWING_PLAYLIST = 'STORE_USER_FOLLOWING_PLAYLIST';
export const STORE_PLAYLIST_TRACK_IDS = 'STORE_PLAYLIST_TRACK_IDS'; |
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 PROCEDURE IF EXISTS getPaymentMethod;
DELIMITER |
CREATE DEFINER=`root`@`localhost` PROCEDURE `getPaymentMethod`(
IN find_id_loc VARCHAR(20)
)
BEGIN
DECLARE n_paymentmethod INT;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH%' AND `content` LIKE '%FPCC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Mixto";
ELSE
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Efectivo";
ELSE
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Credito";
END IF;
END IF;
END IF;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCCAX%' OR `content` LIKE '%FPAX%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="American Express";
END IF;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH+CC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Mixto";
END IF;
END |
DELIMITER ;
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 | 2 | DROP PROCEDURE IF EXISTS getPaymentMethod;
DELIMITER |
CREATE DEFINER=`root`@`localhost` PROCEDURE `getPaymentMethod`(
IN find_id_loc VARCHAR(20)
)
BEGIN
DECLARE n_paymentmethod INT;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH%' AND `content` LIKE '%FPCC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Mixto";
ELSE
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Efectivo";
ELSE
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Credito";
END IF;
END IF;
END IF;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCCAX%' OR `content` LIKE '%FPAX%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="American Express";
END IF;
SET n_paymentmethod=(SELECT COUNT(*) FROM ifm_dbstoredgdsfile WHERE pnrLocator=find_id_loc AND content LIKE '%FPCASH+CC%');
IF (n_paymentmethod>0) THEN
SET @find_paymentmethod="Mixto";
END IF;
END |
DELIMITER ;
|
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:
#Date Utilities
<NAME>
June 11, 2009
Namespace: lib.devlinsf.joda-utils
This library is designed to wrap the Joda Time library from clojure. It was inspired by <NAME> work with sequence abstractions.
It depends on `clojure.contrib.str-utils`, `lib.devlinsf.date-utils`, and the Joda-time 1.6 jar.
#Extending to-ms-count
The first thing this library does is add cases the to-ms-count method for the following classes:
defmethod to-ms-count org.joda.time.DateTime
defmethod to-ms-count org.joda.time.Instant
defmethod to-ms-count org.joda.time.base.BaseDateTime
This way there is now a way to convert Joda time data types to standard java data types. Next the following constructor functions
are defining
defn datetime => returns org.joda.time.DateTime
defn instant => returns org.joda.time.Instant
These functions are written in terms of to-ms-count, so that they have the broad range of inputs you'd expect.
#Creating a duration
The next function that is created is a duration constructor. The Joda time library provides two styles of constructors. The first take a long number of ms. The
second implementation takes a start and stop time.
(defn duration
"Creates a Joda-Time Duration object"
([duration] (org.joda.time.Duration. (long duration)))
([start stop] (org.joda.time.Duration. (to-ms-count start) (to-ms-count stop))))
Notice that the second method has two calls to the `to-ms-count` function. This makes is possible to create a duration object using the following inputs:
* java.lang.Long
* java.util.Date
* java.util.Calenedar
* java.sql.Timestamp
* clojure.lang.map
* org.joda.time.DateTime
* org.joda.time.Instant
* org.joda.time.base.BaseDateTime
The `to-ms-count` multimethod now begins to behave like a Java interface, allowing a broad range of inputs.
#Adding/Subtracting Durations
defn add-dur
[input-time duration]
[input-time duration & durations]
defn sub-dur
[input-time duration]
[input-time duration & durations]
These methods
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 | #Date Utilities
<NAME>
June 11, 2009
Namespace: lib.devlinsf.joda-utils
This library is designed to wrap the Joda Time library from clojure. It was inspired by <NAME> work with sequence abstractions.
It depends on `clojure.contrib.str-utils`, `lib.devlinsf.date-utils`, and the Joda-time 1.6 jar.
#Extending to-ms-count
The first thing this library does is add cases the to-ms-count method for the following classes:
defmethod to-ms-count org.joda.time.DateTime
defmethod to-ms-count org.joda.time.Instant
defmethod to-ms-count org.joda.time.base.BaseDateTime
This way there is now a way to convert Joda time data types to standard java data types. Next the following constructor functions
are defining
defn datetime => returns org.joda.time.DateTime
defn instant => returns org.joda.time.Instant
These functions are written in terms of to-ms-count, so that they have the broad range of inputs you'd expect.
#Creating a duration
The next function that is created is a duration constructor. The Joda time library provides two styles of constructors. The first take a long number of ms. The
second implementation takes a start and stop time.
(defn duration
"Creates a Joda-Time Duration object"
([duration] (org.joda.time.Duration. (long duration)))
([start stop] (org.joda.time.Duration. (to-ms-count start) (to-ms-count stop))))
Notice that the second method has two calls to the `to-ms-count` function. This makes is possible to create a duration object using the following inputs:
* java.lang.Long
* java.util.Date
* java.util.Calenedar
* java.sql.Timestamp
* clojure.lang.map
* org.joda.time.DateTime
* org.joda.time.Instant
* org.joda.time.base.BaseDateTime
The `to-ms-count` multimethod now begins to behave like a Java interface, allowing a broad range of inputs.
#Adding/Subtracting Durations
defn add-dur
[input-time duration]
[input-time duration & durations]
defn sub-dur
[input-time duration]
[input-time duration & durations]
These methods add/subtract a duration from any time abstraction that interacts with the `to-ms-count` function, and returns a new DateTime object.
This is the beginnings of a universal time manipulation library. More to come.
|
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 TABLE IF EXISTS `meeseeks` CASCADE;
CREATE TABLE `meeseeks` (
id BIGINT AUTO_INCREMENT,
`name` VARCHAR(255),
purpose VARCHAR(255),
date_activated VARCHAR(255),
PRIMARY KEY (id)
);
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 | DROP TABLE IF EXISTS `meeseeks` CASCADE;
CREATE TABLE `meeseeks` (
id BIGINT AUTO_INCREMENT,
`name` VARCHAR(255),
purpose VARCHAR(255),
date_activated VARCHAR(255),
PRIMARY KEY (id)
); |
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 route_id, route_long_name
FROM akl_transport.routes
where route_long_name = "380 Queen St To Airport Via Mt Eden Rd";
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 route_id, route_long_name
FROM akl_transport.routes
where route_long_name = "380 Queen St To Airport Via Mt Eden Rd"; |
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 dev.fritz2.components
import dev.fritz2.components.data.File
import dev.fritz2.dom.html.Input
import dev.fritz2.dom.html.RenderContext
import dev.fritz2.styling.StyleClass
import dev.fritz2.styling.div
import dev.fritz2.styling.params.BasicParams
import dev.fritz2.styling.params.BoxParams
import dev.fritz2.styling.staticStyle
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import org.w3c.files.FileReader
import org.w3c.files.File as jsFile
/**
* function for reading the [jsFile] to a [File]
* with [File.content] as a [String]
*/
typealias FileReadingStrategy = (jsFile) -> Flow<File>
/**
* This abstract class is the base _configuration_ for file inputs.
* It has two specific implementations:
* - [SingleFileSelectionComponent] for handling one file input
* - [MultiFileSelectionComponent] for handling an arbitrary amount of files
*
* Both specific implementations only differ in their rendering implementation, but share the same configuration
* options, like creating a [button] which has the same options like a [pushButton].
*
* Much more important are the _configuration_ functions. You can configure the following aspects:
* - the [accept](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept) property
* - the [FileReadingStrategy] for interpreting the content of the file
*
* This can be done within a functional expression that is the last parameter of the two files functions, called
* ``build``. It offers an initialized instance of this [FileSelectionBaseComponent] class as receiver, so every mutating
* method can be called for configuring the desired state for rendering the button.
*
* The following example shows the usage ([SingleFileSelectionComponent]):
* ```
* file {
* accept("application/pdf")
* button({
* background { color { info } }
* }) {
* icon { fromTheme { document } }
* text("Ac
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 | 4 | package dev.fritz2.components
import dev.fritz2.components.data.File
import dev.fritz2.dom.html.Input
import dev.fritz2.dom.html.RenderContext
import dev.fritz2.styling.StyleClass
import dev.fritz2.styling.div
import dev.fritz2.styling.params.BasicParams
import dev.fritz2.styling.params.BoxParams
import dev.fritz2.styling.staticStyle
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import org.w3c.files.FileReader
import org.w3c.files.File as jsFile
/**
* function for reading the [jsFile] to a [File]
* with [File.content] as a [String]
*/
typealias FileReadingStrategy = (jsFile) -> Flow<File>
/**
* This abstract class is the base _configuration_ for file inputs.
* It has two specific implementations:
* - [SingleFileSelectionComponent] for handling one file input
* - [MultiFileSelectionComponent] for handling an arbitrary amount of files
*
* Both specific implementations only differ in their rendering implementation, but share the same configuration
* options, like creating a [button] which has the same options like a [pushButton].
*
* Much more important are the _configuration_ functions. You can configure the following aspects:
* - the [accept](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept) property
* - the [FileReadingStrategy] for interpreting the content of the file
*
* This can be done within a functional expression that is the last parameter of the two files functions, called
* ``build``. It offers an initialized instance of this [FileSelectionBaseComponent] class as receiver, so every mutating
* method can be called for configuring the desired state for rendering the button.
*
* The following example shows the usage ([SingleFileSelectionComponent]):
* ```
* file {
* accept("application/pdf")
* button({
* background { color { info } }
* }) {
* icon { fromTheme { document } }
* text("Accept only pdf files")
* }
* }
* ```
*/
abstract class FileSelectionBaseComponent {
companion object {
const val eventName = "loadend"
val inputStyle = staticStyle("file-input", "display: none;")
}
protected var accept: (Input.() -> Unit)? = null
fun accept(value: String) {
accept = { attr("accept", value) }
}
fun accept(value: Flow<String>) {
accept = { attr("accept", value) }
}
val base64: FileReadingStrategy = { file ->
callbackFlow {
val reader = FileReader()
val listener: (Event) -> Unit = { _ ->
var content = reader.result.toString()
val index = content.indexOf("base64,")
if (index > -1) content = content.substring(index + 7)
offer(File(file.name, file.type, file.size.toLong(), content))
}
reader.addEventListener(eventName, listener)
reader.readAsDataURL(file)
awaitClose { reader.removeEventListener(eventName, listener) }
}
}
val plainText: (String) -> FileReadingStrategy = { encoding ->
{ file ->
callbackFlow {
val reader = FileReader()
val listener: (Event) -> Unit = { _ ->
offer(File(file.name, file.type, file.size.toLong(), reader.result.toString()))
}
reader.addEventListener(eventName, listener)
reader.readAsText(file, encoding)
awaitClose { reader.removeEventListener(eventName, listener) }
}
}
}
val fileReadingStrategy = ComponentProperty<FileSelectionBaseComponent.() -> FileReadingStrategy> { base64 }
fun encoding(value: String) {
fileReadingStrategy { plainText(value) }
}
protected var context: RenderContext.(HTMLInputElement) -> Unit = { input ->
pushButton(prefix = "file-button") {
icon { fromTheme { cloudUpload } }
element {
domNode.onclick = {
input.click()
}
}
}
}
open fun button(
styling: BasicParams.() -> Unit = {},
baseClass: StyleClass = StyleClass.None,
id: String? = null,
prefix: String = "file-button",
build: PushButtonComponent.() -> Unit = {}
) {
context = { input ->
pushButton(styling, baseClass, id, prefix) {
build()
element {
domNode.onclick = {
input.click()
}
}
}
}
}
}
/**
* Specific component for handling the upload for one file at once.
*
* For the common configuration options @see [FileSelectionBaseComponent].
*/
open class SingleFileSelectionComponent : FileSelectionBaseComponent(), Component<Flow<File>> {
override fun render(
context: RenderContext,
styling: BoxParams.() -> Unit,
baseClass: StyleClass,
id: String?,
prefix: String
): Flow<File> {
var file: Flow<File>? = null
context.apply {
div({}, styling, baseClass, id, prefix) {
val inputElement = input(inputStyle.name) {
type("file")
[email protected]?.invoke(this)
file = changes.events.mapNotNull {
domNode.files?.item(0)
}.flatMapLatest {
domNode.value = "" // otherwise same file can't get loaded twice
[email protected](this@SingleFileSelectionComponent)(
it
)
}
}.domNode
[email protected](this, inputElement)
}
}
return file!!
}
}
/**
* Specific component for handling the upload for an arbitrary amount of files.
*
* For the common configuration options @see [FileSelectionBaseComponent].
*/
open class MultiFileSelectionComponent : FileSelectionBaseComponent(), Component<Flow<List<File>>> {
override fun render(
context: RenderContext,
styling: BoxParams.() -> Unit,
baseClass: StyleClass,
id: String?,
prefix: String
): Flow<List<File>> {
var files: Flow<List<File>>? = null
context.apply {
div({}, styling, baseClass, id, prefix) {
val inputElement = input(inputStyle.name) {
type("file")
multiple(true)
[email protected]?.invoke(this)
files = changes.events.mapNotNull {
val list = domNode.files
if (list != null) {
buildList {
for (i in 0..list.length) {
val file = list.item(i)
if (file != null) add(
[email protected](this@MultiFileSelectionComponent)(
file
)
)
}
}
} else null
}.flatMapLatest { files ->
domNode.value = "" // otherwise same files can't get loaded twice
combine(files) { it.toList() }
}
}.domNode
[email protected](this, inputElement)
}
}
return files!!
}
}
/**
* This factory generates a single file selection context.
*
* In there you can create a button with a label, an icon, the position of the icon and access its events.
* For a detailed overview about the possible properties of the button component object itself, have a look at
* [PushButtonComponent]
*
* The [File] function then returns a [Flow] of [File] in order
* to combine the [Flow] directly to a fitting _handler_ which accepts a [File]:
* ```
* val textFileStore = object : RootStore<String>("") {
* val upload = handle<File> { _, file -> file.content }
* }
* file {
* accept("text/plain")
* encoding("utf-8")
* button(id = "myFile") {
* text("Select a file")
* }
* } handledBy textFileStore.upload
* ```
*
* @see PushButtonComponent
*
* @param styling a lambda expression for declaring the styling as fritz2's styling DSL
* @param baseClass optional CSS class that should be applied to the element
* @param id the ID of the element
* @param prefix the prefix for the generated CSS class resulting in the form ``$prefix-$hash``
* @param build a lambda expression for setting up the component itself. Details in [PushButtonComponent]
* @return a [Flow] that offers the selected [File]
*/
fun RenderContext.file(
styling: BasicParams.() -> Unit = {},
baseClass: StyleClass = StyleClass.None,
id: String? = null,
prefix: String = "file",
build: FileSelectionBaseComponent.() -> Unit = {}
): Flow<File> = SingleFileSelectionComponent().apply(build).render(this, styling, baseClass, id, prefix)
/**
* This factory generates a multiple file selection context.
*
* In there you can create a button with a label, an icon, the position of the icon and access its events.
* For a detailed overview about the possible properties of the button component object itself, have a look at
* [PushButtonComponent].
*
* The [File] function then returns a [Flow] of a [List] of [File]s in order
* to combine the [Flow] directly to a fitting _handler_ which accepts a [List] of [File]s:
* ```
* val textFileStore = object : RootStore<List<String>>(emptyList()) {
* val upload = handle<List<File>>{ _, files -> files.map { it.content } }
* }
* files {
* accept("text/plain")
* encoding("utf-8")
* button(id = "myFiles") {
* text("Select one or more files")
* }
* } handledBy textFileStore.upload
* ```
* @see PushButtonComponent
*
* @param styling a lambda expression for declaring the styling as fritz2's styling DSL
* @param baseClass optional CSS class that should be applied to the element
* @param id the ID of the element
* @param prefix the prefix for the generated CSS class resulting in the form ``$prefix-$hash``
* @param build a lambda expression for setting up the component itself. Details in [PushButtonComponent]
* @return a [Flow] that offers the selected [File]
*/
fun RenderContext.files(
styling: BasicParams.() -> Unit = {},
baseClass: StyleClass = StyleClass.None,
id: String? = null,
prefix: String = "file",
build: FileSelectionBaseComponent.() -> Unit = {}
): Flow<List<File>> = MultiFileSelectionComponent().apply(build).render(this, styling, baseClass, id, prefix)
|
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 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(std_misc, collections, catch_panic, rand)]
use std::__rand::{thread_rng, Rng};
use std::thread;
use std::collections::BinaryHeap;
use std::cmp;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
// old binaryheap failed this test
//
// Integrity means that all elements are present after a comparison panics,
// even if the order may not be correct.
//
// Destructors must be called exactly once per element.
fn test_integrity() {
#[derive(Eq, PartialEq, Ord, Clone, Debug)]
struct PanicOrd<T>(T, bool);
impl<T> Drop for PanicOrd<T> {
fn drop(&mut self) {
// update global drop count
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
impl<T: PartialOrd> PartialOrd for PanicOrd<T> {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
if self.1 || other.1 {
panic!("Panicking comparison");
}
self.0.partial_cmp(&other.0)
}
}
let mut rng = thread_rng();
const DATASZ: usize = 32;
const NTEST: usize = 10;
// don't use 0 in the data -- we want to catch the zeroed-out case.
let data = (1..DATASZ + 1).collect::<Vec<_>>();
// since it's a fuzzy test, run several tries.
for _ in 0..NTEST {
for i in 1..DATASZ + 1 {
DROP_COUNTER.store(0, Ordering::SeqCst);
let mut panic_ords: Vec<_> = data.iter()
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 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(std_misc, collections, catch_panic, rand)]
use std::__rand::{thread_rng, Rng};
use std::thread;
use std::collections::BinaryHeap;
use std::cmp;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
// old binaryheap failed this test
//
// Integrity means that all elements are present after a comparison panics,
// even if the order may not be correct.
//
// Destructors must be called exactly once per element.
fn test_integrity() {
#[derive(Eq, PartialEq, Ord, Clone, Debug)]
struct PanicOrd<T>(T, bool);
impl<T> Drop for PanicOrd<T> {
fn drop(&mut self) {
// update global drop count
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
impl<T: PartialOrd> PartialOrd for PanicOrd<T> {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
if self.1 || other.1 {
panic!("Panicking comparison");
}
self.0.partial_cmp(&other.0)
}
}
let mut rng = thread_rng();
const DATASZ: usize = 32;
const NTEST: usize = 10;
// don't use 0 in the data -- we want to catch the zeroed-out case.
let data = (1..DATASZ + 1).collect::<Vec<_>>();
// since it's a fuzzy test, run several tries.
for _ in 0..NTEST {
for i in 1..DATASZ + 1 {
DROP_COUNTER.store(0, Ordering::SeqCst);
let mut panic_ords: Vec<_> = data.iter()
.filter(|&&x| x != i)
.map(|&x| PanicOrd(x, false))
.collect();
let panic_item = PanicOrd(i, true);
// heapify the sane items
rng.shuffle(&mut panic_ords);
let heap = Arc::new(Mutex::new(BinaryHeap::from_vec(panic_ords)));
let inner_data;
{
let heap_ref = heap.clone();
// push the panicking item to the heap and catch the panic
let thread_result = thread::catch_panic(move || {
heap.lock().unwrap().push(panic_item);
});
assert!(thread_result.is_err());
// Assert no elements were dropped
let drops = DROP_COUNTER.load(Ordering::SeqCst);
//assert!(drops == 0, "Must not drop items. drops={}", drops);
{
// now fetch the binary heap's data vector
let mutex_guard = match heap_ref.lock() {
Ok(x) => x,
Err(poison) => poison.into_inner(),
};
inner_data = mutex_guard.clone().into_vec();
}
}
let drops = DROP_COUNTER.load(Ordering::SeqCst);
assert_eq!(drops, DATASZ);
let mut data_sorted = inner_data.into_iter().map(|p| p.0).collect::<Vec<_>>();
data_sorted.sort();
assert_eq!(data_sorted, data);
}
}
}
fn main() {
test_integrity();
}
|
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 entities
import (
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
"time"
)
type Base struct {
ID uuid.UUID `gorm:"type:uuid;primary_key;not null" json:"id"`
CreatedAt time.Time `json:"createdAt,string" gorm:"not null"`
UpdatedAt time.Time `json:"updatedAt,string" gorm:"not null"`
}
// BeforeCreate will set a UUID rather than numeric ID.
func (base *Base) BeforeCreate(_ *gorm.DB) (err error) {
base.ID = uuid.NewV4()
return
}
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 | 2 | package entities
import (
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
"time"
)
type Base struct {
ID uuid.UUID `gorm:"type:uuid;primary_key;not null" json:"id"`
CreatedAt time.Time `json:"createdAt,string" gorm:"not null"`
UpdatedAt time.Time `json:"updatedAt,string" gorm:"not null"`
}
// BeforeCreate will set a UUID rather than numeric ID.
func (base *Base) BeforeCreate(_ *gorm.DB) (err error) {
base.ID = uuid.NewV4()
return
}
|
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.example.bookkeeping
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class detail : AppCompatActivity() {
private val itemList = ArrayList<item_detail>()
private val image = arrayOf<Int>(R.drawable.classify_traffic,R.drawable.classify_eat,R.drawable.classify_cloth,R.drawable.classify_edu,R.drawable.classify_game,R.drawable.classify_fruit,R.drawable.classify_doctor,R.drawable.classify_other
,R.drawable.classify_income_wage,R.drawable.classify_income_jiangjin,R.drawable.classify_income_baoxiao,R.drawable.classify_income_jianzhi,R.drawable.classify_income_redpacket,R.drawable.classify_income_stock,R.drawable.classify_income_gift,R.drawable.classify_other)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
var username = intent.getStringExtra("username")
init(username)//初始化
//创建RecyclerView实例
val layoutManager = LinearLayoutManager(this)
val recyle : RecyclerView = findViewById(R.id.detail_show)
recyle.layoutManager = layoutManager
val adapter = itemDetailAdapter(itemList)
recyle.adapter = adapter
}
fun init(user: String?){
//查询数据
val bookKeeping = BookKeepingData(this,"example.db",1)
val db = bookKeeping.writableDatabase
val cursor = db.rawQuery("select * from Detail where username = ?", arrayOf(user))
//读取数据并装入数组
if(cursor.moveToFirst()){
do{
val time = cursor.getLong(cursor.getColumnIndex("time"))
val amount = cursor.getDouble(cursor.getColumnIndex("amount"))
val type = cursor.getInt(cursor.getColumnIndex("type"))
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.example.bookkeeping
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class detail : AppCompatActivity() {
private val itemList = ArrayList<item_detail>()
private val image = arrayOf<Int>(R.drawable.classify_traffic,R.drawable.classify_eat,R.drawable.classify_cloth,R.drawable.classify_edu,R.drawable.classify_game,R.drawable.classify_fruit,R.drawable.classify_doctor,R.drawable.classify_other
,R.drawable.classify_income_wage,R.drawable.classify_income_jiangjin,R.drawable.classify_income_baoxiao,R.drawable.classify_income_jianzhi,R.drawable.classify_income_redpacket,R.drawable.classify_income_stock,R.drawable.classify_income_gift,R.drawable.classify_other)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
var username = intent.getStringExtra("username")
init(username)//初始化
//创建RecyclerView实例
val layoutManager = LinearLayoutManager(this)
val recyle : RecyclerView = findViewById(R.id.detail_show)
recyle.layoutManager = layoutManager
val adapter = itemDetailAdapter(itemList)
recyle.adapter = adapter
}
fun init(user: String?){
//查询数据
val bookKeeping = BookKeepingData(this,"example.db",1)
val db = bookKeeping.writableDatabase
val cursor = db.rawQuery("select * from Detail where username = ?", arrayOf(user))
//读取数据并装入数组
if(cursor.moveToFirst()){
do{
val time = cursor.getLong(cursor.getColumnIndex("time"))
val amount = cursor.getDouble(cursor.getColumnIndex("amount"))
val type = cursor.getInt(cursor.getColumnIndex("type"))
val des = cursor.getString(cursor.getColumnIndex("description"))
itemList.add(item_detail(image[type],amount,des,time))
}while(cursor.moveToNext())
}
cursor.close()
}
} |
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 { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { MaterialModule } from '../../material.module';
import { AuthService } from '../../services/auth.service';
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
@NgModule({
imports: [
CommonModule,
MaterialModule,
Ng4LoadingSpinnerModule
],
declarations: [],
providers: [AuthService]
})
export class LoginModule { }
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 { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { MaterialModule } from '../../material.module';
import { AuthService } from '../../services/auth.service';
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
@NgModule({
imports: [
CommonModule,
MaterialModule,
Ng4LoadingSpinnerModule
],
declarations: [],
providers: [AuthService]
})
export class LoginModule { }
|
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.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EA;
namespace EAcomments
{
public partial class CommentBrowserWindow : UserControl
{
public DataGridView dataGridView { get; set; }
public Repository Repository { get; set; }
public BindingSource bindingSourse { get; set; }
public CommentBrowserWindow()
{
InitializeComponent();
this.bindingSourse = new BindingSource();
this.dataGridView = dataGridView1;
this.state.TrueValue = true;
this.state.FalseValue = false;
}
public void clearWindow()
{
this.dataGridView1.Rows.Clear();
this.dataGridView1.Refresh();
}
// adding existing notes in diagram to comment browser window
public void initExistingNotes(List<Note> notes, Repository Repository)
{
this.Repository = Repository;
foreach (Note n in notes)
{
addItem(n);
}
initCheckBoxes();
}
//inicialization of check boxes
private void initCheckBoxes()
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Note n = (Note)row.DataBoundItem;
foreach(TagValue tv in n.tagValues)
{
if(tv.name.Equals("state"))
{
if(tv.value.Equals("resolved"))
{
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)row.Cells[9];
checkbox.TrueValue = true;
checkbox.Value = checkbox.TrueValue;
}
}
}
}
}
//
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.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EA;
namespace EAcomments
{
public partial class CommentBrowserWindow : UserControl
{
public DataGridView dataGridView { get; set; }
public Repository Repository { get; set; }
public BindingSource bindingSourse { get; set; }
public CommentBrowserWindow()
{
InitializeComponent();
this.bindingSourse = new BindingSource();
this.dataGridView = dataGridView1;
this.state.TrueValue = true;
this.state.FalseValue = false;
}
public void clearWindow()
{
this.dataGridView1.Rows.Clear();
this.dataGridView1.Refresh();
}
// adding existing notes in diagram to comment browser window
public void initExistingNotes(List<Note> notes, Repository Repository)
{
this.Repository = Repository;
foreach (Note n in notes)
{
addItem(n);
}
initCheckBoxes();
}
//inicialization of check boxes
private void initCheckBoxes()
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Note n = (Note)row.DataBoundItem;
foreach(TagValue tv in n.tagValues)
{
if(tv.name.Equals("state"))
{
if(tv.value.Equals("resolved"))
{
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)row.Cells[9];
checkbox.TrueValue = true;
checkbox.Value = checkbox.TrueValue;
}
}
}
}
}
// method called when new note is being added into diagram
public void addItem(Note note)
{
this.bindingSourse.Add(note);
dataGridView1.DataSource = this.bindingSourse;
}
public void updateContent(string lastElementGUID, string currentElementGUID, string updatedContent)
{
int i = 0;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
Note n = (Note)row.DataBoundItem;
// update Row in Comment Browser Window
if(n.GUID.Equals(lastElementGUID))
{
n.content = updatedContent;
}
// select Row in Comment Browser Window
else if (n.GUID.Equals(currentElementGUID))
{
dataGridView1.CurrentRow.Selected = true;
dataGridView1.Rows[i].Selected = true;
}
i++;
}
dataGridView1.Refresh();
dataGridView1.Update();
}
public void deleteElement(string elementGUID)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Note n = (Note)row.DataBoundItem;
if (n.GUID.Equals(elementGUID))
{
dataGridView1.Rows.Remove(row);
}
}
dataGridView1.Refresh();
dataGridView1.Update();
}
// initialize all collumns for browser window
private void initCols()
{
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn col4 = new DataGridViewTextBoxColumn();
col1.HeaderText = "Type";
col1.Name = "noteType";
col2.HeaderText = "Note";
col2.Name = "noteText";
col3.HeaderText = "Diagram";
col3.Name = "inDiagram";
col4.HeaderText = "Package";
col4.Name = "inPackage";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { col1, col2, col3, col4 });
}
// Handles events when clicked on specified Row
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
Note n = (Note)dataGridView1.CurrentRow.DataBoundItem;
MyAddinClass.commentBrowserController.openDiagramWithGUID(n.diagramGUID);
}
private void CommentBrowserControl_VisibleChanged(object sender, EventArgs e)
{
if(!this.Visible)
{
MyAddinClass.commentBrowserController.windowClosed();
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MyAddinClass.commentBrowserController.updateElementState(e, dataGridView1);
}
private void syncButton_Click(object sender, EventArgs e)
{
UpdateController.sync(this.Repository);
}
private void importButton_Click(object sender, EventArgs e)
{
MyAddinClass.importService.ImportFromJSON();
}
private void exportButton_Click(object sender, EventArgs e)
{
MyAddinClass.exportService.exportToJSON();
}
}
}
|
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:
"use strict";
var TestVO_1 = require("./TestVO");
var SimpleInterface_1 = require("./SimpleInterface");
var TestsSprint2b = (function () {
function TestsSprint2b() {
this.tests = [];
}
TestsSprint2b.prototype.issue60_defaultMethodParams = function () {
var ref = "http://noRef";
var func = function (var1, var2, var3) {
if (var1 === void 0) { var1 = 7; }
if (var2 === void 0) { var2 = "13"; }
if (var3 === void 0) { var3 = 17; }
return var1 + parseInt(var2) + var3;
};
var sum = func();
var testVO = new TestVO_1.TestVO(this.issue60_defaultMethodParams, "issue60_defaultMethodParams", ref, 37, sum);
this.tests.push(testVO);
return testVO.isValid;
};
TestsSprint2b.prototype.issue60_defaultMethodParamsInterfaces = function () {
var ref = "http://noRef";
var myClass = new MyClass();
var sum = myClass.myFunction();
var testVO = new TestVO_1.TestVO(this.issue60_defaultMethodParamsInterfaces, "issue60_defaultMethodParamsInterfaces", ref, 37, sum);
this.tests.push(testVO);
return testVO.isValid;
};
TestsSprint2b.prototype.issue61_upCasts = function () {
var ref = "http://noRef";
var myClass = new MySubClass();
if (myClass instanceof SimpleInterface_1.SimpleInterface) {
var myCastedClass = (<SimpleInterface_1.SimpleInterface>myClass );
}
var result:number = myCastedClass.myFunction();
var testVO:TestVO = new TestVO(this.issue61_upCasts, "issue61_upCasts", ref, 37, result);
this.tests.push(testVO);
return testVO.isValid
}
public issue56_staticConstants():boolean
{} ref:string = "http://noRef";
var result:string = TestsSprint2b.MY_STATIC_CONST + String(MySubClass.MY_STATIC_CONST)
var testVO:TestVO = new TestVO(this.issue56_staticConstants, "issue56_staticConstants", ref, "A29", result);
this.tests.push(testVO);
return testVO.i
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 | "use strict";
var TestVO_1 = require("./TestVO");
var SimpleInterface_1 = require("./SimpleInterface");
var TestsSprint2b = (function () {
function TestsSprint2b() {
this.tests = [];
}
TestsSprint2b.prototype.issue60_defaultMethodParams = function () {
var ref = "http://noRef";
var func = function (var1, var2, var3) {
if (var1 === void 0) { var1 = 7; }
if (var2 === void 0) { var2 = "13"; }
if (var3 === void 0) { var3 = 17; }
return var1 + parseInt(var2) + var3;
};
var sum = func();
var testVO = new TestVO_1.TestVO(this.issue60_defaultMethodParams, "issue60_defaultMethodParams", ref, 37, sum);
this.tests.push(testVO);
return testVO.isValid;
};
TestsSprint2b.prototype.issue60_defaultMethodParamsInterfaces = function () {
var ref = "http://noRef";
var myClass = new MyClass();
var sum = myClass.myFunction();
var testVO = new TestVO_1.TestVO(this.issue60_defaultMethodParamsInterfaces, "issue60_defaultMethodParamsInterfaces", ref, 37, sum);
this.tests.push(testVO);
return testVO.isValid;
};
TestsSprint2b.prototype.issue61_upCasts = function () {
var ref = "http://noRef";
var myClass = new MySubClass();
if (myClass instanceof SimpleInterface_1.SimpleInterface) {
var myCastedClass = (<SimpleInterface_1.SimpleInterface>myClass );
}
var result:number = myCastedClass.myFunction();
var testVO:TestVO = new TestVO(this.issue61_upCasts, "issue61_upCasts", ref, 37, result);
this.tests.push(testVO);
return testVO.isValid
}
public issue56_staticConstants():boolean
{} ref:string = "http://noRef";
var result:string = TestsSprint2b.MY_STATIC_CONST + String(MySubClass.MY_STATIC_CONST)
var testVO:TestVO = new TestVO(this.issue56_staticConstants, "issue56_staticConstants", ref, "A29", result);
this.tests.push(testVO);
return testVO.isValid
}
}
class TestVO
{public} func() :Function {} this._func }
private _func :Function;
public get caption() :string {} this._caption }
private _caption :string
public get ref() :string {} this._ref }
private _ref :string;
public get expected() :any {} this._expected }
private _expected :any;
public get result() :any {} this._result }
private _result :any;
public get isValid() :boolean {} this._isValid }
private _isValid :boolean;
public order
constructor(func:Function, caption:string, ref:string, expected:any, result:any){this._func = func}
this._caption = caption;
this._ref = ref;
this._expected = expected;
this._result = result;
this._isValid = expected === result;
}
}
class MyClass implements SimpleInterface{public}(var1:number = 7, var2:string = "13", var3:number = 17):number
{} var1 + parseInt(var2) + var3
}
}
class MySubClass extends MyClass{public} MY_STATIC_CONST:number = 29;
public myVar:number = 7;
}
const loop = new LoopTestsAbstracts()</>);
}
};
TestsSprint2b.MY_STATIC_CONST = "A";
return TestsSprint2b;
}());
exports.TestsSprint2b = TestsSprint2b;
|
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.android.spacework.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.android.spacework.fragments.CartFragment
import com.android.spacework.fragments.HomeFragment
class TabAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
lateinit var returnFragment : Fragment
when (position) {
0 -> {
returnFragment = HomeFragment()
}
1 -> {
returnFragment = CartFragment()
}
}
return returnFragment
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
var ch : CharSequence? = null
when (position) {
0 -> {
ch = "HOME"
}
1 -> {
ch = "CART"
}
}
return ch
}
}
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.android.spacework.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.android.spacework.fragments.CartFragment
import com.android.spacework.fragments.HomeFragment
class TabAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
lateinit var returnFragment : Fragment
when (position) {
0 -> {
returnFragment = HomeFragment()
}
1 -> {
returnFragment = CartFragment()
}
}
return returnFragment
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
var ch : CharSequence? = null
when (position) {
0 -> {
ch = "HOME"
}
1 -> {
ch = "CART"
}
}
return ch
}
} |
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 "layout.html" %}
{% block content %}
<div class="container">
<center>
<h1> The most danceable song is <font color = #2975a7>{{correct6}}</font>. </h1>
<br>
<h5>
<p>You thought the most danceable song was {{answer6}}.</p>
{% if answer6 == correct6 %}
<p> <font color ="green"> You response was correct ! </font></p>
{% else %}
<p> <font color="red"> You were wrong :) </font></p>
{% endif %}
</h5>
<br>
<!-- Spotify player -->
<iframe src="{{ link }}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>
<br>
<br>
<form action="/end">
<button type="submit"> click to end the quizz </button>
</form>
<br>
<br>
</center>
</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 | 4 | {% extends "layout.html" %}
{% block content %}
<div class="container">
<center>
<h1> The most danceable song is <font color = #2975a7>{{correct6}}</font>. </h1>
<br>
<h5>
<p>You thought the most danceable song was {{answer6}}.</p>
{% if answer6 == correct6 %}
<p> <font color ="green"> You response was correct ! </font></p>
{% else %}
<p> <font color="red"> You were wrong :) </font></p>
{% endif %}
</h5>
<br>
<!-- Spotify player -->
<iframe src="{{ link }}" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>
<br>
<br>
<form action="/end">
<button type="submit"> click to end the quizz </button>
</form>
<br>
<br>
</center>
</div>
{% endblock content%}
|
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 { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AddcontrollerPage } from './addcontroller';
@NgModule({
declarations: [
AddcontrollerPage,
],
imports: [
IonicPageModule.forChild(AddcontrollerPage),
],
})
export class AddcontrollerPageModule {}
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 { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AddcontrollerPage } from './addcontroller';
@NgModule({
declarations: [
AddcontrollerPage,
],
imports: [
IonicPageModule.forChild(AddcontrollerPage),
],
})
export class AddcontrollerPageModule {}
|
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::fmt;
#[derive(Debug)]
pub enum Binary {
Short(u8),
TwoOctet(u8),
Long(u8),
}
#[derive(Debug)]
pub enum Integer {
Direct(u8),
Byte(u8),
Short(u8),
Normal,
}
#[derive(Debug)]
pub enum Long {
Direct(u8),
Byte(u8),
Short(u8),
Int32,
Normal,
}
#[derive(Debug)]
pub enum Double {
Zero,
One,
Byte,
Short,
Float,
Normal,
}
#[derive(Debug)]
pub enum Date {
Millisecond,
Minute,
}
#[derive(Debug)]
pub enum List {
VarLength(bool /* typed */),
FixedLength(bool /* typed */),
ShortFixedLength(bool /* typed */, usize /* length */),
}
#[derive(Debug)]
pub enum String {
/// string of length 0-31
Compact(u8),
/// string of length 0-1023
Small(u8),
/// non-final chunk
Chunk,
/// final chunk
FinalChunk,
}
#[derive(Debug)]
pub enum Object {
Compact(u8),
Normal,
}
#[derive(Debug)]
pub enum ByteCodecType {
True,
False,
Null,
Definition,
Object(Object),
Ref,
Int(Integer),
Long(Long),
Double(Double),
Date(Date),
Binary(Binary),
List(List),
Map(bool /*typed*/),
String(String),
Unknown,
}
impl ByteCodecType {
#[inline]
pub fn from(c: u8) -> ByteCodecType {
match c {
b'T' => ByteCodecType::True,
b'F' => ByteCodecType::False,
b'N' => ByteCodecType::Null,
0x51 => ByteCodecType::Ref,
// Map
b'M' => ByteCodecType::Map(true),
b'H' => ByteCodecType::Map(false),
// List
0x55 => ByteCodecType::List(List::VarLength(true)),
b'V' => ByteCodecType::List(List::FixedLength(true)),
0x57 => ByteCodecType::List(List::VarLength(false)),
0x58 => ByteCodecType::List(List::FixedLength(false)),
0x70..=0x77 => ByteCodecType::List(List::ShortFixedLength(true, (c - 0x70) as usize)),
0x78..=0x7f => ByteCodecType::List(List::ShortFixed
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 std::fmt;
#[derive(Debug)]
pub enum Binary {
Short(u8),
TwoOctet(u8),
Long(u8),
}
#[derive(Debug)]
pub enum Integer {
Direct(u8),
Byte(u8),
Short(u8),
Normal,
}
#[derive(Debug)]
pub enum Long {
Direct(u8),
Byte(u8),
Short(u8),
Int32,
Normal,
}
#[derive(Debug)]
pub enum Double {
Zero,
One,
Byte,
Short,
Float,
Normal,
}
#[derive(Debug)]
pub enum Date {
Millisecond,
Minute,
}
#[derive(Debug)]
pub enum List {
VarLength(bool /* typed */),
FixedLength(bool /* typed */),
ShortFixedLength(bool /* typed */, usize /* length */),
}
#[derive(Debug)]
pub enum String {
/// string of length 0-31
Compact(u8),
/// string of length 0-1023
Small(u8),
/// non-final chunk
Chunk,
/// final chunk
FinalChunk,
}
#[derive(Debug)]
pub enum Object {
Compact(u8),
Normal,
}
#[derive(Debug)]
pub enum ByteCodecType {
True,
False,
Null,
Definition,
Object(Object),
Ref,
Int(Integer),
Long(Long),
Double(Double),
Date(Date),
Binary(Binary),
List(List),
Map(bool /*typed*/),
String(String),
Unknown,
}
impl ByteCodecType {
#[inline]
pub fn from(c: u8) -> ByteCodecType {
match c {
b'T' => ByteCodecType::True,
b'F' => ByteCodecType::False,
b'N' => ByteCodecType::Null,
0x51 => ByteCodecType::Ref,
// Map
b'M' => ByteCodecType::Map(true),
b'H' => ByteCodecType::Map(false),
// List
0x55 => ByteCodecType::List(List::VarLength(true)),
b'V' => ByteCodecType::List(List::FixedLength(true)),
0x57 => ByteCodecType::List(List::VarLength(false)),
0x58 => ByteCodecType::List(List::FixedLength(false)),
0x70..=0x77 => ByteCodecType::List(List::ShortFixedLength(true, (c - 0x70) as usize)),
0x78..=0x7f => ByteCodecType::List(List::ShortFixedLength(false, (c - 0x78) as usize)),
b'O' => ByteCodecType::Object(Object::Normal),
0x60..=0x6f => ByteCodecType::Object(Object::Compact(c)),
b'C' => ByteCodecType::Definition,
// Integer
0x80..=0xbf => ByteCodecType::Int(Integer::Direct(c)),
0xc0..=0xcf => ByteCodecType::Int(Integer::Byte(c)),
0xd0..=0xd7 => ByteCodecType::Int(Integer::Short(c)),
b'I' => ByteCodecType::Int(Integer::Normal),
// Long
0xd8..=0xef => ByteCodecType::Long(Long::Direct(c)),
0xf0..=0xff => ByteCodecType::Long(Long::Byte(c)),
0x38..=0x3f => ByteCodecType::Long(Long::Short(c)),
0x59 => ByteCodecType::Long(Long::Int32),
b'L' => ByteCodecType::Long(Long::Normal),
// Double
0x5b => ByteCodecType::Double(Double::Zero),
0x5c => ByteCodecType::Double(Double::One),
0x5d => ByteCodecType::Double(Double::Byte),
0x5e => ByteCodecType::Double(Double::Short),
0x5f => ByteCodecType::Double(Double::Float),
b'D' => ByteCodecType::Double(Double::Normal),
// Date
0x4a => ByteCodecType::Date(Date::Millisecond),
0x4b => ByteCodecType::Date(Date::Minute),
// Binary
0x20..=0x2f => ByteCodecType::Binary(Binary::Short(c)),
0x34..=0x37 => ByteCodecType::Binary(Binary::TwoOctet(c)),
b'B' | 0x41 => ByteCodecType::Binary(Binary::Long(c)),
// String
// ::= [x00-x1f] <utf8-data> # string of length 0-31
0x00..=0x1f => ByteCodecType::String(String::Compact(c)),
// ::= [x30-x34] <utf8-data> # string of length 0-1023
0x30..=0x33 => ByteCodecType::String(String::Small(c)),
// x52 ('R') represents any non-final chunk
0x52 => ByteCodecType::String(String::Chunk),
// x53 ('S') represents the final chunk
b'S' => ByteCodecType::String(String::FinalChunk),
_ => ByteCodecType::Unknown,
}
}
}
impl fmt::Display for ByteCodecType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ByteCodecType::Int(_) => write!(f, "int"),
ByteCodecType::Long(_) => write!(f, "long"),
ByteCodecType::Double(_) => write!(f, "double"),
ByteCodecType::Date(_) => write!(f, "date"),
ByteCodecType::Binary(_) => write!(f, "binary"),
ByteCodecType::String(_) => write!(f, "string"),
ByteCodecType::List(_) => write!(f, "list"),
ByteCodecType::Map(_) => write!(f, "map"),
ByteCodecType::True | ByteCodecType::False => write!(f, "bool"),
ByteCodecType::Null => write!(f, "null"),
ByteCodecType::Definition => write!(f, "definition"),
ByteCodecType::Ref => write!(f, "ref"),
ByteCodecType::Object(_) => write!(f, "object"),
ByteCodecType::Unknown => write!(f, "unknown"),
}
}
}
|
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:
#[doc = "Register `FILTER` reader"]
pub struct R(crate::R<FILTER_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<FILTER_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<FILTER_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<FILTER_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `FILTER` writer"]
pub struct W(crate::W<FILTER_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<FILTER_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<FILTER_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<FILTER_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `CH0FVAL` reader - Channel 0 Filter Value"]
pub struct CH0FVAL_R(crate::FieldReader<u8, u8>);
impl CH0FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH0FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH0FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH0FVAL` writer - Channel 0 Filter Value"]
pub struct CH0FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH0FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f);
self.w
}
}
#[doc = "Field `CH1FVAL` reader - Channel 1 Filter Value"]
pub struct CH1FVAL_R(crate::FieldReader<u8, u8>);
impl CH1FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH1FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH1FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.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>"
| rust | 2 | #[doc = "Register `FILTER` reader"]
pub struct R(crate::R<FILTER_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<FILTER_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<FILTER_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<FILTER_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `FILTER` writer"]
pub struct W(crate::W<FILTER_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<FILTER_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<FILTER_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<FILTER_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `CH0FVAL` reader - Channel 0 Filter Value"]
pub struct CH0FVAL_R(crate::FieldReader<u8, u8>);
impl CH0FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH0FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH0FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH0FVAL` writer - Channel 0 Filter Value"]
pub struct CH0FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH0FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f);
self.w
}
}
#[doc = "Field `CH1FVAL` reader - Channel 1 Filter Value"]
pub struct CH1FVAL_R(crate::FieldReader<u8, u8>);
impl CH1FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH1FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH1FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH1FVAL` writer - Channel 1 Filter Value"]
pub struct CH1FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH1FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | ((value as u32 & 0x0f) << 4);
self.w
}
}
#[doc = "Field `CH2FVAL` reader - Channel 2 Filter Value"]
pub struct CH2FVAL_R(crate::FieldReader<u8, u8>);
impl CH2FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH2FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH2FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH2FVAL` writer - Channel 2 Filter Value"]
pub struct CH2FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH2FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8);
self.w
}
}
#[doc = "Field `CH3FVAL` reader - Channel 3 Filter Value"]
pub struct CH3FVAL_R(crate::FieldReader<u8, u8>);
impl CH3FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH3FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH3FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH3FVAL` writer - Channel 3 Filter Value"]
pub struct CH3FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH3FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 12)) | ((value as u32 & 0x0f) << 12);
self.w
}
}
#[doc = "Field `CH4FVAL` reader - Channel 4 Filter Value"]
pub struct CH4FVAL_R(crate::FieldReader<u8, u8>);
impl CH4FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH4FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH4FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH4FVAL` writer - Channel 4 Filter Value"]
pub struct CH4FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH4FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16);
self.w
}
}
#[doc = "Field `CH5FVAL` reader - Channel 5 Filter Value"]
pub struct CH5FVAL_R(crate::FieldReader<u8, u8>);
impl CH5FVAL_R {
pub(crate) fn new(bits: u8) -> Self {
CH5FVAL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CH5FVAL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CH5FVAL` writer - Channel 5 Filter Value"]
pub struct CH5FVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CH5FVAL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 20)) | ((value as u32 & 0x0f) << 20);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Channel 0 Filter Value"]
#[inline(always)]
pub fn ch0fval(&self) -> CH0FVAL_R {
CH0FVAL_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - Channel 1 Filter Value"]
#[inline(always)]
pub fn ch1fval(&self) -> CH1FVAL_R {
CH1FVAL_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - Channel 2 Filter Value"]
#[inline(always)]
pub fn ch2fval(&self) -> CH2FVAL_R {
CH2FVAL_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - Channel 3 Filter Value"]
#[inline(always)]
pub fn ch3fval(&self) -> CH3FVAL_R {
CH3FVAL_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - Channel 4 Filter Value"]
#[inline(always)]
pub fn ch4fval(&self) -> CH4FVAL_R {
CH4FVAL_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - Channel 5 Filter Value"]
#[inline(always)]
pub fn ch5fval(&self) -> CH5FVAL_R {
CH5FVAL_R::new(((self.bits >> 20) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - Channel 0 Filter Value"]
#[inline(always)]
pub fn ch0fval(&mut self) -> CH0FVAL_W {
CH0FVAL_W { w: self }
}
#[doc = "Bits 4:7 - Channel 1 Filter Value"]
#[inline(always)]
pub fn ch1fval(&mut self) -> CH1FVAL_W {
CH1FVAL_W { w: self }
}
#[doc = "Bits 8:11 - Channel 2 Filter Value"]
#[inline(always)]
pub fn ch2fval(&mut self) -> CH2FVAL_W {
CH2FVAL_W { w: self }
}
#[doc = "Bits 12:15 - Channel 3 Filter Value"]
#[inline(always)]
pub fn ch3fval(&mut self) -> CH3FVAL_W {
CH3FVAL_W { w: self }
}
#[doc = "Bits 16:19 - Channel 4 Filter Value"]
#[inline(always)]
pub fn ch4fval(&mut self) -> CH4FVAL_W {
CH4FVAL_W { w: self }
}
#[doc = "Bits 20:23 - Channel 5 Filter Value"]
#[inline(always)]
pub fn ch5fval(&mut self) -> CH5FVAL_W {
CH5FVAL_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Filter Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [filter](index.html) module"]
pub struct FILTER_SPEC;
impl crate::RegisterSpec for FILTER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [filter::R](R) reader structure"]
impl crate::Readable for FILTER_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [filter::W](W) writer structure"]
impl crate::Writable for FILTER_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets FILTER to value 0"]
impl crate::Resettable for FILTER_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
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:
use crate::{data::Percentile, receiver::Receiver};
use std::{fmt::Display, hash::Hash, marker::PhantomData, time::Duration};
/// A configuration builder for [`Receiver`].
#[derive(Clone)]
pub struct Configuration<T> {
metric_type: PhantomData<T>,
pub(crate) capacity: usize,
pub(crate) batch_size: usize,
pub(crate) histogram_window: Duration,
pub(crate) histogram_granularity: Duration,
pub(crate) percentiles: Vec<Percentile>,
}
impl<T> Default for Configuration<T> {
fn default() -> Configuration<T> {
Configuration {
metric_type: PhantomData::<T>,
capacity: 512,
batch_size: 64,
histogram_window: Duration::from_secs(10),
histogram_granularity: Duration::from_secs(1),
percentiles: default_percentiles(),
}
}
}
impl<T: Send + Eq + Hash + Display + Clone> Configuration<T> {
/// Creates a new [`Configuration`] with default values.
pub fn new() -> Configuration<T> { Default::default() }
/// Sets the buffer capacity.
///
/// Defaults to 512.
///
/// This controls the size of the channel used to send metrics. This channel is shared amongst
/// all active sinks. If this channel is full when sending a metric, that send will be blocked
/// until the channel has free space.
///
/// Tweaking this value allows for a trade-off between low memory consumption and throughput
/// burst capabilities. By default, we expect samples to occupy approximately 64 bytes. Thus,
/// at our default value, we preallocate roughly ~32KB.
///
/// Generally speaking, sending and processing metrics is fast enough that the default value of
/// 4096 supports millions of samples per second.
pub fn capacity(mut self, capacity: usize) -> Self {
self.capacity = capacity;
self
}
/// Sets the batch size.
///
/// Defaults to 64.
///
/// This controls the size of message batches tha
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 crate::{data::Percentile, receiver::Receiver};
use std::{fmt::Display, hash::Hash, marker::PhantomData, time::Duration};
/// A configuration builder for [`Receiver`].
#[derive(Clone)]
pub struct Configuration<T> {
metric_type: PhantomData<T>,
pub(crate) capacity: usize,
pub(crate) batch_size: usize,
pub(crate) histogram_window: Duration,
pub(crate) histogram_granularity: Duration,
pub(crate) percentiles: Vec<Percentile>,
}
impl<T> Default for Configuration<T> {
fn default() -> Configuration<T> {
Configuration {
metric_type: PhantomData::<T>,
capacity: 512,
batch_size: 64,
histogram_window: Duration::from_secs(10),
histogram_granularity: Duration::from_secs(1),
percentiles: default_percentiles(),
}
}
}
impl<T: Send + Eq + Hash + Display + Clone> Configuration<T> {
/// Creates a new [`Configuration`] with default values.
pub fn new() -> Configuration<T> { Default::default() }
/// Sets the buffer capacity.
///
/// Defaults to 512.
///
/// This controls the size of the channel used to send metrics. This channel is shared amongst
/// all active sinks. If this channel is full when sending a metric, that send will be blocked
/// until the channel has free space.
///
/// Tweaking this value allows for a trade-off between low memory consumption and throughput
/// burst capabilities. By default, we expect samples to occupy approximately 64 bytes. Thus,
/// at our default value, we preallocate roughly ~32KB.
///
/// Generally speaking, sending and processing metrics is fast enough that the default value of
/// 4096 supports millions of samples per second.
pub fn capacity(mut self, capacity: usize) -> Self {
self.capacity = capacity;
self
}
/// Sets the batch size.
///
/// Defaults to 64.
///
/// This controls the size of message batches that we collect for processing. The only real
/// reason to tweak this is to control the latency from the sender side. Larger batches lower
/// the ingest latency in the face of high metric ingest pressure at the cost of higher tail
/// latencies.
///
/// Long story short, you shouldn't need to change this, but it's here if you really do.
pub fn batch_size(mut self, batch_size: usize) -> Self {
self.batch_size = batch_size;
self
}
/// Sets the histogram configuration.
///
/// Defaults to a 10 second window with 1 second granularity.
///
/// This controls how long of a time frame the histogram will track, on a rolling window.
/// We'll create enough underlying histogram buckets so that we have (window / granularity)
/// buckets, and every interval that passes (granularity), we'll add a new bucket and drop the
/// oldest one, thereby providing a rolling window.
///
/// Histograms, under the hood, are hard-coded to track three significant digits, and will take
/// a theoretical maximum of around 60KB per bucket, so a single histogram metric with the
/// default window/granularity will take a maximum of around 600KB.
///
/// In practice, this should be much smaller based on the maximum values pushed into the
/// histogram, as the underlying histogram storage is automatically resized on the fly.
pub fn histogram(mut self, window: Duration, granularity: Duration) -> Self {
self.histogram_window = window;
self.histogram_granularity = granularity;
self
}
/// Sets the default percentiles for histograms.
///
/// Defaults to min/p50/p95/p99/p999/max.
///
/// This controls the percentiles we extract from histograms when taking a snapshot.
/// Percentiles are represented in metrics as pXXX, where XXX is the percentile i.e. p99 is
/// 99.0, p999 is 99.9, etc. min and max are 0.0 and 100.0, respectively.
pub fn percentiles(mut self, percentiles: &[f64]) -> Self {
self.percentiles = percentiles.iter().cloned().map(Percentile::from).collect();
self
}
/// Create a [`Receiver`] based on this configuration.
pub fn build(self) -> Receiver<T> { Receiver::from_config(self) }
}
/// A default set of percentiles that should support most use cases.
fn default_percentiles() -> Vec<Percentile> {
let mut p = Vec::new();
p.push(Percentile::from(0.0));
p.push(Percentile::from(50.0));
p.push(Percentile::from(95.0));
p.push(Percentile::from(99.0));
p.push(Percentile::from(99.9));
p.push(Percentile::from(100.0));
p
}
|
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::net::SocketAddr;
use std::result::Result::Ok;
use futures_util::{future, pin_mut, SinkExt, StreamExt};
use log::*;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync;
use tokio_socketcan::{CANFrame, CANSocket};
use tokio_tungstenite::tungstenite::Message;
use can::CanFrame;
mod can;
type Sender<T = CANFrame> = sync::mpsc::Sender<T>;
type Receiver<T = CANFrame> = sync::mpsc::Receiver<T>;
async fn handle_ws_connection(
raw_stream: TcpStream,
addr: SocketAddr,
in_tx: &Sender,
mut out_rx: Receiver,
) {
info!("Incoming TCP connection from: {}", addr);
let stream = tokio_tungstenite::accept_async(raw_stream)
.await
.expect("Error during the websocket handshake occurred");
info!("WebSocket connection established: {}", addr);
let (mut outgoing, incoming) = stream.split();
let ws_receiver = incoming.for_each(|msg| async move {
match msg {
Ok(msg) => {
if let Ok(msg) = msg.to_text() {
if let Ok(can_frame) = CanFrame::from_json(msg) {
info!("WS(in): {}", msg);
if let Err(e) = in_tx.clone().send(can_frame.to_linux_frame()).await {
error!(
"Error occurred while sending frame from WS to CAN channel: {:?}",
e
);
}
} else {
error!("Couldn't parse received can frame json: {}", msg);
}
}
}
Err(e) => {
error!("Error occurred while WS receiving a message: {:?}", e);
}
}
});
let ws_transmitter = tokio::spawn(async move {
while let Some(f) = out_rx.recv().await {
let j = CanFrame::from_linux_frame(f).to_json();
info!("WS(out): {}", j);
let msg = Message::Text(j);
if le
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::net::SocketAddr;
use std::result::Result::Ok;
use futures_util::{future, pin_mut, SinkExt, StreamExt};
use log::*;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync;
use tokio_socketcan::{CANFrame, CANSocket};
use tokio_tungstenite::tungstenite::Message;
use can::CanFrame;
mod can;
type Sender<T = CANFrame> = sync::mpsc::Sender<T>;
type Receiver<T = CANFrame> = sync::mpsc::Receiver<T>;
async fn handle_ws_connection(
raw_stream: TcpStream,
addr: SocketAddr,
in_tx: &Sender,
mut out_rx: Receiver,
) {
info!("Incoming TCP connection from: {}", addr);
let stream = tokio_tungstenite::accept_async(raw_stream)
.await
.expect("Error during the websocket handshake occurred");
info!("WebSocket connection established: {}", addr);
let (mut outgoing, incoming) = stream.split();
let ws_receiver = incoming.for_each(|msg| async move {
match msg {
Ok(msg) => {
if let Ok(msg) = msg.to_text() {
if let Ok(can_frame) = CanFrame::from_json(msg) {
info!("WS(in): {}", msg);
if let Err(e) = in_tx.clone().send(can_frame.to_linux_frame()).await {
error!(
"Error occurred while sending frame from WS to CAN channel: {:?}",
e
);
}
} else {
error!("Couldn't parse received can frame json: {}", msg);
}
}
}
Err(e) => {
error!("Error occurred while WS receiving a message: {:?}", e);
}
}
});
let ws_transmitter = tokio::spawn(async move {
while let Some(f) = out_rx.recv().await {
let j = CanFrame::from_linux_frame(f).to_json();
info!("WS(out): {}", j);
let msg = Message::Text(j);
if let Err(e) = outgoing.send(msg).await {
error!("Error occurred while sending WS message: {:?}", e);
}
}
});
pin_mut!(ws_receiver, ws_transmitter);
future::select(ws_receiver, ws_transmitter).await;
info!("WS disconnected!");
}
async fn start_ws(addr: &str, in_tx: &Sender, out_rx: Receiver) {
let listener = TcpListener::bind(addr)
.await
.expect(&format!("Can't bind websocket address {}", addr));
info!("Listening on: {}", addr);
if let Ok((stream, addr)) = listener.accept().await {
handle_ws_connection(stream, addr, &in_tx, out_rx).await;
}
}
async fn start_can(can_addr: &str, out_tx: &Sender, mut in_rx: Receiver) {
let can_socket = CANSocket::open(&can_addr).unwrap();
let (mut outgoing, incoming) = can_socket.split();
let can_receiver = incoming.for_each(|msg| async move {
match msg {
Ok(msg) => {
info!("CAN(in): {:?}", msg);
if let Err(e) = out_tx.clone().send(msg).await {
error!(
"Error occurred while sending frame from CAN to WS channel: {:?}",
e
);
}
}
Err(e) => {
error!("Error occurred while CAN receiving a message: {:?}", e);
}
}
});
let can_transmitter = tokio::spawn(async move {
while let Some(frame) = in_rx.recv().await {
info!("CAN(out): {:?}", frame);
if let Err(e) = outgoing.send(frame).await {
error!("Error occurred while sending CAN frame: {:?}", e);
}
}
});
if let (Err(e), _) = tokio::join!(can_transmitter, can_receiver) {
error!("Error occurred in can_transmitter task: {:?}", e);
}
}
/// (in_tx , in_rx ) = sync::mpsc::channel();
/// (out_tx , out_rx) = sync::mpsc::channel();
/// -> in_tx ----> in_rx ->
/// WS CAN
/// <- out_tx <---- out_rx <-
pub async fn run(ws_addr: &str, can_addr: &str) -> Result<(), Box<dyn std::error::Error>> {
let (in_tx, in_rx) = sync::mpsc::channel(100);
let (out_tx, out_rx) = sync::mpsc::channel(100);
let ws = start_ws(&ws_addr, &in_tx, out_rx);
let can = start_can(&can_addr, &out_tx, in_rx);
tokio::join!(ws, can);
Ok(())
}
|
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:
//
// PullRequestListViewController.swift
// GitHubApp
//
// Created by <NAME> on 30/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
final class PullRequestListViewController: UIViewController {
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .clear
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 160
tableView.allowsSelection = false
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(PullRequestListViewCell.self, forCellReuseIdentifier: PullRequestListViewCell.identifier)
return tableView
}()
private lazy var emptyMessageLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
label.numberOfLines = 0
label.textAlignment = .center
label.textColor = UIColor(hexadecimal: 0x628FB8)
label.text = "No Pull Requests created"
label.accessibilityLanguage = "en-US"
label.alpha = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var presenter: PullRequestListPresenter?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
self.setupUI()
self.loadPullRequests()
}
}
// MARK: - UITableViewDataSource
extension PullRequestListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let presenter = self.presenter else {
return 0
}
return presenter.pullRequests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: PullRequestListViewCell.ident
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 | //
// PullRequestListViewController.swift
// GitHubApp
//
// Created by <NAME> on 30/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
final class PullRequestListViewController: UIViewController {
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .clear
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 160
tableView.allowsSelection = false
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(PullRequestListViewCell.self, forCellReuseIdentifier: PullRequestListViewCell.identifier)
return tableView
}()
private lazy var emptyMessageLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
label.numberOfLines = 0
label.textAlignment = .center
label.textColor = UIColor(hexadecimal: 0x628FB8)
label.text = "No Pull Requests created"
label.accessibilityLanguage = "en-US"
label.alpha = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var presenter: PullRequestListPresenter?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
self.setupUI()
self.loadPullRequests()
}
}
// MARK: - UITableViewDataSource
extension PullRequestListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let presenter = self.presenter else {
return 0
}
return presenter.pullRequests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: PullRequestListViewCell.identifier, for: indexPath) as? PullRequestListViewCell else {
fatalError("Couldn't dequeue \(PullRequestListViewCell.identifier)")
}
guard let presenter = self.presenter else {
fatalError("Present can't be nil")
}
let pullRequest = presenter.pullRequests[indexPath.row]
cell.bind(model: pullRequest)
return cell
}
}
// MARK: - PullRequestListViewProtocol
extension PullRequestListViewController: PullRequestListViewProtocol {
func showLoading() {
self.showActivityIndicator()
}
func hideLoading() {
self.hideActivityIndicator()
}
func showEmptyMessage() {
UIView.animate(withDuration: 0.2, animations: {
self.tableView.alpha = 0
self.emptyMessageLabel.alpha = 1
}, completion: nil)
}
func reloadTableView() {
UIView.transition(with: self.tableView, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
})
}
func showAlertError(title: String, message: String, buttonTitle: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - Private methods
extension PullRequestListViewController {
fileprivate func loadPullRequests() {
guard let presenter = self.presenter else {
fatalError("Presenter can't be nil")
}
presenter.loadPullRequests()
self.title = presenter.repository
}
fileprivate func setupUI() {
view.addSubview(self.tableView)
view.addSubview(self.emptyMessageLabel)
NSLayoutConstraint.activate([
self.tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
self.tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
self.tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
self.tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
NSLayoutConstraint.activate([
self.emptyMessageLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
self.emptyMessageLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
self.emptyMessageLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
self.emptyMessageLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
}
}
|
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 clap::{ App, Arg };
use std::path::Path;
use std::fs::File;
use std::io::{BufReader};
use std::collections::HashMap;
use serde::Deserialize;
use std::error::Error;
use serde_json;
use csv;
#[derive(Deserialize, Clone, PartialEq)]
enum Sides {
Red,
Blue,
}
#[derive(Deserialize, Clone, PartialEq)]
enum Leagues {
LFL,
LCS,
LCK,
LPL,
LEC,
CK,
VCS,
LJL,
}
#[derive(Deserialize, Clone)]
enum Constraint {
Team(String),
GameResult(bool),
Side(Sides),
League(Leagues),
}
#[derive(Deserialize, Clone, Copy, Debug)]
enum Stats {
Kills,
Deaths,
GoldDiff10,
GoldDiff15,
Barons,
FirstBaron,
Dragons,
FirstDragon,
Towers,
FirstTower,
}
#[derive(Deserialize, Clone)]
struct Query {
constraints: Vec<Constraint>,
stats: Vec<Stats>,
}
type PlayerData = HashMap<String, String>;
#[derive(Debug, Clone)]
struct TeamData {
name: String,
data: HashMap<String, String>,
}
type GameID = String;
type GameData = (TeamData, Option<TeamData>);
type Games = HashMap<GameID, GameData>;
enum MergeType {
And,
Or,
IntSum,
NoOp,
}
fn get_player_data_game_id(player_data: &PlayerData) -> &str {
player_data.get("gameid").unwrap()
}
fn get_player_data_team(player_data: &PlayerData) -> &str {
player_data.get("team").unwrap()
}
fn player_row_to_player_data(player_row: &csv::StringRecord, header_legend: &HashMap<String, usize>) -> PlayerData {
let mut player_data = PlayerData::new();
for (attribute, index) in header_legend {
let player_value = match player_row.get(*index) {
Some(v) => v,
None => continue
};
player_data.insert(attribute.clone(), player_value.to_string());
}
player_data
}
fn player_data_to_team_data(player_data: PlayerData) -> TeamData {
TeamData {
name: player_data.get("team").unwrap().clone(),
data: player_data
}
}
fn add_player_row_to_games(games: &mut Games, p
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 clap::{ App, Arg };
use std::path::Path;
use std::fs::File;
use std::io::{BufReader};
use std::collections::HashMap;
use serde::Deserialize;
use std::error::Error;
use serde_json;
use csv;
#[derive(Deserialize, Clone, PartialEq)]
enum Sides {
Red,
Blue,
}
#[derive(Deserialize, Clone, PartialEq)]
enum Leagues {
LFL,
LCS,
LCK,
LPL,
LEC,
CK,
VCS,
LJL,
}
#[derive(Deserialize, Clone)]
enum Constraint {
Team(String),
GameResult(bool),
Side(Sides),
League(Leagues),
}
#[derive(Deserialize, Clone, Copy, Debug)]
enum Stats {
Kills,
Deaths,
GoldDiff10,
GoldDiff15,
Barons,
FirstBaron,
Dragons,
FirstDragon,
Towers,
FirstTower,
}
#[derive(Deserialize, Clone)]
struct Query {
constraints: Vec<Constraint>,
stats: Vec<Stats>,
}
type PlayerData = HashMap<String, String>;
#[derive(Debug, Clone)]
struct TeamData {
name: String,
data: HashMap<String, String>,
}
type GameID = String;
type GameData = (TeamData, Option<TeamData>);
type Games = HashMap<GameID, GameData>;
enum MergeType {
And,
Or,
IntSum,
NoOp,
}
fn get_player_data_game_id(player_data: &PlayerData) -> &str {
player_data.get("gameid").unwrap()
}
fn get_player_data_team(player_data: &PlayerData) -> &str {
player_data.get("team").unwrap()
}
fn player_row_to_player_data(player_row: &csv::StringRecord, header_legend: &HashMap<String, usize>) -> PlayerData {
let mut player_data = PlayerData::new();
for (attribute, index) in header_legend {
let player_value = match player_row.get(*index) {
Some(v) => v,
None => continue
};
player_data.insert(attribute.clone(), player_value.to_string());
}
player_data
}
fn player_data_to_team_data(player_data: PlayerData) -> TeamData {
TeamData {
name: player_data.get("team").unwrap().clone(),
data: player_data
}
}
fn add_player_row_to_games(games: &mut Games, player_row: &csv::StringRecord, header_legend: &HashMap<String, usize>) {
let player_data = player_row_to_player_data(player_row, header_legend);
let game_id = get_player_data_game_id(&player_data).to_string();
let team_data = player_data_to_team_data(player_data.clone());
let player_team = get_player_data_team(&player_data);
match games.get_mut(&game_id) {
Some(teams) => {
if teams.0.name == player_team {
merge_player_data_into_team(&mut teams.0, &player_data);
} else {
teams.1 = Some(team_data);
}
},
None => {
games.insert(game_id, (team_data, None));
}
};
}
fn or_merge_values(a: &str, b: &str) -> String {
if a == "1" || b == "1" {
return "1".to_string();
}
"0".to_string()
}
fn and_merge_values(a: &str, b: &str) -> String {
if a == "1" && b == "1" {
return "1".to_string();
}
"0".to_string()
}
fn int_sum_merge_values(a: &str, b: &str) -> String {
let a_int: i32 = str::parse(a).unwrap();
let b_int: i32 = str::parse(b).unwrap();
return (a_int + b_int).to_string();
}
fn op_merge_player_data_into_team(team_data: &mut TeamData, player_data: PlayerData, attribute: &String, op: &impl Fn(&str, &str) -> String) {
let team_attribute = match team_data.data.get(attribute) {
Some(v) => v.as_str(),
None => ""
};
let player_attribute = match player_data.get(attribute) {
Some(v) => v.as_str(),
None => ""
};
let new = op(team_attribute, player_attribute);
team_data.data.insert(attribute.clone(), new);
}
fn or_merge_player_data_into_team(team_data: &mut TeamData, player_data: PlayerData, attribute: &String) {
op_merge_player_data_into_team(team_data, player_data, attribute, &or_merge_values);
}
fn int_sum_merge_player_data_into_team(team_data: &mut TeamData, player_data: PlayerData, attribute: &String) {
op_merge_player_data_into_team(team_data, player_data, attribute, &int_sum_merge_values);
}
fn get_merge_type_of_attribute(attribute: &str) -> MergeType {
match attribute {
"firstbaron" => MergeType::Or,
"firstblood" => MergeType::Or,
"firsttower" => MergeType::Or,
"kills" => MergeType::IntSum,
"towers" => MergeType::IntSum,
"barons" => MergeType::IntSum,
"deaths" => MergeType::IntSum,
"dragons" => MergeType::IntSum,
"golddiffat10" => MergeType::IntSum,
"golddiffat15" => MergeType::IntSum,
_ => MergeType::NoOp,
}
}
fn merge_attributes(a: &str, b: &str, merge_type: MergeType) -> String {
match merge_type {
MergeType::Or => or_merge_values(a, b),
MergeType::IntSum => int_sum_merge_values(a, b),
MergeType::And => and_merge_values(a, b),
MergeType::NoOp => a.to_string(),
}
}
fn merge_player_data_into_team(team_data: &mut TeamData, player_data: &PlayerData) {
let merge_attributes = vec!["firstblood"];
for attribute in merge_attributes.iter() {
let merge_type = get_merge_type_of_attribute(attribute);
match merge_type {
MergeType::Or => or_merge_player_data_into_team(team_data, player_data.clone(), &attribute.to_string()),
MergeType::IntSum => int_sum_merge_player_data_into_team(team_data, player_data.clone(), &attribute.to_string()),
MergeType::NoOp => (),
_ => ()
}
}
}
fn header_row_to_legend(header_row: csv::StringRecord) -> HashMap<String, usize> {
let mut result = HashMap::new();
for (index, attribute) in header_row.into_iter().enumerate() {
result.insert(attribute.to_string(), index);
}
result
}
fn get_query_from_path(path: &Path) -> Result<Query, Box<dyn Error>> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let constraints = serde_json::from_reader(reader)?;
Ok(constraints)
}
fn bool_to_result_str(b: bool) -> &'static str {
match b {
true => "1",
false => "0"
}
}
fn string_to_league(s: &str) -> Leagues {
match s {
"CK" => Leagues::CK,
"LCK" => Leagues::LCK,
"LCS" => Leagues::LCS,
"LEC" => Leagues::LEC,
"LFL" => Leagues::LFL,
"LJL" => Leagues::LJL,
"LPL" => Leagues::LPL,
"VCS" => Leagues::VCS,
_ => panic!("Unrecognized league: {:?}", s)
}
}
fn string_to_side(s: &str) -> Sides {
match s {
"Blue" => Sides::Blue,
"Red" => Sides::Red,
_ => panic!("Unrecognized side: {:?}", s)
}
}
fn fits_constraint(team: &TeamData, constraint: &Constraint) -> bool {
match constraint {
Constraint::GameResult(result) => {
return team.data.get("result").unwrap() == bool_to_result_str(*result);
},
Constraint::Team(name) => {
return team.name == *name;
},
Constraint::League(league) => {
return string_to_league(team.data.get("league").unwrap()) == *league;
},
Constraint::Side(side) => {
return string_to_side(team.data.get("side").unwrap()) == *side;
}
}
}
fn fits_constraints(team: &TeamData, constraints: &Vec<Constraint>) -> bool {
for constraint in constraints {
if !fits_constraint(team, constraint) {
return false;
}
}
return true;
}
fn stat_to_attribute_string(stat: Stats) -> &'static str {
match stat {
Stats::Barons => "barons",
Stats::Deaths => "deaths",
Stats::Dragons => "dragons",
Stats::FirstBaron => "firstbaron",
Stats::FirstDragon => "firstdragon",
Stats::FirstTower => "firsttower",
Stats::GoldDiff10 => "golddiffat10",
Stats::GoldDiff15 => "golddiffat15",
Stats::Kills => "kills",
Stats::Towers => "towers",
}
}
fn query_stat(stat: Stats, team: &TeamData) -> String {
match stat {
Stats::Kills => {
return team.data.get("kills").unwrap().clone();
},
_ => panic!("Unknown stat: {:?}", stat)
}
}
fn query_games(query: Query, games: Games) -> HashMap<String, String> {
let mut results = HashMap::<String, String>::new();
for (_, game) in games {
let team_a = game.0;
let team_b = match game.1 {
Some(v) => v,
None => continue
};
for team in [team_a, team_b].iter() {
if fits_constraints(team, &query.constraints) {
for stat in &query.stats {
let stat_attribute_string = stat_to_attribute_string(*stat);
let merge_type = get_merge_type_of_attribute(stat_attribute_string);
let default = String::from("0");
let current = match results.get(stat_attribute_string) {
Some(v) => v,
None => &default,
};
let v = query_stat(*stat, team);
let new = merge_attributes(¤t.to_string(), &v, merge_type);
results.insert(stat_attribute_string.to_string(), new);
}
}
}
}
results
}
fn main() {
let matches = App::new("Match Data Analyzer")
.version("1.0")
.author("<NAME>")
.about("Compiles data about matchsets")
.arg(Arg::with_name("matches")
.help("Path to matches CSV file")
.takes_value(true)
.required(true))
.arg(Arg::with_name("query")
.help("Path to query file")
.takes_value(true)
.required(true))
.get_matches();
let matches_path = matches.value_of("matches").unwrap();
let query_path = matches.value_of("query").unwrap();
let query = match get_query_from_path(Path::new(query_path)) {
Ok(v) => v,
Err(error) => panic!("Query could not be parsed: {:?}", error)
};
let mut reader = match csv::Reader::from_path(Path::new(matches_path)) {
Ok(v) => v,
Err(error) => panic!("Reader could not be created: {:?}", error)
};
let header_legend = match reader.headers() {
Ok(v) => header_row_to_legend(v.clone()),
Err(error) => panic!("No headers in matches: {:?}", error)
};
let mut games = Games::new();
for record in reader.into_records() {
let row = match record {
Ok(v) => v,
Err(_) => continue
};
add_player_row_to_games(&mut games, &row, &header_legend);
}
let results = query_games(query, games);
println!("{:?}", results);
}
|
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:
# MChc
蒙特卡罗法求解热传导方程
## 请使用MATLAB运行
# bianjietj.csv
基本数据文件
# main.m
主程序文件
# MC_PDE.m
核心函数文件
# MC_PDE_mex.mexw64
核心函数经mex化后文件(使用JIT编译器)
# data100s.mat
M(掷点数)为100时,所求的数据集

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 | # MChc
蒙特卡罗法求解热传导方程
## 请使用MATLAB运行
# bianjietj.csv
基本数据文件
# main.m
主程序文件
# MC_PDE.m
核心函数文件
# MC_PDE_mex.mexw64
核心函数经mex化后文件(使用JIT编译器)
# data100s.mat
M(掷点数)为100时,所求的数据集

|
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:
/*************************************************************************
> File Name: 39_输出一定数量的偶数.cpp
> Author:
> Mail:
> Created Time: 2019年12月06日 星期五 19时29分01秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
int begin, n, ans;
cin >> begin >> n;
if(begin < 0) begin = 0;
if(begin % 2 != 0) begin++;
ans = begin;
for(int i = 0; i < n; i++){
cout << ans << endl;
ans += 2;
}
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 | /*************************************************************************
> File Name: 39_输出一定数量的偶数.cpp
> Author:
> Mail:
> Created Time: 2019年12月06日 星期五 19时29分01秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
int begin, n, ans;
cin >> begin >> n;
if(begin < 0) begin = 0;
if(begin % 2 != 0) begin++;
ans = begin;
for(int i = 0; i < n; i++){
cout << ans << endl;
ans += 2;
}
return 0;
}
|
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:
'use strict'
import { Socket } from 'net';
import { ServerRequest } from 'http';
import { ModelConfig, Model } from './model/Base';
import parse from './lib/parse';
import * as cookie from 'cookie';
function createVerify(param: { uin: number, skey: string }): () => Promise<boolean> {
let hasVerify: boolean;
return () => {
return new Promise(function (resolve, reject) {
if (hasVerify !== undefined) return resolve(hasVerify);
let code = 0; // auth.PTVerify(param);
if (code === 0) {
hasVerify = true;
resolve(true);
} else {
hasVerify = false;
resolve(false);
}
});
}
}
function _wrap(graph: ModelConfig, i: number, res: Socket, verify: () => Promise<boolean>): Promise<any> {
try {
var ChildModel: any = require('./model/' + graph.name).Model;
} catch(e) {
console.error(e);
return undefined;
}
return (async function(): Promise<any> {
let inst = new ChildModel(graph);
if (
inst.verify &&
!(await verify())
) {
// need login
res && res.end(JSON.stringify({ seq: i, code: 100000 }));
} else {
let result = await inst.get(graph.param);
try {
let data = JSON.stringify({ seq: i, result: result });
res && res.write(data);
} catch(e) {
console.error(e);
}
}
})();
}
function uin(cookies: { [key: string]: string }): number {
var u = cookies['uin'] || cookies['uid_uin'];
if (cookies['uid_type'] === '2') {
return +u;
}
return !u ? null : parseInt(u.substring(1, u.length), 10);
}
function skey(cookies: { [key: string]: string }) {
return cookies['skey'];
}
/**
* combo protobuf
* @example
* [
* CourseList({ "type": 168, "ignore": ["*.price"] }),
* UserInfo({ "uin": 0, "need": ["nickname"] })
* ]
*/
export async function combo(describe: string, res: Socket, req?: ServerRequest) {
let list = parse(describe),
headers = req.headers || {},
cookies: { [key: string]: string } = { "uin": '123', "skey": '321' }, // cookie.parse(headers['Cookie']),
verify = createVerify({ uin:
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 | 'use strict'
import { Socket } from 'net';
import { ServerRequest } from 'http';
import { ModelConfig, Model } from './model/Base';
import parse from './lib/parse';
import * as cookie from 'cookie';
function createVerify(param: { uin: number, skey: string }): () => Promise<boolean> {
let hasVerify: boolean;
return () => {
return new Promise(function (resolve, reject) {
if (hasVerify !== undefined) return resolve(hasVerify);
let code = 0; // auth.PTVerify(param);
if (code === 0) {
hasVerify = true;
resolve(true);
} else {
hasVerify = false;
resolve(false);
}
});
}
}
function _wrap(graph: ModelConfig, i: number, res: Socket, verify: () => Promise<boolean>): Promise<any> {
try {
var ChildModel: any = require('./model/' + graph.name).Model;
} catch(e) {
console.error(e);
return undefined;
}
return (async function(): Promise<any> {
let inst = new ChildModel(graph);
if (
inst.verify &&
!(await verify())
) {
// need login
res && res.end(JSON.stringify({ seq: i, code: 100000 }));
} else {
let result = await inst.get(graph.param);
try {
let data = JSON.stringify({ seq: i, result: result });
res && res.write(data);
} catch(e) {
console.error(e);
}
}
})();
}
function uin(cookies: { [key: string]: string }): number {
var u = cookies['uin'] || cookies['uid_uin'];
if (cookies['uid_type'] === '2') {
return +u;
}
return !u ? null : parseInt(u.substring(1, u.length), 10);
}
function skey(cookies: { [key: string]: string }) {
return cookies['skey'];
}
/**
* combo protobuf
* @example
* [
* CourseList({ "type": 168, "ignore": ["*.price"] }),
* UserInfo({ "uin": 0, "need": ["nickname"] })
* ]
*/
export async function combo(describe: string, res: Socket, req?: ServerRequest) {
let list = parse(describe),
headers = req.headers || {},
cookies: { [key: string]: string } = { "uin": '123', "skey": '321' }, // cookie.parse(headers['Cookie']),
verify = createVerify({ uin: uin(cookies), skey: skey(cookies) }),
promise,
promises: Promise<any>[] = [];
for (var i = 0, l = list.length; i < l; i++) {
promise = _wrap(list[i], i, res, verify);
if (promise) promises.push(promise);
}
try {
await Promise.all(promises);
} catch(e) {
console.error(e);
} finally {
res && res.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:
//
// UIControl+SignalsTests.swift
// Signals
//
// Created by <NAME> on 1.1.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import XCTest
import Signals
class UIControl_SignalsTests: XCTestCase {
func testActionObservation() {
let button = UIButton()
var onTouchDownCount = 0
var onTouchDownRepeatCount = 0
var onTouchDragInsideCount = 0
var onTouchDragOutsideCount = 0
var onTouchDragEnterCount = 0
var onTouchDragExitCount = 0
var onTouchUpInsideCount = 0
var onTouchUpOutsideCount = 0
var onTouchCancelCount = 0
var onValueChangedCount = 0
var onEditingDidBeginCount = 0
var onEditingChangedCount = 0
var onEditingDidEndCount = 0
var onEditingDidEndOnExitCount = 0
button.onTouchDown.listen(self) {
onTouchDownCount += 1
}
button.onTouchDownRepeat.listen(self) {
onTouchDownRepeatCount += 1
}
button.onTouchDragInside.listen(self) {
onTouchDragInsideCount += 1
}
button.onTouchDragOutside.listen(self) {
onTouchDragOutsideCount += 1
}
button.onTouchDragEnter.listen(self) {
onTouchDragEnterCount += 1
}
button.onTouchDragExit.listen(self) {
onTouchDragExitCount += 1
}
button.onTouchUpInside.listen(self) {
onTouchUpInsideCount += 1
}
button.onTouchUpOutside.listen(self) {
onTouchUpOutsideCount += 1
}
button.onTouchCancel.listen(self) {
onTouchCancelCount += 1
}
button.onValueChanged.listen(self) {
onValueChangedCount += 1
}
button.onEditingDidBegin.listen(self) {
onEditingDidBeginCount += 1
}
button.onEditingChanged.listen(self) {
onEditingChangedCount += 1
}
button.onEditingDidEnd.listen(self) {
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 | //
// UIControl+SignalsTests.swift
// Signals
//
// Created by <NAME> on 1.1.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import XCTest
import Signals
class UIControl_SignalsTests: XCTestCase {
func testActionObservation() {
let button = UIButton()
var onTouchDownCount = 0
var onTouchDownRepeatCount = 0
var onTouchDragInsideCount = 0
var onTouchDragOutsideCount = 0
var onTouchDragEnterCount = 0
var onTouchDragExitCount = 0
var onTouchUpInsideCount = 0
var onTouchUpOutsideCount = 0
var onTouchCancelCount = 0
var onValueChangedCount = 0
var onEditingDidBeginCount = 0
var onEditingChangedCount = 0
var onEditingDidEndCount = 0
var onEditingDidEndOnExitCount = 0
button.onTouchDown.listen(self) {
onTouchDownCount += 1
}
button.onTouchDownRepeat.listen(self) {
onTouchDownRepeatCount += 1
}
button.onTouchDragInside.listen(self) {
onTouchDragInsideCount += 1
}
button.onTouchDragOutside.listen(self) {
onTouchDragOutsideCount += 1
}
button.onTouchDragEnter.listen(self) {
onTouchDragEnterCount += 1
}
button.onTouchDragExit.listen(self) {
onTouchDragExitCount += 1
}
button.onTouchUpInside.listen(self) {
onTouchUpInsideCount += 1
}
button.onTouchUpOutside.listen(self) {
onTouchUpOutsideCount += 1
}
button.onTouchCancel.listen(self) {
onTouchCancelCount += 1
}
button.onValueChanged.listen(self) {
onValueChangedCount += 1
}
button.onEditingDidBegin.listen(self) {
onEditingDidBeginCount += 1
}
button.onEditingChanged.listen(self) {
onEditingChangedCount += 1
}
button.onEditingDidEnd.listen(self) {
onEditingDidEndCount += 1
}
button.onEditingDidEndOnExit.listen(self) {
onEditingDidEndOnExitCount += 1
}
let events: [UIControlEvents] = [.TouchDown, .TouchDownRepeat, .TouchDragInside, .TouchDragOutside, .TouchDragEnter,
.TouchDragExit, .TouchUpInside, .TouchUpOutside, .TouchCancel, .ValueChanged, .EditingDidBegin, .EditingChanged,
.EditingDidEnd, .EditingDidEndOnExit];
for event in events {
let actions = button.actionsForTarget(button, forControlEvent: event);
for action in actions! {
button.performSelector(Selector(action))
}
}
XCTAssertEqual(onTouchDownCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchDownRepeatCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchDragInsideCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchDragOutsideCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchDragEnterCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchDragExitCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchUpInsideCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchUpOutsideCount, 1, "Should have triggered once")
XCTAssertEqual(onTouchCancelCount, 1, "Should have triggered once")
XCTAssertEqual(onValueChangedCount, 1, "Should have triggered once")
XCTAssertEqual(onEditingDidBeginCount, 1, "Should have triggered once")
XCTAssertEqual(onEditingChangedCount, 1, "Should have triggered once")
XCTAssertEqual(onEditingDidEndCount, 1, "Should have triggered once")
XCTAssertEqual(onEditingDidEndOnExitCount, 1, "Should have triggered once")
}
}
|
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:
# Release History
## 0.5.0 (2022-05-17)
### Breaking Changes
- Function `*AttestationsClient.BeginCreateOrUpdateAtSubscription` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtSubscriptionResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtSubscriptionResponse], error)`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResource` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtResourceResponse], error)`
- Function `*PolicyStatesClient.BeginTriggerResourceGroupEvaluation` return value(s) have been changed from `(*armruntime.Poller[PolicyStatesClientTriggerResourceGroupEvaluationResponse], error)` to `(*runtime.Poller[PolicyStatesClientTriggerResourceGroupEvaluationResponse], error)`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResourceGroup` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceGroupResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtResourceGroupResponse], error)`
- Function `*PolicyStatesClient.BeginTriggerSubscriptionEvaluation` return value(s) have been changed from `(*armruntime.Poller[PolicyStatesClientTriggerSubscriptionEvaluationResponse], error)` to `(*runtime.Poller[PolicyStatesClientTriggerSubscriptionEvaluationResponse], error)`
- Function `PolicyAssignmentSummary.MarshalJSON` has been removed
- Function `SummarizeResults.MarshalJSON` has been removed
- Function `ComponentStateDetails.MarshalJSON` has been removed
- Function `ErrorDefinitionAutoGenerated2.MarshalJSON` has been removed
- Function `CheckRestrictionsResultContentEvaluationResult.MarshalJSON` has been removed
- Function `Summary.MarshalJSON` has been removed
- Function `TrackedResourceModificationDetails.MarshalJSON` has been removed
- Function `PolicyTrackedResource.MarshalJSON` has been removed
- Func
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 | # Release History
## 0.5.0 (2022-05-17)
### Breaking Changes
- Function `*AttestationsClient.BeginCreateOrUpdateAtSubscription` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtSubscriptionResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtSubscriptionResponse], error)`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResource` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtResourceResponse], error)`
- Function `*PolicyStatesClient.BeginTriggerResourceGroupEvaluation` return value(s) have been changed from `(*armruntime.Poller[PolicyStatesClientTriggerResourceGroupEvaluationResponse], error)` to `(*runtime.Poller[PolicyStatesClientTriggerResourceGroupEvaluationResponse], error)`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResourceGroup` return value(s) have been changed from `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceGroupResponse], error)` to `(*runtime.Poller[AttestationsClientCreateOrUpdateAtResourceGroupResponse], error)`
- Function `*PolicyStatesClient.BeginTriggerSubscriptionEvaluation` return value(s) have been changed from `(*armruntime.Poller[PolicyStatesClientTriggerSubscriptionEvaluationResponse], error)` to `(*runtime.Poller[PolicyStatesClientTriggerSubscriptionEvaluationResponse], error)`
- Function `PolicyAssignmentSummary.MarshalJSON` has been removed
- Function `SummarizeResults.MarshalJSON` has been removed
- Function `ComponentStateDetails.MarshalJSON` has been removed
- Function `ErrorDefinitionAutoGenerated2.MarshalJSON` has been removed
- Function `CheckRestrictionsResultContentEvaluationResult.MarshalJSON` has been removed
- Function `Summary.MarshalJSON` has been removed
- Function `TrackedResourceModificationDetails.MarshalJSON` has been removed
- Function `PolicyTrackedResource.MarshalJSON` has been removed
- Function `CheckRestrictionsResult.MarshalJSON` has been removed
- Function `AttestationListResult.MarshalJSON` has been removed
- Function `RemediationDeployment.MarshalJSON` has been removed
- Function `ErrorDefinitionAutoGenerated.MarshalJSON` has been removed
- Function `SummaryResults.MarshalJSON` has been removed
- Function `PolicyEvent.MarshalJSON` has been removed
- Function `FieldRestrictions.MarshalJSON` has been removed
- Function `PolicyState.MarshalJSON` has been removed
- Function `PolicyMetadataCollection.MarshalJSON` has been removed
- Function `RemediationListResult.MarshalJSON` has been removed
- Function `OperationsListResults.MarshalJSON` has been removed
- Function `PolicyTrackedResourcesQueryResults.MarshalJSON` has been removed
- Function `PolicyEvaluationDetails.MarshalJSON` has been removed
- Function `FieldRestriction.MarshalJSON` has been removed
- Function `PolicyEventsQueryResults.MarshalJSON` has been removed
- Function `PolicyStatesQueryResults.MarshalJSON` has been removed
- Function `ErrorDefinition.MarshalJSON` has been removed
- Function `PolicyDefinitionSummary.MarshalJSON` has been removed
- Function `ComponentEventDetails.MarshalJSON` has been removed
- Function `RemediationDeploymentsListResult.MarshalJSON` has been removed
## 0.4.0 (2022-04-18)
### Breaking Changes
- Function `*RemediationsClient.ListDeploymentsAtSubscription` has been removed
- Function `*AttestationsClient.ListForResource` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForResource` has been removed
- Function `*RemediationsClient.ListForResourceGroup` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForPolicyDefinition` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForSubscription` has been removed
- Function `*RemediationsClient.ListDeploymentsAtManagementGroup` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForPolicySetDefinition` has been removed
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup` has been removed
- Function `*AttestationsClient.ListForSubscription` has been removed
- Function `*RemediationsClient.ListDeploymentsAtResourceGroup` has been removed
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForSubscription` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroup` has been removed
- Function `*RemediationsClient.ListForSubscription` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForPolicySetDefinition` has been removed
- Function `*PolicyMetadataClient.List` has been removed
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForPolicyDefinition` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForManagementGroup` has been removed
- Function `*PolicyStatesClient.ListQueryResultsForManagementGroup` has been removed
- Function `*AttestationsClient.ListForResourceGroup` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForSubscription` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroup` has been removed
- Function `*RemediationsClient.ListForManagementGroup` has been removed
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResource` has been removed
- Function `*PolicyEventsClient.ListQueryResultsForResource` has been removed
- Function `*RemediationsClient.ListForResource` has been removed
- Function `*RemediationsClient.ListDeploymentsAtResource` has been removed
### Features Added
- New function `*RemediationsClient.NewListDeploymentsAtSubscriptionPager(string, *QueryOptions, *RemediationsClientListDeploymentsAtSubscriptionOptions) *runtime.Pager[RemediationsClientListDeploymentsAtSubscriptionResponse]`
- New function `*PolicyTrackedResourcesClient.NewListQueryResultsForResourceGroupPager(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForResourceGroupOptions) *runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForResourceGroupResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForSubscriptionLevelPolicyAssignmentPager(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForManagementGroupPager(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForManagementGroupOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForManagementGroupResponse]`
- New function `*RemediationsClient.NewListDeploymentsAtManagementGroupPager(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtManagementGroupOptions) *runtime.Pager[RemediationsClientListDeploymentsAtManagementGroupResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForResourceGroupLevelPolicyAssignmentPager(PolicyEventsResourceType, string, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse]`
- New function `*RemediationsClient.NewListForResourceGroupPager(string, *QueryOptions, *RemediationsClientListForResourceGroupOptions) *runtime.Pager[RemediationsClientListForResourceGroupResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForSubscriptionLevelPolicyAssignmentPager(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse]`
- New function `*PolicyTrackedResourcesClient.NewListQueryResultsForSubscriptionPager(PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForSubscriptionOptions) *runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForSubscriptionResponse]`
- New function `*PolicyTrackedResourcesClient.NewListQueryResultsForManagementGroupPager(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForManagementGroupOptions) *runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForManagementGroupResponse]`
- New function `*RemediationsClient.NewListDeploymentsAtResourcePager(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtResourceOptions) *runtime.Pager[RemediationsClientListDeploymentsAtResourceResponse]`
- New function `*PolicyMetadataClient.NewListPager(*QueryOptions, *PolicyMetadataClientListOptions) *runtime.Pager[PolicyMetadataClientListResponse]`
- New function `*PolicyTrackedResourcesClient.NewListQueryResultsForResourcePager(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForResourceOptions) *runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForResourceResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForPolicySetDefinitionPager(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForPolicySetDefinitionOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForPolicySetDefinitionResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForResourcePager(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForResourceResponse]`
- New function `*RemediationsClient.NewListDeploymentsAtResourceGroupPager(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtResourceGroupOptions) *runtime.Pager[RemediationsClientListDeploymentsAtResourceGroupResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForPolicyDefinitionPager(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForPolicyDefinitionOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForPolicyDefinitionResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForManagementGroupPager(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForManagementGroupOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForManagementGroupResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForPolicySetDefinitionPager(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForPolicySetDefinitionOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForPolicySetDefinitionResponse]`
- New function `*RemediationsClient.NewListForManagementGroupPager(string, *QueryOptions, *RemediationsClientListForManagementGroupOptions) *runtime.Pager[RemediationsClientListForManagementGroupResponse]`
- New function `*RemediationsClient.NewListForResourcePager(string, *QueryOptions, *RemediationsClientListForResourceOptions) *runtime.Pager[RemediationsClientListForResourceResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForResourceGroupPager(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceGroupOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForResourceGroupResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForResourceGroupLevelPolicyAssignmentPager(PolicyStatesResource, string, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForSubscriptionPager(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForSubscriptionOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForSubscriptionResponse]`
- New function `*RemediationsClient.NewListForSubscriptionPager(*QueryOptions, *RemediationsClientListForSubscriptionOptions) *runtime.Pager[RemediationsClientListForSubscriptionResponse]`
- New function `*AttestationsClient.NewListForResourceGroupPager(string, *QueryOptions, *AttestationsClientListForResourceGroupOptions) *runtime.Pager[AttestationsClientListForResourceGroupResponse]`
- New function `*AttestationsClient.NewListForSubscriptionPager(*QueryOptions, *AttestationsClientListForSubscriptionOptions) *runtime.Pager[AttestationsClientListForSubscriptionResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForResourcePager(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForResourceResponse]`
- New function `*AttestationsClient.NewListForResourcePager(string, *QueryOptions, *AttestationsClientListForResourceOptions) *runtime.Pager[AttestationsClientListForResourceResponse]`
- New function `*PolicyStatesClient.NewListQueryResultsForPolicyDefinitionPager(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForPolicyDefinitionOptions) *runtime.Pager[PolicyStatesClientListQueryResultsForPolicyDefinitionResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForResourceGroupPager(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceGroupOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForResourceGroupResponse]`
- New function `*PolicyEventsClient.NewListQueryResultsForSubscriptionPager(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForSubscriptionOptions) *runtime.Pager[PolicyEventsClientListQueryResultsForSubscriptionResponse]`
## 0.3.0 (2022-04-12)
### Breaking Changes
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(PolicyEventsResourceType, string, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse])`
- Function `*PolicyStatesClient.SummarizeForResource` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions, *PolicyStatesClientSummarizeForResourceOptions)`
- Function `*PolicyStatesClient.SummarizeForPolicyDefinition` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions, *PolicyStatesClientSummarizeForPolicyDefinitionOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup` parameter(s) have been changed from `(string, PolicyTrackedResourcesResourceType, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForResourceGroupOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup` return value(s) have been changed from `(*PolicyTrackedResourcesClientListQueryResultsForResourceGroupPager)` to `(*runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForResourceGroupResponse])`
- Function `*PolicyStatesClient.ListQueryResultsForPolicyDefinition` parameter(s) have been changed from `(PolicyStatesResource, string, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForPolicyDefinitionOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForPolicyDefinition` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForPolicyDefinitionPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForPolicyDefinitionResponse])`
- Function `*PolicyStatesClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(PolicyStatesResource, string, *QueryOptions)` to `(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForManagementGroupOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForManagementGroup` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForManagementGroupPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForManagementGroupResponse])`
- Function `*RemediationsClient.ListDeploymentsAtManagementGroup` parameter(s) have been changed from `(string, string, *QueryOptions)` to `(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtManagementGroupOptions)`
- Function `*RemediationsClient.ListDeploymentsAtManagementGroup` return value(s) have been changed from `(*RemediationsClientListDeploymentsAtManagementGroupPager)` to `(*runtime.Pager[RemediationsClientListDeploymentsAtManagementGroupResponse])`
- Function `*AttestationsClient.ListForResourceGroup` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *AttestationsClientListForResourceGroupOptions)`
- Function `*AttestationsClient.ListForResourceGroup` return value(s) have been changed from `(*AttestationsClientListForResourceGroupPager)` to `(*runtime.Pager[AttestationsClientListForResourceGroupResponse])`
- Function `*PolicyEventsClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(PolicyEventsResourceType, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForManagementGroupOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForManagementGroup` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForManagementGroupPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForManagementGroupResponse])`
- Function `NewAttestationsClient` return value(s) have been changed from `(*AttestationsClient)` to `(*AttestationsClient, error)`
- Function `*PolicyStatesClient.ListQueryResultsForResource` parameter(s) have been changed from `(PolicyStatesResource, string, *QueryOptions)` to `(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForResource` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForResourcePager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForResourceResponse])`
- Function `*AttestationsClient.ListForSubscription` parameter(s) have been changed from `(*QueryOptions)` to `(*QueryOptions, *AttestationsClientListForSubscriptionOptions)`
- Function `*AttestationsClient.ListForSubscription` return value(s) have been changed from `(*AttestationsClientListForSubscriptionPager)` to `(*runtime.Pager[AttestationsClientListForSubscriptionResponse])`
- Function `*PolicyStatesClient.SummarizeForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, string, *QueryOptions, *PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResource` parameter(s) have been changed from `(PolicyEventsResourceType, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResource` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForResourcePager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForResourceResponse])`
- Function `*RemediationsClient.ListDeploymentsAtSubscription` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *RemediationsClientListDeploymentsAtSubscriptionOptions)`
- Function `*RemediationsClient.ListDeploymentsAtSubscription` return value(s) have been changed from `(*RemediationsClientListDeploymentsAtSubscriptionPager)` to `(*runtime.Pager[RemediationsClientListDeploymentsAtSubscriptionResponse])`
- Function `*PolicyMetadataClient.List` parameter(s) have been changed from `(*QueryOptions)` to `(*QueryOptions, *PolicyMetadataClientListOptions)`
- Function `*PolicyMetadataClient.List` return value(s) have been changed from `(*PolicyMetadataClientListPager)` to `(*runtime.Pager[PolicyMetadataClientListResponse])`
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroup` parameter(s) have been changed from `(PolicyEventsResourceType, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForResourceGroupOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroup` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForResourceGroupPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForResourceGroupResponse])`
- Function `NewOperationsClient` return value(s) have been changed from `(*OperationsClient)` to `(*OperationsClient, error)`
- Function `*PolicyStatesClient.SummarizeForSubscription` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions, *PolicyStatesClientSummarizeForSubscriptionOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroup` parameter(s) have been changed from `(PolicyStatesResource, string, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceGroupOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroup` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForResourceGroupPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForResourceGroupResponse])`
- Function `*PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(PolicyStatesResource, string, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse])`
- Function `NewPolicyStatesClient` return value(s) have been changed from `(*PolicyStatesClient)` to `(*PolicyStatesClient, error)`
- Function `*RemediationsClient.ListDeploymentsAtResourceGroup` parameter(s) have been changed from `(string, string, *QueryOptions)` to `(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtResourceGroupOptions)`
- Function `*RemediationsClient.ListDeploymentsAtResourceGroup` return value(s) have been changed from `(*RemediationsClientListDeploymentsAtResourceGroupPager)` to `(*runtime.Pager[RemediationsClientListDeploymentsAtResourceGroupResponse])`
- Function `*AttestationsClient.BeginCreateOrUpdateAtSubscription` return value(s) have been changed from `(AttestationsClientCreateOrUpdateAtSubscriptionPollerResponse, error)` to `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtSubscriptionResponse], error)`
- Function `*RemediationsClient.ListForResource` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *RemediationsClientListForResourceOptions)`
- Function `*RemediationsClient.ListForResource` return value(s) have been changed from `(*RemediationsClientListForResourcePager)` to `(*runtime.Pager[RemediationsClientListForResourceResponse])`
- Function `*PolicyStatesClient.SummarizeForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions, *PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForPolicySetDefinition` parameter(s) have been changed from `(PolicyStatesResource, string, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForPolicySetDefinitionOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForPolicySetDefinition` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForPolicySetDefinitionPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForPolicySetDefinitionResponse])`
- Function `NewRemediationsClient` return value(s) have been changed from `(*RemediationsClient)` to `(*RemediationsClient, error)`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResourceGroup` return value(s) have been changed from `(AttestationsClientCreateOrUpdateAtResourceGroupPollerResponse, error)` to `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceGroupResponse], error)`
- Function `NewPolicyRestrictionsClient` return value(s) have been changed from `(*PolicyRestrictionsClient)` to `(*PolicyRestrictionsClient, error)`
- Function `*PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(PolicyEventsResourceType, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse])`
- Function `NewPolicyMetadataClient` return value(s) have been changed from `(*PolicyMetadataClient)` to `(*PolicyMetadataClient, error)`
- Function `*PolicyStatesClient.SummarizeForPolicySetDefinition` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions, *PolicyStatesClientSummarizeForPolicySetDefinitionOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForSubscription` parameter(s) have been changed from `(PolicyStatesResource, string, *QueryOptions)` to `(PolicyStatesResource, string, *QueryOptions, *PolicyStatesClientListQueryResultsForSubscriptionOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForSubscription` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForSubscriptionPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForSubscriptionResponse])`
- Function `*AttestationsClient.BeginCreateOrUpdateAtResource` return value(s) have been changed from `(AttestationsClientCreateOrUpdateAtResourcePollerResponse, error)` to `(*armruntime.Poller[AttestationsClientCreateOrUpdateAtResourceResponse], error)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForSubscription` parameter(s) have been changed from `(PolicyTrackedResourcesResourceType, *QueryOptions)` to `(PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForSubscriptionOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForSubscription` return value(s) have been changed from `(*PolicyTrackedResourcesClientListQueryResultsForSubscriptionPager)` to `(*runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForSubscriptionResponse])`
- Function `*AttestationsClient.ListForResource` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *AttestationsClientListForResourceOptions)`
- Function `*AttestationsClient.ListForResource` return value(s) have been changed from `(*AttestationsClientListForResourcePager)` to `(*runtime.Pager[AttestationsClientListForResourceResponse])`
- Function `*RemediationsClient.ListForResourceGroup` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *RemediationsClientListForResourceGroupOptions)`
- Function `*RemediationsClient.ListForResourceGroup` return value(s) have been changed from `(*RemediationsClientListForResourceGroupPager)` to `(*runtime.Pager[RemediationsClientListForResourceGroupResponse])`
- Function `*PolicyStatesClient.SummarizeForResourceGroup` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions, *PolicyStatesClientSummarizeForResourceGroupOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResource` parameter(s) have been changed from `(string, PolicyTrackedResourcesResourceType, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForResourceOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResource` return value(s) have been changed from `(*PolicyTrackedResourcesClientListQueryResultsForResourcePager)` to `(*runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForResourceResponse])`
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(PolicyStatesResource, string, string, string, *QueryOptions)` to `(PolicyStatesResource, string, string, string, *QueryOptions, *PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` return value(s) have been changed from `(*PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager)` to `(*runtime.Pager[PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse])`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(string, PolicyTrackedResourcesResourceType, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions, *PolicyTrackedResourcesClientListQueryResultsForManagementGroupOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup` return value(s) have been changed from `(*PolicyTrackedResourcesClientListQueryResultsForManagementGroupPager)` to `(*runtime.Pager[PolicyTrackedResourcesClientListQueryResultsForManagementGroupResponse])`
- Function `*PolicyEventsClient.ListQueryResultsForPolicyDefinition` parameter(s) have been changed from `(PolicyEventsResourceType, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForPolicyDefinitionOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForPolicyDefinition` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForPolicyDefinitionPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForPolicyDefinitionResponse])`
- Function `*RemediationsClient.ListForSubscription` parameter(s) have been changed from `(*QueryOptions)` to `(*QueryOptions, *RemediationsClientListForSubscriptionOptions)`
- Function `*RemediationsClient.ListForSubscription` return value(s) have been changed from `(*RemediationsClientListForSubscriptionPager)` to `(*runtime.Pager[RemediationsClientListForSubscriptionResponse])`
- Function `*PolicyEventsClient.ListQueryResultsForPolicySetDefinition` parameter(s) have been changed from `(PolicyEventsResourceType, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions, *PolicyEventsClientListQueryResultsForPolicySetDefinitionOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForPolicySetDefinition` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForPolicySetDefinitionPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForPolicySetDefinitionResponse])`
- Function `*PolicyStatesClient.BeginTriggerResourceGroupEvaluation` return value(s) have been changed from `(PolicyStatesClientTriggerResourceGroupEvaluationPollerResponse, error)` to `(*armruntime.Poller[PolicyStatesClientTriggerResourceGroupEvaluationResponse], error)`
- Function `NewPolicyTrackedResourcesClient` return value(s) have been changed from `(*PolicyTrackedResourcesClient)` to `(*PolicyTrackedResourcesClient, error)`
- Function `*PolicyStatesClient.BeginTriggerSubscriptionEvaluation` return value(s) have been changed from `(PolicyStatesClientTriggerSubscriptionEvaluationPollerResponse, error)` to `(*armruntime.Poller[PolicyStatesClientTriggerSubscriptionEvaluationResponse], error)`
- Function `*RemediationsClient.ListDeploymentsAtResource` parameter(s) have been changed from `(string, string, *QueryOptions)` to `(string, string, *QueryOptions, *RemediationsClientListDeploymentsAtResourceOptions)`
- Function `*RemediationsClient.ListDeploymentsAtResource` return value(s) have been changed from `(*RemediationsClientListDeploymentsAtResourcePager)` to `(*runtime.Pager[RemediationsClientListDeploymentsAtResourceResponse])`
- Function `*PolicyEventsClient.ListQueryResultsForSubscription` parameter(s) have been changed from `(PolicyEventsResourceType, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions, *PolicyEventsClientListQueryResultsForSubscriptionOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForSubscription` return value(s) have been changed from `(*PolicyEventsClientListQueryResultsForSubscriptionPager)` to `(*runtime.Pager[PolicyEventsClientListQueryResultsForSubscriptionResponse])`
- Function `*RemediationsClient.ListForManagementGroup` parameter(s) have been changed from `(string, *QueryOptions)` to `(string, *QueryOptions, *RemediationsClientListForManagementGroupOptions)`
- Function `*RemediationsClient.ListForManagementGroup` return value(s) have been changed from `(*RemediationsClientListForManagementGroupPager)` to `(*runtime.Pager[RemediationsClientListForManagementGroupResponse])`
- Function `NewPolicyEventsClient` return value(s) have been changed from `(*PolicyEventsClient)` to `(*PolicyEventsClient, error)`
- Function `*PolicyStatesClient.SummarizeForManagementGroup` parameter(s) have been changed from `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions, *PolicyStatesClientSummarizeForManagementGroupOptions)`
- Function `*AttestationsClientCreateOrUpdateAtResourcePoller.ResumeToken` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourceGroupPager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicyDefinitionPager.Err` has been removed
- Function `*RemediationsClientListDeploymentsAtResourceGroupPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicySetDefinitionPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicyDefinitionPager.PageResponse` has been removed
- Function `*RemediationsClientListForResourceGroupPager.NextPage` has been removed
- Function `*RemediationsClientListDeploymentsAtSubscriptionPager.PageResponse` has been removed
- Function `*RemediationsClientListDeploymentsAtResourcePager.PageResponse` has been removed
- Function `*RemediationsClientListDeploymentsAtResourcePager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicySetDefinitionPager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicyDefinitionPager.PageResponse` has been removed
- Function `*RemediationsClientListForSubscriptionPager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupPager.Err` has been removed
- Function `*PolicyStatesClientTriggerResourceGroupEvaluationPoller.ResumeToken` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForSubscriptionPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicySetDefinitionPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtSubscriptionPoller.Poll` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionPager.Err` has been removed
- Function `*RemediationsClientListDeploymentsAtManagementGroupPager.NextPage` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourcePoller.FinalResponse` has been removed
- Function `*AttestationsClientListForResourcePager.PageResponse` has been removed
- Function `*PolicyMetadataClientListPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.PageResponse` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourcePager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionPager.NextPage` has been removed
- Function `AttestationsClientCreateOrUpdateAtResourcePollerResponse.PollUntilDone` has been removed
- Function `*AttestationsClientCreateOrUpdateAtSubscriptionPoller.ResumeToken` has been removed
- Function `*PolicyStatesClientListQueryResultsForManagementGroupPager.Err` has been removed
- Function `ComplianceState.ToPtr` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicyDefinitionPager.NextPage` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourceGroupPager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourcePager.Err` has been removed
- Function `*AttestationsClientCreateOrUpdateAtSubscriptionPollerResponse.Resume` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicySetDefinitionPager.PageResponse` has been removed
- Function `*RemediationsClientListForResourcePager.PageResponse` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForManagementGroupPager.PageResponse` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicyDefinitionPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionPager.NextPage` has been removed
- Function `*PolicyStatesClientTriggerResourceGroupEvaluationPoller.FinalResponse` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.Err` has been removed
- Function `PolicyStatesClientTriggerSubscriptionEvaluationPollerResponse.PollUntilDone` has been removed
- Function `CreatedByType.ToPtr` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupPager.NextPage` has been removed
- Function `*PolicyStatesClientTriggerResourceGroupEvaluationPollerResponse.Resume` has been removed
- Function `*RemediationsClientListForSubscriptionPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtSubscriptionPoller.FinalResponse` has been removed
- Function `*RemediationsClientListDeploymentsAtSubscriptionPager.NextPage` has been removed
- Function `*PolicyStatesClientTriggerSubscriptionEvaluationPollerResponse.Resume` has been removed
- Function `*AttestationsClientListForResourcePager.NextPage` has been removed
- Function `AttestationsClientCreateOrUpdateAtResourceGroupPollerResponse.PollUntilDone` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionPager.Err` has been removed
- Function `*RemediationsClientListForResourceGroupPager.Err` has been removed
- Function `PolicyTrackedResourcesResourceType.ToPtr` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForManagementGroupPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.NextPage` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourceGroupPoller.Done` has been removed
- Function `*AttestationsClientListForResourceGroupPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForManagementGroupPager.NextPage` has been removed
- Function `AttestationsClientCreateOrUpdateAtSubscriptionPollerResponse.PollUntilDone` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourcePager.Err` has been removed
- Function `*PolicyStatesClientTriggerSubscriptionEvaluationPoller.Done` has been removed
- Function `*PolicyStatesClientTriggerSubscriptionEvaluationPoller.ResumeToken` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionPager.PageResponse` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.NextPage` has been removed
- Function `FieldRestrictionResult.ToPtr` has been removed
- Function `*PolicyMetadataClientListPager.NextPage` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourcePoller.Done` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourceGroupPoller.FinalResponse` has been removed
- Function `*RemediationsClientListForResourcePager.NextPage` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourcePollerResponse.Resume` has been removed
- Function `*AttestationsClientListForResourceGroupPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForSubscriptionPager.PageResponse` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupPager.PageResponse` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.PageResponse` has been removed
- Function `*RemediationsClientListDeploymentsAtResourcePager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForManagementGroupPager.PageResponse` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.Err` has been removed
- Function `*RemediationsClientListDeploymentsAtManagementGroupPager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForManagementGroupPager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourcePager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourcePager.PageResponse` has been removed
- Function `*RemediationsClientListDeploymentsAtManagementGroupPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourceGroupPoller.Poll` has been removed
- Function `*PolicyStatesClientTriggerSubscriptionEvaluationPoller.FinalResponse` has been removed
- Function `*PolicyMetadataClientListPager.PageResponse` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourcePager.PageResponse` has been removed
- Function `*RemediationsClientListForManagementGroupPager.Err` has been removed
- Function `PolicyStatesResource.ToPtr` has been removed
- Function `*RemediationsClientListDeploymentsAtResourceGroupPager.PageResponse` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourceGroupPager.PageResponse` has been removed
- Function `*RemediationsClientListForResourcePager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicySetDefinitionPager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourcePager.Err` has been removed
- Function `*PolicyEventsClientListQueryResultsForPolicyDefinitionPager.Err` has been removed
- Function `*PolicyStatesClientListQueryResultsForManagementGroupPager.PageResponse` has been removed
- Function `*PolicyEventsClientListQueryResultsForResourcePager.NextPage` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForManagementGroupPager.Err` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForSubscriptionPager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtSubscriptionPoller.Done` has been removed
- Function `*PolicyStatesClientListQueryResultsForPolicySetDefinitionPager.NextPage` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.PageResponse` has been removed
- Function `*RemediationsClientListForSubscriptionPager.NextPage` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourceGroupPoller.ResumeToken` has been removed
- Function `*PolicyStatesClientTriggerSubscriptionEvaluationPoller.Poll` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupPager.NextPage` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForSubscriptionPager.PageResponse` has been removed
- Function `*PolicyStatesClientTriggerResourceGroupEvaluationPoller.Poll` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.NextPage` has been removed
- Function `PolicyStatesSummaryResourceType.ToPtr` has been removed
- Function `*AttestationsClientListForSubscriptionPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourcePoller.Poll` has been removed
- Function `*RemediationsClientListForManagementGroupPager.NextPage` has been removed
- Function `*PolicyEventsClientListQueryResultsForManagementGroupPager.Err` has been removed
- Function `*RemediationsClientListDeploymentsAtSubscriptionPager.Err` has been removed
- Function `*RemediationsClientListDeploymentsAtResourceGroupPager.Err` has been removed
- Function `*AttestationsClientListForResourcePager.Err` has been removed
- Function `PolicyEventsResourceType.ToPtr` has been removed
- Function `*PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager.PageResponse` has been removed
- Function `*AttestationsClientCreateOrUpdateAtResourceGroupPollerResponse.Resume` has been removed
- Function `*PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager.Err` has been removed
- Function `*AttestationsClientListForSubscriptionPager.Err` has been removed
- Function `*AttestationsClientListForSubscriptionPager.NextPage` has been removed
- Function `ResourceDiscoveryMode.ToPtr` has been removed
- Function `*RemediationsClientListForResourceGroupPager.PageResponse` has been removed
- Function `*PolicyTrackedResourcesClientListQueryResultsForResourcePager.PageResponse` has been removed
- Function `*AttestationsClientListForResourceGroupPager.PageResponse` has been removed
- Function `*PolicyStatesClientTriggerResourceGroupEvaluationPoller.Done` has been removed
- Function `PolicyStatesClientTriggerResourceGroupEvaluationPollerResponse.PollUntilDone` has been removed
- Function `*RemediationsClientListForManagementGroupPager.PageResponse` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourceGroupPoller` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourceGroupPollerResponse` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourceGroupResult` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourcePoller` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourcePollerResponse` has been removed
- Struct `AttestationsClientCreateOrUpdateAtResourceResult` has been removed
- Struct `AttestationsClientCreateOrUpdateAtSubscriptionPoller` has been removed
- Struct `AttestationsClientCreateOrUpdateAtSubscriptionPollerResponse` has been removed
- Struct `AttestationsClientCreateOrUpdateAtSubscriptionResult` has been removed
- Struct `AttestationsClientGetAtResourceGroupResult` has been removed
- Struct `AttestationsClientGetAtResourceResult` has been removed
- Struct `AttestationsClientGetAtSubscriptionResult` has been removed
- Struct `AttestationsClientListForResourceGroupPager` has been removed
- Struct `AttestationsClientListForResourceGroupResult` has been removed
- Struct `AttestationsClientListForResourcePager` has been removed
- Struct `AttestationsClientListForResourceResult` has been removed
- Struct `AttestationsClientListForSubscriptionPager` has been removed
- Struct `AttestationsClientListForSubscriptionResult` has been removed
- Struct `OperationsClientListResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForManagementGroupPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForManagementGroupResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForPolicyDefinitionPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForPolicyDefinitionResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForPolicySetDefinitionPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForPolicySetDefinitionResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourceGroupPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourceGroupResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourcePager` has been removed
- Struct `PolicyEventsClientListQueryResultsForResourceResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResult` has been removed
- Struct `PolicyEventsClientListQueryResultsForSubscriptionPager` has been removed
- Struct `PolicyEventsClientListQueryResultsForSubscriptionResult` has been removed
- Struct `PolicyMetadataClientGetResourceResult` has been removed
- Struct `PolicyMetadataClientListPager` has been removed
- Struct `PolicyMetadataClientListResult` has been removed
- Struct `PolicyRestrictionsClientCheckAtResourceGroupScopeResult` has been removed
- Struct `PolicyRestrictionsClientCheckAtSubscriptionScopeResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForManagementGroupPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForManagementGroupResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForPolicyDefinitionPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForPolicyDefinitionResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForPolicySetDefinitionPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForPolicySetDefinitionResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourceGroupPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourceGroupResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourcePager` has been removed
- Struct `PolicyStatesClientListQueryResultsForResourceResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResult` has been removed
- Struct `PolicyStatesClientListQueryResultsForSubscriptionPager` has been removed
- Struct `PolicyStatesClientListQueryResultsForSubscriptionResult` has been removed
- Struct `PolicyStatesClientSummarizeForManagementGroupResult` has been removed
- Struct `PolicyStatesClientSummarizeForPolicyDefinitionResult` has been removed
- Struct `PolicyStatesClientSummarizeForPolicySetDefinitionResult` has been removed
- Struct `PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentResult` has been removed
- Struct `PolicyStatesClientSummarizeForResourceGroupResult` has been removed
- Struct `PolicyStatesClientSummarizeForResourceResult` has been removed
- Struct `PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentResult` has been removed
- Struct `PolicyStatesClientSummarizeForSubscriptionResult` has been removed
- Struct `PolicyStatesClientTriggerResourceGroupEvaluationPoller` has been removed
- Struct `PolicyStatesClientTriggerResourceGroupEvaluationPollerResponse` has been removed
- Struct `PolicyStatesClientTriggerSubscriptionEvaluationPoller` has been removed
- Struct `PolicyStatesClientTriggerSubscriptionEvaluationPollerResponse` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForManagementGroupPager` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForManagementGroupResult` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForResourceGroupPager` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForResourceGroupResult` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForResourcePager` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForResourceResult` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForSubscriptionPager` has been removed
- Struct `PolicyTrackedResourcesClientListQueryResultsForSubscriptionResult` has been removed
- Struct `RemediationsClientCancelAtManagementGroupResult` has been removed
- Struct `RemediationsClientCancelAtResourceGroupResult` has been removed
- Struct `RemediationsClientCancelAtResourceResult` has been removed
- Struct `RemediationsClientCancelAtSubscriptionResult` has been removed
- Struct `RemediationsClientCreateOrUpdateAtManagementGroupResult` has been removed
- Struct `RemediationsClientCreateOrUpdateAtResourceGroupResult` has been removed
- Struct `RemediationsClientCreateOrUpdateAtResourceResult` has been removed
- Struct `RemediationsClientCreateOrUpdateAtSubscriptionResult` has been removed
- Struct `RemediationsClientDeleteAtManagementGroupResult` has been removed
- Struct `RemediationsClientDeleteAtResourceGroupResult` has been removed
- Struct `RemediationsClientDeleteAtResourceResult` has been removed
- Struct `RemediationsClientDeleteAtSubscriptionResult` has been removed
- Struct `RemediationsClientGetAtManagementGroupResult` has been removed
- Struct `RemediationsClientGetAtResourceGroupResult` has been removed
- Struct `RemediationsClientGetAtResourceResult` has been removed
- Struct `RemediationsClientGetAtSubscriptionResult` has been removed
- Struct `RemediationsClientListDeploymentsAtManagementGroupPager` has been removed
- Struct `RemediationsClientListDeploymentsAtManagementGroupResult` has been removed
- Struct `RemediationsClientListDeploymentsAtResourceGroupPager` has been removed
- Struct `RemediationsClientListDeploymentsAtResourceGroupResult` has been removed
- Struct `RemediationsClientListDeploymentsAtResourcePager` has been removed
- Struct `RemediationsClientListDeploymentsAtResourceResult` has been removed
- Struct `RemediationsClientListDeploymentsAtSubscriptionPager` has been removed
- Struct `RemediationsClientListDeploymentsAtSubscriptionResult` has been removed
- Struct `RemediationsClientListForManagementGroupPager` has been removed
- Struct `RemediationsClientListForManagementGroupResult` has been removed
- Struct `RemediationsClientListForResourceGroupPager` has been removed
- Struct `RemediationsClientListForResourceGroupResult` has been removed
- Struct `RemediationsClientListForResourcePager` has been removed
- Struct `RemediationsClientListForResourceResult` has been removed
- Struct `RemediationsClientListForSubscriptionPager` has been removed
- Struct `RemediationsClientListForSubscriptionResult` has been removed
- Field `PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentResult` of struct `PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForPolicyDefinitionResult` of struct `PolicyEventsClientListQueryResultsForPolicyDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForPolicyDefinitionResponse` has been removed
- Field `PolicyRestrictionsClientCheckAtResourceGroupScopeResult` of struct `PolicyRestrictionsClientCheckAtResourceGroupScopeResponse` has been removed
- Field `RawResponse` of struct `PolicyRestrictionsClientCheckAtResourceGroupScopeResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForPolicySetDefinitionResult` of struct `PolicyStatesClientListQueryResultsForPolicySetDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForPolicySetDefinitionResponse` has been removed
- Field `PolicyStatesClientSummarizeForPolicyDefinitionResult` of struct `PolicyStatesClientSummarizeForPolicyDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForPolicyDefinitionResponse` has been removed
- Field `AttestationsClientCreateOrUpdateAtResourceResult` of struct `AttestationsClientCreateOrUpdateAtResourceResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientCreateOrUpdateAtResourceResponse` has been removed
- Field `AttestationsClientCreateOrUpdateAtSubscriptionResult` of struct `AttestationsClientCreateOrUpdateAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientCreateOrUpdateAtSubscriptionResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForResourceResult` of struct `PolicyEventsClientListQueryResultsForResourceResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForResourceResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientDeleteAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientDeleteAtResourceGroupResponse` has been removed
- Field `OperationsClientListResult` of struct `OperationsClientListResponse` has been removed
- Field `RawResponse` of struct `OperationsClientListResponse` has been removed
- Field `RemediationsClientDeleteAtSubscriptionResult` of struct `RemediationsClientDeleteAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientDeleteAtSubscriptionResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForSubscriptionResult` of struct `PolicyStatesClientListQueryResultsForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientDeleteAtResourceResponse` has been removed
- Field `AttestationsClientGetAtResourceGroupResult` of struct `AttestationsClientGetAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientGetAtResourceGroupResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResult` of struct `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `RemediationsClientCreateOrUpdateAtResourceGroupResult` of struct `RemediationsClientCreateOrUpdateAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCreateOrUpdateAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientTriggerResourceGroupEvaluationResponse` has been removed
- Field `RemediationsClientGetAtManagementGroupResult` of struct `RemediationsClientGetAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientGetAtManagementGroupResponse` has been removed
- Field `AttestationsClientCreateOrUpdateAtResourceGroupResult` of struct `AttestationsClientCreateOrUpdateAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientCreateOrUpdateAtResourceGroupResponse` has been removed
- Field `RemediationsClientGetAtResourceGroupResult` of struct `RemediationsClientGetAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientGetAtResourceGroupResponse` has been removed
- Field `RemediationsClientGetAtSubscriptionResult` of struct `RemediationsClientGetAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientGetAtSubscriptionResponse` has been removed
- Field `RemediationsClientCreateOrUpdateAtResourceResult` of struct `RemediationsClientCreateOrUpdateAtResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCreateOrUpdateAtResourceResponse` has been removed
- Field `RemediationsClientCancelAtManagementGroupResult` of struct `RemediationsClientCancelAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCancelAtManagementGroupResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForPolicyDefinitionResult` of struct `PolicyStatesClientListQueryResultsForPolicyDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForPolicyDefinitionResponse` has been removed
- Field `AttestationsClientGetAtSubscriptionResult` of struct `AttestationsClientGetAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientGetAtSubscriptionResponse` has been removed
- Field `RemediationsClientCancelAtResourceGroupResult` of struct `RemediationsClientCancelAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCancelAtResourceGroupResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResult` of struct `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResult` of struct `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse` has been removed
- Field `RemediationsClientDeleteAtResourceResult` of struct `RemediationsClientDeleteAtResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientDeleteAtResourceResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForResourceGroupResult` of struct `PolicyEventsClientListQueryResultsForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForResourceGroupResponse` has been removed
- Field `RemediationsClientCancelAtResourceResult` of struct `RemediationsClientCancelAtResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCancelAtResourceResponse` has been removed
- Field `RemediationsClientListDeploymentsAtSubscriptionResult` of struct `RemediationsClientListDeploymentsAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListDeploymentsAtSubscriptionResponse` has been removed
- Field `PolicyMetadataClientListResult` of struct `PolicyMetadataClientListResponse` has been removed
- Field `RawResponse` of struct `PolicyMetadataClientListResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForManagementGroupResult` of struct `PolicyStatesClientListQueryResultsForManagementGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForManagementGroupResponse` has been removed
- Field `PolicyStatesClientSummarizeForResourceGroupResult` of struct `PolicyStatesClientSummarizeForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForResourceGroupResponse` has been removed
- Field `PolicyTrackedResourcesClientListQueryResultsForResourceResult` of struct `PolicyTrackedResourcesClientListQueryResultsForResourceResponse` has been removed
- Field `RawResponse` of struct `PolicyTrackedResourcesClientListQueryResultsForResourceResponse` has been removed
- Field `RemediationsClientCreateOrUpdateAtManagementGroupResult` of struct `RemediationsClientCreateOrUpdateAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCreateOrUpdateAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientTriggerSubscriptionEvaluationResponse` has been removed
- Field `RemediationsClientDeleteAtResourceGroupResult` of struct `RemediationsClientDeleteAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientDeleteAtResourceGroupResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForResourceResult` of struct `PolicyStatesClientListQueryResultsForResourceResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForResourceResponse` has been removed
- Field `PolicyStatesClientSummarizeForManagementGroupResult` of struct `PolicyStatesClientSummarizeForManagementGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForManagementGroupResponse` has been removed
- Field `RemediationsClientListDeploymentsAtResourceResult` of struct `RemediationsClientListDeploymentsAtResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListDeploymentsAtResourceResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResult` of struct `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForPolicySetDefinitionResult` of struct `PolicyEventsClientListQueryResultsForPolicySetDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForPolicySetDefinitionResponse` has been removed
- Field `RemediationsClientCancelAtSubscriptionResult` of struct `RemediationsClientCancelAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCancelAtSubscriptionResponse` has been removed
- Field `PolicyMetadataClientGetResourceResult` of struct `PolicyMetadataClientGetResourceResponse` has been removed
- Field `RawResponse` of struct `PolicyMetadataClientGetResourceResponse` has been removed
- Field `RemediationsClientDeleteAtManagementGroupResult` of struct `RemediationsClientDeleteAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientDeleteAtManagementGroupResponse` has been removed
- Field `PolicyRestrictionsClientCheckAtSubscriptionScopeResult` of struct `PolicyRestrictionsClientCheckAtSubscriptionScopeResponse` has been removed
- Field `RawResponse` of struct `PolicyRestrictionsClientCheckAtSubscriptionScopeResponse` has been removed
- Field `RemediationsClientListForSubscriptionResult` of struct `RemediationsClientListForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListForSubscriptionResponse` has been removed
- Field `RemediationsClientListForResourceGroupResult` of struct `RemediationsClientListForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListForResourceGroupResponse` has been removed
- Field `RemediationsClientCreateOrUpdateAtSubscriptionResult` of struct `RemediationsClientCreateOrUpdateAtSubscriptionResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientCreateOrUpdateAtSubscriptionResponse` has been removed
- Field `RemediationsClientListForResourceResult` of struct `RemediationsClientListForResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListForResourceResponse` has been removed
- Field `AttestationsClientListForResourceGroupResult` of struct `AttestationsClientListForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientListForResourceGroupResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForManagementGroupResult` of struct `PolicyEventsClientListQueryResultsForManagementGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForManagementGroupResponse` has been removed
- Field `PolicyTrackedResourcesClientListQueryResultsForResourceGroupResult` of struct `PolicyTrackedResourcesClientListQueryResultsForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyTrackedResourcesClientListQueryResultsForResourceGroupResponse` has been removed
- Field `PolicyStatesClientSummarizeForPolicySetDefinitionResult` of struct `PolicyStatesClientSummarizeForPolicySetDefinitionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForPolicySetDefinitionResponse` has been removed
- Field `PolicyTrackedResourcesClientListQueryResultsForSubscriptionResult` of struct `PolicyTrackedResourcesClientListQueryResultsForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `PolicyTrackedResourcesClientListQueryResultsForSubscriptionResponse` has been removed
- Field `PolicyEventsClientListQueryResultsForSubscriptionResult` of struct `PolicyEventsClientListQueryResultsForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `PolicyEventsClientListQueryResultsForSubscriptionResponse` has been removed
- Field `RemediationsClientListForManagementGroupResult` of struct `RemediationsClientListForManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListForManagementGroupResponse` has been removed
- Field `PolicyTrackedResourcesClientListQueryResultsForManagementGroupResult` of struct `PolicyTrackedResourcesClientListQueryResultsForManagementGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyTrackedResourcesClientListQueryResultsForManagementGroupResponse` has been removed
- Field `RemediationsClientListDeploymentsAtManagementGroupResult` of struct `RemediationsClientListDeploymentsAtManagementGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListDeploymentsAtManagementGroupResponse` has been removed
- Field `AttestationsClientListForSubscriptionResult` of struct `AttestationsClientListForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientListForSubscriptionResponse` has been removed
- Field `PolicyStatesClientSummarizeForSubscriptionResult` of struct `PolicyStatesClientSummarizeForSubscriptionResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForSubscriptionResponse` has been removed
- Field `AttestationsClientGetAtResourceResult` of struct `AttestationsClientGetAtResourceResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientGetAtResourceResponse` has been removed
- Field `RemediationsClientGetAtResourceResult` of struct `RemediationsClientGetAtResourceResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientGetAtResourceResponse` has been removed
- Field `PolicyStatesClientListQueryResultsForResourceGroupResult` of struct `PolicyStatesClientListQueryResultsForResourceGroupResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientListQueryResultsForResourceGroupResponse` has been removed
- Field `RemediationsClientListDeploymentsAtResourceGroupResult` of struct `RemediationsClientListDeploymentsAtResourceGroupResponse` has been removed
- Field `RawResponse` of struct `RemediationsClientListDeploymentsAtResourceGroupResponse` has been removed
- Field `PolicyStatesClientSummarizeForResourceResult` of struct `PolicyStatesClientSummarizeForResourceResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForResourceResponse` has been removed
- Field `PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentResult` of struct `PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `RawResponse` of struct `PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentResponse` has been removed
- Field `AttestationsClientListForResourceResult` of struct `AttestationsClientListForResourceResponse` has been removed
- Field `RawResponse` of struct `AttestationsClientListForResourceResponse` has been removed
### Features Added
- New function `*PolicyRestrictionsClient.CheckAtManagementGroupScope(context.Context, string, CheckManagementGroupRestrictionsRequest, *PolicyRestrictionsClientCheckAtManagementGroupScopeOptions) (PolicyRestrictionsClientCheckAtManagementGroupScopeResponse, error)`
- New function `ErrorDefinitionAutoGenerated2.MarshalJSON() ([]byte, error)`
- New function `CheckManagementGroupRestrictionsRequest.MarshalJSON() ([]byte, error)`
- New function `ErrorDefinitionAutoGenerated.MarshalJSON() ([]byte, error)`
- New struct `CheckManagementGroupRestrictionsRequest`
- New struct `ErrorDefinitionAutoGenerated`
- New struct `ErrorDefinitionAutoGenerated2`
- New struct `ErrorResponse`
- New struct `ErrorResponseAutoGenerated`
- New struct `ErrorResponseAutoGenerated2`
- New struct `PolicyRestrictionsClientCheckAtManagementGroupScopeOptions`
- New struct `PolicyRestrictionsClientCheckAtManagementGroupScopeResponse`
- New struct `QueryFailure`
- New struct `QueryFailureError`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse`
- New anonymous field `PolicyTrackedResourcesQueryResults` in struct `PolicyTrackedResourcesClientListQueryResultsForResourceResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForResourceGroupResponse`
- New anonymous field `PolicyTrackedResourcesQueryResults` in struct `PolicyTrackedResourcesClientListQueryResultsForResourceGroupResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForResourceGroupLevelPolicyAssignmentResponse`
- New field `ResumeToken` in struct `AttestationsClientBeginCreateOrUpdateAtResourceOptions`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForPolicySetDefinitionResponse`
- New anonymous field `PolicyTrackedResourcesQueryResults` in struct `PolicyTrackedResourcesClientListQueryResultsForSubscriptionResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCancelAtResourceResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCancelAtResourceGroupResponse`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForPolicySetDefinitionResponse`
- New anonymous field `RemediationDeploymentsListResult` in struct `RemediationsClientListDeploymentsAtManagementGroupResponse`
- New anonymous field `RemediationListResult` in struct `RemediationsClientListForSubscriptionResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForSubscriptionLevelPolicyAssignmentResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForSubscriptionResponse`
- New anonymous field `CheckRestrictionsResult` in struct `PolicyRestrictionsClientCheckAtResourceGroupScopeResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForResourceGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientDeleteAtSubscriptionResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForSubscriptionResponse`
- New anonymous field `Attestation` in struct `AttestationsClientGetAtResourceGroupResponse`
- New field `ResumeToken` in struct `AttestationsClientBeginCreateOrUpdateAtSubscriptionOptions`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForPolicySetDefinitionResponse`
- New anonymous field `RemediationListResult` in struct `RemediationsClientListForResourceResponse`
- New anonymous field `PolicyMetadataCollection` in struct `PolicyMetadataClientListResponse`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForResourceGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientDeleteAtManagementGroupResponse`
- New field `ResumeToken` in struct `PolicyStatesClientBeginTriggerResourceGroupEvaluationOptions`
- New anonymous field `PolicyTrackedResourcesQueryResults` in struct `PolicyTrackedResourcesClientListQueryResultsForManagementGroupResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForManagementGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientDeleteAtResourceResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCreateOrUpdateAtManagementGroupResponse`
- New anonymous field `RemediationDeploymentsListResult` in struct `RemediationsClientListDeploymentsAtResourceGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientGetAtSubscriptionResponse`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForResourceResponse`
- New anonymous field `AttestationListResult` in struct `AttestationsClientListForSubscriptionResponse`
- New anonymous field `Remediation` in struct `RemediationsClientGetAtManagementGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCancelAtSubscriptionResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForPolicyDefinitionResponse`
- New anonymous field `RemediationDeploymentsListResult` in struct `RemediationsClientListDeploymentsAtResourceResponse`
- New anonymous field `Attestation` in struct `AttestationsClientCreateOrUpdateAtResourceResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForPolicyDefinitionResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCreateOrUpdateAtResourceGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCreateOrUpdateAtResourceResponse`
- New anonymous field `AttestationListResult` in struct `AttestationsClientListForResourceGroupResponse`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForSubscriptionResponse`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForPolicyDefinitionResponse`
- New field `ResumeToken` in struct `AttestationsClientBeginCreateOrUpdateAtResourceGroupOptions`
- New anonymous field `PolicyStatesQueryResults` in struct `PolicyStatesClientListQueryResultsForManagementGroupResponse`
- New anonymous field `AttestationListResult` in struct `AttestationsClientListForResourceResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCreateOrUpdateAtSubscriptionResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForSubscriptionLevelPolicyAssignmentResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForManagementGroupResponse`
- New anonymous field `OperationsListResults` in struct `OperationsClientListResponse`
- New anonymous field `Remediation` in struct `RemediationsClientDeleteAtResourceGroupResponse`
- New anonymous field `Remediation` in struct `RemediationsClientGetAtResourceResponse`
- New anonymous field `Attestation` in struct `AttestationsClientGetAtResourceResponse`
- New anonymous field `PolicyMetadata` in struct `PolicyMetadataClientGetResourceResponse`
- New anonymous field `Remediation` in struct `RemediationsClientCancelAtManagementGroupResponse`
- New anonymous field `RemediationListResult` in struct `RemediationsClientListForResourceGroupResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForResourceGroupLevelPolicyAssignmentResponse`
- New anonymous field `RemediationListResult` in struct `RemediationsClientListForManagementGroupResponse`
- New field `ResumeToken` in struct `PolicyStatesClientBeginTriggerSubscriptionEvaluationOptions`
- New anonymous field `Attestation` in struct `AttestationsClientCreateOrUpdateAtSubscriptionResponse`
- New anonymous field `Attestation` in struct `AttestationsClientCreateOrUpdateAtResourceGroupResponse`
- New anonymous field `Attestation` in struct `AttestationsClientGetAtSubscriptionResponse`
- New anonymous field `RemediationDeploymentsListResult` in struct `RemediationsClientListDeploymentsAtSubscriptionResponse`
- New anonymous field `PolicyEventsQueryResults` in struct `PolicyEventsClientListQueryResultsForResourceResponse`
- New anonymous field `Remediation` in struct `RemediationsClientGetAtResourceGroupResponse`
- New anonymous field `CheckRestrictionsResult` in struct `PolicyRestrictionsClientCheckAtSubscriptionScopeResponse`
- New anonymous field `SummarizeResults` in struct `PolicyStatesClientSummarizeForResourceResponse`
## 0.2.0 (2022-02-22)
### Breaking Changes
- Function `*PolicyStatesClient.SummarizeForManagementGroup` parameter(s) have been changed from `(context.Context, Enum6, Enum0, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForSubscription` parameter(s) have been changed from `(context.Context, Enum6, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)`
- Function `*RemediationsClient.CreateOrUpdateAtManagementGroup` parameter(s) have been changed from `(context.Context, Enum0, string, string, Remediation, *RemediationsClientCreateOrUpdateAtManagementGroupOptions)` to `(context.Context, string, string, Remediation, *RemediationsClientCreateOrUpdateAtManagementGroupOptions)`
- Function `*RemediationsClient.GetAtManagementGroup` parameter(s) have been changed from `(context.Context, Enum0, string, string, *RemediationsClientGetAtManagementGroupOptions)` to `(context.Context, string, string, *RemediationsClientGetAtManagementGroupOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForPolicyDefinition` parameter(s) have been changed from `(Enum1, string, Enum4, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(PolicyStatesResource, string, Enum4, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForSubscription` parameter(s) have been changed from `(Enum1, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForPolicyDefinition` parameter(s) have been changed from `(PolicyStatesResource, string, Enum4, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions)`
- Function `*RemediationsClient.CancelAtManagementGroup` parameter(s) have been changed from `(context.Context, Enum0, string, string, *RemediationsClientCancelAtManagementGroupOptions)` to `(context.Context, string, string, *RemediationsClientCancelAtManagementGroupOptions)`
- Function `*RemediationsClient.ListDeploymentsAtManagementGroup` parameter(s) have been changed from `(Enum0, string, string, *QueryOptions)` to `(string, string, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroup` parameter(s) have been changed from `(Enum1, string, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForResourceGroup` parameter(s) have been changed from `(context.Context, Enum6, string, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(context.Context, Enum6, string, Enum4, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForResource` parameter(s) have been changed from `(context.Context, Enum6, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, *QueryOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(PolicyStatesResource, Enum0, string, *QueryOptions)` to `(PolicyStatesResource, string, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(Enum1, string, string, Enum4, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForPolicySetDefinition` parameter(s) have been changed from `(PolicyStatesResource, string, Enum4, string, *QueryOptions)` to `(PolicyStatesResource, string, string, *QueryOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(Enum0, string, Enum1, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup` parameter(s) have been changed from `(string, Enum1, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions)`
- Function `*RemediationsClient.DeleteAtManagementGroup` parameter(s) have been changed from `(context.Context, Enum0, string, string, *RemediationsClientDeleteAtManagementGroupOptions)` to `(context.Context, string, string, *RemediationsClientDeleteAtManagementGroupOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForPolicySetDefinition` parameter(s) have been changed from `(Enum1, string, Enum4, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForManagementGroup` parameter(s) have been changed from `(Enum1, Enum0, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForPolicySetDefinition` parameter(s) have been changed from `(context.Context, Enum6, string, Enum4, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForResource` parameter(s) have been changed from `(string, Enum1, *QueryOptions)` to `(string, PolicyTrackedResourcesResourceType, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment` parameter(s) have been changed from `(Enum1, string, Enum4, string, *QueryOptions)` to `(PolicyEventsResourceType, string, string, *QueryOptions)`
- Function `*RemediationsClient.ListForManagementGroup` parameter(s) have been changed from `(Enum0, string, *QueryOptions)` to `(string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForPolicyDefinition` parameter(s) have been changed from `(context.Context, Enum6, string, Enum4, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, *QueryOptions)`
- Function `*PolicyTrackedResourcesClient.ListQueryResultsForSubscription` parameter(s) have been changed from `(Enum1, *QueryOptions)` to `(PolicyTrackedResourcesResourceType, *QueryOptions)`
- Function `*PolicyEventsClient.ListQueryResultsForResource` parameter(s) have been changed from `(Enum1, string, *QueryOptions)` to `(PolicyEventsResourceType, string, *QueryOptions)`
- Function `*PolicyStatesClient.SummarizeForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(context.Context, Enum6, string, string, Enum4, string, *QueryOptions)` to `(context.Context, PolicyStatesSummaryResourceType, string, string, string, *QueryOptions)`
- Function `*PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment` parameter(s) have been changed from `(PolicyStatesResource, string, string, Enum4, string, *QueryOptions)` to `(PolicyStatesResource, string, string, string, *QueryOptions)`
- Type of `ExpressionEvaluationDetails.ExpressionValue` has been changed from `map[string]interface{}` to `interface{}`
- Type of `ExpressionEvaluationDetails.TargetValue` has been changed from `map[string]interface{}` to `interface{}`
- Type of `CheckRestrictionsResourceDetails.ResourceContent` has been changed from `map[string]interface{}` to `interface{}`
- Type of `PolicyMetadataProperties.Metadata` has been changed from `map[string]interface{}` to `interface{}`
- Type of `PolicyMetadataSlimProperties.Metadata` has been changed from `map[string]interface{}` to `interface{}`
- Const `Enum6Latest` has been removed
- Const `Enum1Default` has been removed
- Const `Enum0MicrosoftManagement` has been removed
- Const `Enum4MicrosoftAuthorization` has been removed
- Function `Enum6.ToPtr` has been removed
- Function `PossibleEnum4Values` has been removed
- Function `ErrorDefinitionAutoGenerated.MarshalJSON` has been removed
- Function `Enum1.ToPtr` has been removed
- Function `PossibleEnum6Values` has been removed
- Function `Enum4.ToPtr` has been removed
- Function `PossibleEnum0Values` has been removed
- Function `PossibleEnum1Values` has been removed
- Function `ErrorDefinitionAutoGenerated2.MarshalJSON` has been removed
- Function `Enum0.ToPtr` has been removed
- Struct `ErrorDefinitionAutoGenerated` has been removed
- Struct `ErrorDefinitionAutoGenerated2` has been removed
- Struct `ErrorResponse` has been removed
- Struct `ErrorResponseAutoGenerated` has been removed
- Struct `ErrorResponseAutoGenerated2` has been removed
- Struct `QueryFailure` has been removed
- Struct `QueryFailureError` has been removed
### Features Added
- New const `PolicyStatesSummaryResourceTypeLatest`
- New const `PolicyEventsResourceTypeDefault`
- New const `PolicyTrackedResourcesResourceTypeDefault`
- New function `PolicyTrackedResourcesResourceType.ToPtr() *PolicyTrackedResourcesResourceType`
- New function `PossiblePolicyStatesSummaryResourceTypeValues() []PolicyStatesSummaryResourceType`
- New function `PolicyStatesSummaryResourceType.ToPtr() *PolicyStatesSummaryResourceType`
- New function `PossiblePolicyTrackedResourcesResourceTypeValues() []PolicyTrackedResourcesResourceType`
- New function `PossiblePolicyEventsResourceTypeValues() []PolicyEventsResourceType`
- New function `PolicyEventsResourceType.ToPtr() *PolicyEventsResourceType`
## 0.1.1 (2022-02-22)
### Other Changes
- Remove the go_mod_tidy_hack.go file.
## 0.1.0 (2022-01-14)
- Init release. |
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:
byte oldKeyPadValues[]={0,0,0,0};
byte newKeyPadValues[]={0,0,0,0};
void setupKeypad(){
// matrix keypad
pinMode(keypadOutputClockPin, OUTPUT); // make the clock pin an output
pinMode(keypadOutputDataPin , OUTPUT); // make the data pin an output
pinMode(ploadPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, INPUT);
digitalWrite(clockPin, LOW);
digitalWrite(ploadPin, HIGH);
// nav keys
pinMode(navploadPin, OUTPUT);
pinMode(navclockPin, OUTPUT);
pinMode(navdataPin, INPUT);
digitalWrite(navclockPin, LOW);
digitalWrite(navploadPin, HIGH);
}
byte read_shift_regs(int row){
byte bitVal;
byte bytesVal = 0;
digitalWriteFast(ploadPin, HIGH);
/* Loop to read each bit value from the serial out line
* of the SN74HC165N.
*/
for(int i = 0; i < 8; i++)
{
bitVal = digitalReadFast(dataPin);
bytesVal |= (bitVal << i);
digitalWriteFast(clockPin, HIGH);
digitalWriteFast(clockPin, LOW);
}
digitalWriteFast(ploadPin, LOW);
return(bytesVal);
}
void scanKeypad(){
// scan the key matrix
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 254);
newKeyPadValues[0] = read_shift_regs(1);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 247);
newKeyPadValues[1] = read_shift_regs(2);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 251);
newKeyPadValues[2] = read_shift_regs(3);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 253);
newKeyPadValues[3] = read_shift_regs(4);
MIDI.read();
}
void handleKeypad(){
for (int row = 0; row < 4; row++){
if (newKeyPadValues[row] != oldKeyPadValues[row]){
oldKeyPadValues[row] = newKeyPadValues[row];
for (int i = 0; i < 8; i++) {
if (~newKeyPadValues[row] & (B00000001 << i) ){
curPosition = buttonMapping[row][i];
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 | 3 | byte oldKeyPadValues[]={0,0,0,0};
byte newKeyPadValues[]={0,0,0,0};
void setupKeypad(){
// matrix keypad
pinMode(keypadOutputClockPin, OUTPUT); // make the clock pin an output
pinMode(keypadOutputDataPin , OUTPUT); // make the data pin an output
pinMode(ploadPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, INPUT);
digitalWrite(clockPin, LOW);
digitalWrite(ploadPin, HIGH);
// nav keys
pinMode(navploadPin, OUTPUT);
pinMode(navclockPin, OUTPUT);
pinMode(navdataPin, INPUT);
digitalWrite(navclockPin, LOW);
digitalWrite(navploadPin, HIGH);
}
byte read_shift_regs(int row){
byte bitVal;
byte bytesVal = 0;
digitalWriteFast(ploadPin, HIGH);
/* Loop to read each bit value from the serial out line
* of the SN74HC165N.
*/
for(int i = 0; i < 8; i++)
{
bitVal = digitalReadFast(dataPin);
bytesVal |= (bitVal << i);
digitalWriteFast(clockPin, HIGH);
digitalWriteFast(clockPin, LOW);
}
digitalWriteFast(ploadPin, LOW);
return(bytesVal);
}
void scanKeypad(){
// scan the key matrix
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 254);
newKeyPadValues[0] = read_shift_regs(1);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 247);
newKeyPadValues[1] = read_shift_regs(2);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 251);
newKeyPadValues[2] = read_shift_regs(3);
MIDI.read();
shiftOut(keypadOutputDataPin, keypadOutputClockPin, LSBFIRST, 253);
newKeyPadValues[3] = read_shift_regs(4);
MIDI.read();
}
void handleKeypad(){
for (int row = 0; row < 4; row++){
if (newKeyPadValues[row] != oldKeyPadValues[row]){
oldKeyPadValues[row] = newKeyPadValues[row];
for (int i = 0; i < 8; i++) {
if (~newKeyPadValues[row] & (B00000001 << i) ){
curPosition = buttonMapping[row][i];
switch(editMode){
case 0: // play
currentStep = curPosition;
if ( patternData[currentChannel][0][curPosition] == 1){
patternData[currentChannel][0][curPosition] = 0;
} else {
patternData[currentChannel][0][curPosition] = 1;
}
break;
case 1: // edit
currentStep = curPosition;
updateLCD=1;
break;
case 2: // record
// pressed button
if (recordLastNote == curPosition){ // hold it
digitalWriteFast(gate[currentChannel], LOW);
patternData[currentChannel][0][tickCounter] = 2;
patternData[currentChannel][1][tickCounter] = curPosition+oct3;
}
if (recordLastNote != curPosition && recordLastPosition != i){
//MIDI.sendNoteOff(recordLastNote+oct3,0,currentChannel +1);
MIDI.sendNoteOn(curPosition+oct3,127,currentChannel +1);
digitalWriteFast(gate[currentChannel], HIGH);
patternData[currentChannel][0][tickCounter] = 1;
patternData[currentChannel][1][tickCounter] = curPosition+oct3;
recordLastNote = curPosition;
recordLastPosition = i;
}
break;
}
} else {
switch(editMode){
case 0: // play
break;
case 1:
break;
case 2:
//NEED TO MOVE THIS - RELEASE NOTE IS NOT FIRING!
if ( recordLastNote == curPosition && recordLastPosition == i) {
MIDI.sendNoteOff(recordLastNote+oct3,0,currentChannel +1);
digitalWriteFast(gate[currentChannel], LOW);
patternData[currentChannel][0][tickCounter] = 0;
patternData[currentChannel][1][tickCounter] = curPosition+oct3;
recordLastNote=0;
recordLastPosition = 0;
}
break;
}
}
}
MIDI.read();
updateMatrix = 1;
}
}
}
|
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 "game/ui/general/ingameoptions.h"
#include "forms/checkbox.h"
#include "forms/form.h"
#include "forms/label.h"
#include "forms/listbox.h"
#include "forms/scrollbar.h"
#include "forms/textbutton.h"
#include "forms/ui.h"
#include "framework/configfile.h"
#include "framework/data.h"
#include "framework/event.h"
#include "framework/framework.h"
#include "framework/keycodes.h"
#include "framework/sound.h"
#include "game/state/battle/battle.h"
#include "game/state/gamestate.h"
#include "game/ui/battle/battledebriefing.h"
#include "game/ui/general/cheatoptions.h"
#include "game/ui/general/mainmenu.h"
#include "game/ui/general/messagebox.h"
#include "game/ui/general/savemenu.h"
#include "game/ui/skirmish/skirmish.h"
#include "game/ui/tileview/cityview.h"
#include <list>
namespace OpenApoc
{
namespace
{
std::list<std::pair<UString, UString>> battleNotificationList = {
{"Notifications.Battle", "HostileSpotted"},
{"Notifications.Battle", "HostileDied"},
{"Notifications.Battle", "UnknownDied"},
{"Notifications.Battle", "AgentDiedBattle"},
{"Notifications.Battle", "AgentBrainsucked"},
{"Notifications.Battle", "AgentCriticallyWounded"},
{"Notifications.Battle", "AgentBadlyInjured"},
{"Notifications.Battle", "AgentInjured"},
{"Notifications.Battle", "AgentUnderFire"},
{"Notifications.Battle", "AgentUnconscious"},
{"Notifications.Battle", "AgentLeftCombat"},
{"Notifications.Battle", "AgentFrozen"},
{"Notifications.Battle", "AgentBerserk"},
{"Notifications.Battle", "AgentPanicked"},
{"Notifications.Battle", "AgentPanicOver"},
{"Notifications.Battle", "AgentPsiAttacked"},
{"Notifications.Battle", "AgentPsiControlled"},
{"Notifications.Battle", "AgentPsiOver"},
};
std::list<std::pair<UString, UString>> cityNotificationList = {
{"Notifications.City", "UfoSpotted"},
{"Notifications.City", "VehicleLightDamage"},
{"Notifications.City", "VehicleModerateDamage"},
{"Notifications.City", "Vehicl
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 "game/ui/general/ingameoptions.h"
#include "forms/checkbox.h"
#include "forms/form.h"
#include "forms/label.h"
#include "forms/listbox.h"
#include "forms/scrollbar.h"
#include "forms/textbutton.h"
#include "forms/ui.h"
#include "framework/configfile.h"
#include "framework/data.h"
#include "framework/event.h"
#include "framework/framework.h"
#include "framework/keycodes.h"
#include "framework/sound.h"
#include "game/state/battle/battle.h"
#include "game/state/gamestate.h"
#include "game/ui/battle/battledebriefing.h"
#include "game/ui/general/cheatoptions.h"
#include "game/ui/general/mainmenu.h"
#include "game/ui/general/messagebox.h"
#include "game/ui/general/savemenu.h"
#include "game/ui/skirmish/skirmish.h"
#include "game/ui/tileview/cityview.h"
#include <list>
namespace OpenApoc
{
namespace
{
std::list<std::pair<UString, UString>> battleNotificationList = {
{"Notifications.Battle", "HostileSpotted"},
{"Notifications.Battle", "HostileDied"},
{"Notifications.Battle", "UnknownDied"},
{"Notifications.Battle", "AgentDiedBattle"},
{"Notifications.Battle", "AgentBrainsucked"},
{"Notifications.Battle", "AgentCriticallyWounded"},
{"Notifications.Battle", "AgentBadlyInjured"},
{"Notifications.Battle", "AgentInjured"},
{"Notifications.Battle", "AgentUnderFire"},
{"Notifications.Battle", "AgentUnconscious"},
{"Notifications.Battle", "AgentLeftCombat"},
{"Notifications.Battle", "AgentFrozen"},
{"Notifications.Battle", "AgentBerserk"},
{"Notifications.Battle", "AgentPanicked"},
{"Notifications.Battle", "AgentPanicOver"},
{"Notifications.Battle", "AgentPsiAttacked"},
{"Notifications.Battle", "AgentPsiControlled"},
{"Notifications.Battle", "AgentPsiOver"},
};
std::list<std::pair<UString, UString>> cityNotificationList = {
{"Notifications.City", "UfoSpotted"},
{"Notifications.City", "VehicleLightDamage"},
{"Notifications.City", "VehicleModerateDamage"},
{"Notifications.City", "VehicleHeavyDamage"},
{"Notifications.City", "VehicleDestroyed"},
{"Notifications.City", "VehicleEscaping"},
{"Notifications.City", "VehicleNoAmmo"},
{"Notifications.City", "VehicleLowFuel"},
{"Notifications.City", "AgentDiedCity"},
{"Notifications.City", "AgentArrived"},
{"Notifications.City", "CargoArrived"},
{"Notifications.City", "TransferArrived"},
{"Notifications.City", "RecoveryArrived"},
{"Notifications.City", "VehicleRepaired"},
{"Notifications.City", "VehicleRearmed"},
{"Notifications.City", "NotEnoughAmmo"},
{"Notifications.City", "VehicleRefuelled"},
{"Notifications.City", "NotEnoughFuel"},
{"Notifications.City", "UnauthorizedVehicle"},
};
std::list<std::pair<UString, UString>> openApocList = {
{"OpenApoc.NewFeature", "UFODamageModel"},
{"OpenApoc.NewFeature", "InstantExplosionDamage"},
{"OpenApoc.NewFeature", "GravliftSounds"},
{"OpenApoc.NewFeature", "NoInstantThrows"},
{"OpenApoc.NewFeature", "PayloadExplosion"},
{"OpenApoc.NewFeature", "DisplayUnitPaths"},
{"OpenApoc.NewFeature", "AdditionalUnitIcons"},
{"OpenApoc.NewFeature", "AllowForceFiringParallel"},
{"OpenApoc.NewFeature", "RequireLOSToMaintainPsi"},
{"OpenApoc.NewFeature", "AdvancedInventoryControls"},
{"OpenApoc.NewFeature", "EnableAgentTemplates"},
{"OpenApoc.NewFeature", "FerryChecksRelationshipWhenBuying"},
{"OpenApoc.NewFeature", "AllowManualCityTeleporters"},
{"OpenApoc.NewFeature", "AllowManualCargoFerry"},
{"OpenApoc.NewFeature", "AllowSoldierTaxiUse"},
{"OpenApoc.NewFeature", "AllowAttackingOwnedVehicles"},
{"OpenApoc.NewFeature", "CallExistingFerry"},
{"OpenApoc.NewFeature", "AlternateVehicleShieldSound"},
{"OpenApoc.NewFeature", "StoreDroppedEquipment"},
{"OpenApoc.NewFeature", "EnforceCargoLimits"},
{"OpenApoc.NewFeature", "AllowNearbyVehicleLootPickup"},
{"OpenApoc.NewFeature", "AllowBuildingLootDeposit"},
{"OpenApoc.NewFeature", "ArmoredRoads"},
{"OpenApoc.NewFeature", "CrashingGroundVehicles"},
{"OpenApoc.NewFeature", "OpenApocCityControls"},
{"OpenApoc.NewFeature", "CollapseRaidedBuilding"},
{"OpenApoc.NewFeature", "ScrambleOnUnintentionalHit"},
{"OpenApoc.NewFeature", "MarketOnRight"},
{"OpenApoc.NewFeature", "CrashingDimensionGate"},
{"OpenApoc.NewFeature", "SkipTurboMovement"},
{"OpenApoc.NewFeature", "CrashingOutOfFuel"},
{"OpenApoc.NewFeature", "RunAndKneel"},
{"OpenApoc.NewFeature", "SeedRng"},
{"OpenApoc.NewFeature", "AutoReload"},
{"OpenApoc.Mod", "StunHostileAction"},
{"OpenApoc.Mod", "RaidHostileAction"},
{"OpenApoc.Mod", "CrashingVehicles"},
{"OpenApoc.Mod", "InvulnerableRoads"},
{"OpenApoc.Mod", "ATVTank"},
{"OpenApoc.Mod", "ATVAPC"},
{"OpenApoc.Mod", "BSKLauncherSound"},
};
std::vector<UString> listNames = {tr("Message Toggles"), tr("OpenApoc Features")};
} // namespace
InGameOptions::InGameOptions(sp<GameState> state)
: Stage(), menuform(ui().getForm("ingameoptions")), state(state)
{
}
InGameOptions::~InGameOptions() {}
void InGameOptions::saveList()
{
auto listControl = menuform->findControlTyped<ListBox>("NOTIFICATIONS_LIST");
for (auto &c : listControl->Controls)
{
auto name = c->getData<UString>();
config().set(*name, std::dynamic_pointer_cast<CheckBox>(c)->isChecked());
}
}
void InGameOptions::loadList(int id)
{
saveList();
curId = id;
menuform->findControlTyped<Label>("LIST_NAME")->setText(listNames[curId]);
std::list<std::pair<UString, UString>> *notificationList = nullptr;
switch (curId)
{
case 0:
notificationList =
state->current_battle ? &battleNotificationList : &cityNotificationList;
break;
case 1:
notificationList = &openApocList;
break;
}
auto listControl = menuform->findControlTyped<ListBox>("NOTIFICATIONS_LIST");
listControl->clear();
auto font = ui().getFont("smalfont");
for (auto &p : *notificationList)
{
auto checkBox = mksp<CheckBox>(fw().data->loadImage("BUTTON_CHECKBOX_TRUE"),
fw().data->loadImage("BUTTON_CHECKBOX_FALSE"));
checkBox->Size = {240, listControl->ItemSize};
UString full_name = p.first + "." + p.second;
checkBox->setData(mksp<UString>(full_name));
checkBox->setChecked(config().getBool(full_name));
auto label = checkBox->createChild<Label>(tr(config().describe(p.first, p.second)), font);
label->Size = {216, listControl->ItemSize};
label->Location = {24, 0};
listControl->addItem(checkBox);
}
}
void InGameOptions::loadNextList()
{
curId++;
if (curId > 1)
{
curId = 0;
}
loadList(curId);
}
void InGameOptions::begin()
{
/* Initialise all initial values */
menuform->findControlTyped<ScrollBar>("GLOBAL_GAIN_SLIDER")
->setValue(config().getInt("Framework.Audio.GlobalGain"));
menuform->findControlTyped<ScrollBar>("MUSIC_GAIN_SLIDER")
->setValue(config().getInt("Framework.Audio.MusicGain"));
menuform->findControlTyped<ScrollBar>("SAMPLE_GAIN_SLIDER")
->setValue(config().getInt("Framework.Audio.SampleGain"));
menuform->findControlTyped<CheckBox>("AUTO_SCROLL")
->setChecked(config().getBool("Options.Misc.AutoScroll"));
menuform->findControlTyped<CheckBox>("TOOL_TIPS")
->setChecked(config().getInt("Options.Misc.ToolTipDelay") > 0);
menuform->findControlTyped<CheckBox>("ACTION_MUSIC")
->setChecked(config().getBool("Options.Misc.ActionMusic"));
menuform->findControlTyped<CheckBox>("AUTO_EXECUTE_ORDERS")
->setChecked(config().getBool("Options.Misc.AutoExecute"));
if (state->current_battle)
{
menuform->findControlTyped<TextButton>("BUTTON_EXIT_BATTLE")->setVisible(true);
menuform->findControlTyped<TextButton>("BUTTON_SKIRMISH")->setVisible(false);
}
else
{
menuform->findControlTyped<TextButton>("BUTTON_EXIT_BATTLE")->setVisible(false);
menuform->findControlTyped<TextButton>("BUTTON_SKIRMISH")->setVisible(true);
}
menuform->findControlTyped<Label>("TEXT_FUNDS")->setText(state->getPlayerBalance());
loadList(0);
}
void InGameOptions::pause() {}
void InGameOptions::resume() {}
void InGameOptions::finish()
{
/* Store persistent options */
config().set("Framework.Audio.GlobalGain",
menuform->findControlTyped<ScrollBar>("GLOBAL_GAIN_SLIDER")->getValue());
config().set("Framework.Audio.MusicGain",
menuform->findControlTyped<ScrollBar>("MUSIC_GAIN_SLIDER")->getValue());
config().set("Framework.Audio.SampleGain",
menuform->findControlTyped<ScrollBar>("SAMPLE_GAIN_SLIDER")->getValue());
config().set("Options.Misc.AutoScroll",
menuform->findControlTyped<CheckBox>("AUTO_SCROLL")->isChecked());
config().set("Options.Misc.ToolTipDelay",
menuform->findControlTyped<CheckBox>("TOOL_TIPS")->isChecked() ? 500 : 0);
config().set("Options.Misc.ActionMusic",
menuform->findControlTyped<CheckBox>("ACTION_MUSIC")->isChecked());
config().set("Options.Misc.AutoExecute",
menuform->findControlTyped<CheckBox>("AUTO_EXECUTE_ORDERS")->isChecked());
saveList();
}
void InGameOptions::eventOccurred(Event *e)
{
menuform->eventOccured(e);
if (e->type() == EVENT_KEY_DOWN)
{
if (e->keyboard().KeyCode == SDLK_ESCAPE || e->keyboard().KeyCode == SDLK_RETURN ||
e->keyboard().KeyCode == SDLK_KP_ENTER)
{
menuform->findControl("BUTTON_OK")->click();
return;
}
}
if (e->type() == EVENT_FORM_INTERACTION && e->forms().EventFlag == FormEventType::ButtonClick)
{
if (e->forms().RaisedBy->Name == "BUTTON_OK")
{
fw().stageQueueCommand({StageCmd::Command::POP});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_ABANDONGAME")
{
fw().stageQueueCommand({StageCmd::Command::REPLACEALL, mksp<MainMenu>()});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_QUIT")
{
fw().stageQueueCommand({StageCmd::Command::QUIT});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_SAVEGAME")
{
fw().stageQueueCommand(
{StageCmd::Command::PUSH, mksp<SaveMenu>(SaveMenuAction::Save, state)});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_DELETESAVEDGAME")
{
fw().stageQueueCommand(
{StageCmd::Command::PUSH, mksp<SaveMenu>(SaveMenuAction::Delete, state)});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_LOADGAME")
{
fw().stageQueueCommand(
{StageCmd::Command::PUSH, mksp<SaveMenu>(SaveMenuAction::Load, state)});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_NEXT_LIST")
{
loadNextList();
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_CHEATS")
{
fw().stageQueueCommand({StageCmd::Command::PUSH, mksp<CheatOptions>(state)});
return;
}
if (e->forms().RaisedBy->Name == "BUTTON_EXIT_BATTLE")
{
int unitsLost = state->current_battle->killStrandedUnits(
*state, state->current_battle->currentPlayer, true);
fw().stageQueueCommand(
{StageCmd::Command::PUSH,
mksp<MessageBox>(tr("Abort Mission"),
format("%s %d", tr("Units Lost :"), unitsLost),
MessageBox::ButtonOptions::YesNo, [this] {
state->current_battle->abortMission(*state);
Battle::finishBattle(*state);
fw().stageQueueCommand({StageCmd::Command::REPLACEALL,
mksp<BattleDebriefing>(state)});
})});
}
else if (e->forms().RaisedBy->Name == "BUTTON_SKIRMISH")
{
fw().stageQueueCommand({StageCmd::Command::PUSH, mksp<Skirmish>(state)});
}
}
if (e->type() == EVENT_FORM_INTERACTION &&
e->forms().EventFlag == FormEventType::ScrollBarChange)
{
if (e->forms().RaisedBy->Name == "GLOBAL_GAIN_SLIDER")
{
auto slider = std::dynamic_pointer_cast<ScrollBar>(e->forms().RaisedBy);
if (!slider)
{
LogError("Failed to cast \"GLOBAL_GAIN_SLIDER\" control to ScrollBar");
return;
}
float gain =
static_cast<float>(slider->getValue()) / static_cast<float>(slider->getMaximum());
fw().soundBackend->setGain(SoundBackend::Gain::Global, gain);
}
else if (e->forms().RaisedBy->Name == "MUSIC_GAIN_SLIDER")
{
auto slider = std::dynamic_pointer_cast<ScrollBar>(e->forms().RaisedBy);
if (!slider)
{
LogError("Failed to cast \"MUSIC_GAIN_SLIDER\" control to ScrollBar");
return;
}
float gain =
static_cast<float>(slider->getValue()) / static_cast<float>(slider->getMaximum());
fw().soundBackend->setGain(SoundBackend::Gain::Music, gain);
}
else if (e->forms().RaisedBy->Name == "SAMPLE_GAIN_SLIDER")
{
auto slider = std::dynamic_pointer_cast<ScrollBar>(e->forms().RaisedBy);
if (!slider)
{
LogError("Failed to cast \"SAMPLE_GAIN_SLIDER\" control to ScrollBar");
return;
}
float gain =
static_cast<float>(slider->getValue()) / static_cast<float>(slider->getMaximum());
fw().soundBackend->setGain(SoundBackend::Gain::Sample, gain);
}
}
if (e->type() == EVENT_FORM_INTERACTION &&
e->forms().EventFlag == FormEventType::CheckBoxChange)
{
if (e->forms().RaisedBy->Name == "SOME_NON_CONFIG_FILE_OPTION_OR_HAS_TO_EFFECT_IMMEDIATELY")
{
auto box = std::dynamic_pointer_cast<CheckBox>(e->forms().RaisedBy);
// Set non-config option here or do the effect
}
}
}
void InGameOptions::update() { menuform->update(); }
void InGameOptions::render()
{
fw().stageGetPrevious(this->shared_from_this())->render();
menuform->render();
}
bool InGameOptions::isTransition() { return false; }
}; // namespace OpenApoc
|
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:
class Node {
constructor(next, value) {
this.next = next
this.value = value
}
}
class Stack {
constructor() {
this.stack = null
}
push(element) {
let head = this.stack
let newNode = new Node(null, element)
if (!head) {
this.stack = newNode
} else {
newNode.next = head
this.stack = newNode
}
}
pop() {
let head = this.stack
if (!head) return 'Stack is empty!'
this.stack = head.next
return head.value
}
peek() {
if(!this.stack) return 'Stack is empty!'
return this.stack.value
}
}
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 | class Node {
constructor(next, value) {
this.next = next
this.value = value
}
}
class Stack {
constructor() {
this.stack = null
}
push(element) {
let head = this.stack
let newNode = new Node(null, element)
if (!head) {
this.stack = newNode
} else {
newNode.next = head
this.stack = newNode
}
}
pop() {
let head = this.stack
if (!head) return 'Stack is empty!'
this.stack = head.next
return head.value
}
peek() {
if(!this.stack) return 'Stack is empty!'
return this.stack.value
}
} |
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 { Action } from 'redux-actions';
import { LOGIN, LOGIN_FAILURE, LOGIN_SUCCESS, UPDATE_PASSWORD, UPDATE_USERNAME } from '../constants/login';
export enum LoginStatus {
Failure,
Initial,
Pending,
Success
}
export function loginReducer(state = { password: '', status: LoginStatus.Initial, username: '' }, action: Action<any>) {
switch (action.type) {
case UPDATE_PASSWORD:
return Object.assign({}, state, { password: action.payload.password });
case UPDATE_USERNAME:
return Object.assign({}, state, { username: action.payload.username });
case LOGIN:
return Object.assign({}, state, { status: LoginStatus.Pending });
case LOGIN_SUCCESS:
return Object.assign({}, state, { status: LoginStatus.Failure });
case LOGIN_FAILURE:
return Object.assign({}, state, { status: LoginStatus.Failure });
default:
return state;
}
}
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 { Action } from 'redux-actions';
import { LOGIN, LOGIN_FAILURE, LOGIN_SUCCESS, UPDATE_PASSWORD, UPDATE_USERNAME } from '../constants/login';
export enum LoginStatus {
Failure,
Initial,
Pending,
Success
}
export function loginReducer(state = { password: '', status: LoginStatus.Initial, username: '' }, action: Action<any>) {
switch (action.type) {
case UPDATE_PASSWORD:
return Object.assign({}, state, { password: action.payload.password });
case UPDATE_USERNAME:
return Object.assign({}, state, { username: action.payload.username });
case LOGIN:
return Object.assign({}, state, { status: LoginStatus.Pending });
case LOGIN_SUCCESS:
return Object.assign({}, state, { status: LoginStatus.Failure });
case LOGIN_FAILURE:
return Object.assign({}, state, { status: LoginStatus.Failure });
default:
return state;
}
}
|
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 <stdio.h>
#include <cs50.h>
#include <math.h>
int main()
{
// get input from user and save it to variable
// get sum of all card digits
// display result
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>"
| c | 1 | #include <stdio.h>
#include <cs50.h>
#include <math.h>
int main()
{
// get input from user and save it to variable
// get sum of all card digits
// display result
return 0;
}
|
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 GuiaLocaliza\Companies\Admin\Domains\Models\Subcategory;
use GuiaLocaliza\Companies\Admin\Domains\Models\Banner\Banner;
use GuiaLocaliza\Companies\Admin\Domains\Models\Company\Company;
use GuiaLocaliza\Companies\Admin\Domains\Models\Category\Category;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
protected $connection = 'companies';
protected $fillable = [
'id',
'category_id',
'name',
'active'
];
protected $dates = [
'created_at',
'updated_at',
];
public function companies()
{
return $this->belongsToMany(Company::class, 'subcategory_company');
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function banners()
{
return $this->belongsToMany(Banner::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
namespace GuiaLocaliza\Companies\Admin\Domains\Models\Subcategory;
use GuiaLocaliza\Companies\Admin\Domains\Models\Banner\Banner;
use GuiaLocaliza\Companies\Admin\Domains\Models\Company\Company;
use GuiaLocaliza\Companies\Admin\Domains\Models\Category\Category;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
protected $connection = 'companies';
protected $fillable = [
'id',
'category_id',
'name',
'active'
];
protected $dates = [
'created_at',
'updated_at',
];
public function companies()
{
return $this->belongsToMany(Company::class, 'subcategory_company');
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function banners()
{
return $this->belongsToMany(Banner::class);
}
}
|
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:
module Crud
#to import the module to other files:
#same directory: require_relative 'crud'
#can use the module through require 'crud' -> This wouldnt work if its in the same directory
#in that case, put this before require 'crud' => $LOAD_PATH << "."
#in the file that is requiring the module, call Crud.(methods from the module)
#in the file that is the module (in this case, bcrypt.rb),when loading the method, you should do this for ALL methods -> def Crud.create_new_hash ...
# or -> def self.create_new_hash ...
require 'bcrypt'
users = [
{username: "Jonathan", password: "<PASSWORD>", location: "havelock road", school: "GA" },
{username: "Anne", password: "<PASSWORD>", location: "purmei road", school: "Smart Local" },
{username: "Gid", password: "<PASSWORD>", location: "panjang road", school: "Church of Christ" },
{username: "Timo", password: "<PASSWORD>", location: "compasss road", school: "Info tech" },
{username: "Ben", password: "<PASSWORD>", location: "bedok road", school: "Student" },
{username: "NJ", password: "<PASSWORD>", location: "bishan road", school: "CyberSecurity" },
{username: "Lee", password: "<PASSWORD>", location: "bukit timah road", school: "parliament" },
{username: "Handy", password: "<PASSWORD>", location: "sungei road", school: "Sign on regular officer" },
{username: "Akira", password: "<PASSWORD>", location: "orchard road", school: "GA instructor" },
{username: "Rachel", password: "<PASSWORD>", location: "kallang road", school: "Interior Designer" },
{username: "Hosy", password: "<PASSWORD>", location: "panjang road", school: "Professor at NTU" },
{username: "Cheng", password: "<PASSWORD>", location: "changi airport road", school: "Cleaner" }
]
# my_password = BCrypt::Password.create('my <PASSWORD>')
#=> <PASSWORD>"
# puts my_password
# my_password = BCrypt::Password.new('<PASSWORD>.')
# puts my_password == '<PASSWORD>'
def create_new_hash(password)
BCrypt::Password.creat
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 | module Crud
#to import the module to other files:
#same directory: require_relative 'crud'
#can use the module through require 'crud' -> This wouldnt work if its in the same directory
#in that case, put this before require 'crud' => $LOAD_PATH << "."
#in the file that is requiring the module, call Crud.(methods from the module)
#in the file that is the module (in this case, bcrypt.rb),when loading the method, you should do this for ALL methods -> def Crud.create_new_hash ...
# or -> def self.create_new_hash ...
require 'bcrypt'
users = [
{username: "Jonathan", password: "<PASSWORD>", location: "havelock road", school: "GA" },
{username: "Anne", password: "<PASSWORD>", location: "purmei road", school: "Smart Local" },
{username: "Gid", password: "<PASSWORD>", location: "panjang road", school: "Church of Christ" },
{username: "Timo", password: "<PASSWORD>", location: "compasss road", school: "Info tech" },
{username: "Ben", password: "<PASSWORD>", location: "bedok road", school: "Student" },
{username: "NJ", password: "<PASSWORD>", location: "bishan road", school: "CyberSecurity" },
{username: "Lee", password: "<PASSWORD>", location: "bukit timah road", school: "parliament" },
{username: "Handy", password: "<PASSWORD>", location: "sungei road", school: "Sign on regular officer" },
{username: "Akira", password: "<PASSWORD>", location: "orchard road", school: "GA instructor" },
{username: "Rachel", password: "<PASSWORD>", location: "kallang road", school: "Interior Designer" },
{username: "Hosy", password: "<PASSWORD>", location: "panjang road", school: "Professor at NTU" },
{username: "Cheng", password: "<PASSWORD>", location: "changi airport road", school: "Cleaner" }
]
# my_password = BCrypt::Password.create('my <PASSWORD>')
#=> <PASSWORD>"
# puts my_password
# my_password = BCrypt::Password.new('<PASSWORD>.')
# puts my_password == '<PASSWORD>'
def create_new_hash(password)
BCrypt::Password.create(password)
end
def verify_hash(password)
BCrypt::Password.new(password)
end
# new_password = create_new_hash('<PASSWORD>')
# puts new_password
# puts new_password == '<PASSWORD>' #-> true
# puts new_password == '<PASSWORD>' #-> false
# puts verify_hash('$2a$10$3HR5btzacqMQZdbhNg25XeUgHMEktUy0W.LOvIljZ3oknAEv6KIxS') == 'Something'
def create_secure_users(list_of_user)
list_of_user.each do |user|
user[:password] = create_new_hash(user[:password])
end
list_of_user
end
puts create_secure_users(users)
def authenticate_user(username, password, list_of_user)
list_of_user.each do |user|
if user[:username] == username && verify_hash(user[:password]) == password
return user
end
end
"Credentials are not correct!"
end
puts authenticate_user("Jonathan", 123456, users)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.