prompt
stringlengths 1.3k
3.64k
| language
stringclasses 16
values | label
int64 -1
5
| text
stringlengths 14
130k
|
---|---|---|---|
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:
## react-native-alerts-help
> Atualmente, o desempenho não é testado no IOS.
<br />
Minha primeira lib para react-native!
#### Demostração da lib

### Instalação
React-native-alerts-help usa react-native-vector-icons como dependencia.
instalação:
```bash
npm install react-native-alerts-help
```
link:
```bash
react-native link
```
### Usage
```js
import Alert from 'react-native-alerts-help';
<Alert
visible={this.state.warning}
onPress={() => this.close()}
icon="warning"
color="#f1c40f"
title="Warning.."
text="Fill in all the fields below."
textButton="Close"
/>
```
### Props
| name | type | description |
| :----------------- | :------------ | :--------------------------------------- |
| visible | bool | Para que o modal seja visivel. |
| icon | string | Nome do icone FontAwesome https://oblador.github.io/react-native-vector-icons/ |
| color | string | Cor hexadecimal para o botão e icone |
| title | string | Texto de titulo |
| text | string | Texto do corpo da alerta |
| textButton | string | Texto do botão |
<br />
__event:__
| name | type | description |
| :----------------- | :------- | :-------------------------------------- |
| onClose | function | Ao fechar a alerta. |
| onPress | function | Quando clica no botão. |
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
markdown
| 3 |
## react-native-alerts-help
> Atualmente, o desempenho não é testado no IOS.
<br />
Minha primeira lib para react-native!
#### Demostração da lib

### Instalação
React-native-alerts-help usa react-native-vector-icons como dependencia.
instalação:
```bash
npm install react-native-alerts-help
```
link:
```bash
react-native link
```
### Usage
```js
import Alert from 'react-native-alerts-help';
<Alert
visible={this.state.warning}
onPress={() => this.close()}
icon="warning"
color="#f1c40f"
title="Warning.."
text="Fill in all the fields below."
textButton="Close"
/>
```
### Props
| name | type | description |
| :----------------- | :------------ | :--------------------------------------- |
| visible | bool | Para que o modal seja visivel. |
| icon | string | Nome do icone FontAwesome https://oblador.github.io/react-native-vector-icons/ |
| color | string | Cor hexadecimal para o botão e icone |
| title | string | Texto de titulo |
| text | string | Texto do corpo da alerta |
| textButton | string | Texto do botão |
<br />
__event:__
| name | type | description |
| :----------------- | :------- | :-------------------------------------- |
| onClose | function | Ao fechar a alerta. |
| onPress | function | Quando clica no botão. |
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.lib.core.net.rtf2;
import com.lib.core.net.callback.IError;
import com.lib.core.net.callback.IFailure;
import com.lib.core.net.callback.IRequest;
import com.lib.core.net.callback.ISuccess;
import com.lib.core.net.callback.RequestCallbacks;
import java.util.HashMap;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
/**
* @Description: 网络可用框架接口,提供给框架外使用的
* @Author itsdf07
* @E-Mail <EMAIL>
* @Github https://github.com/itsdf07
* @Date 2020/4/2
*/
public class NetClient {
private final HashMap<String, Object> PARAMS;
private final String URL;
private final IRequest REQUEST;
private final ISuccess SUCCESS;
private final IFailure FAILURE;
private final IError ERROR;
private final RequestBody BODY;
public NetClient(HashMap<String, Object> params,
String url,
IRequest request,
ISuccess success,
IFailure failure,
IError error,
RequestBody body) {
this.PARAMS = params;
this.URL = url;
this.REQUEST = request;
this.SUCCESS = success;
this.FAILURE = failure;
this.ERROR = error;
this.BODY = body;
}
public static NetClientBuilder create() {
return new NetClientBuilder();
}
/**
* 开始实现真实的网络操作
*
* @param method
*/
private void request(HttpMethod method) {
final ApiService service = NetCreator.getRestService();
Call<String> call = null;
if (REQUEST != null) {
REQUEST.onRequestStart();
}
switch (method) {
case GET:
if (null == PARAMS || PARAMS.size() == 0) {
call = service.get(URL);
} else {
call = service.get(URL, PARAMS);
}
break;
case POST:
call = service.post(URL, PARAMS);
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 |
package com.lib.core.net.rtf2;
import com.lib.core.net.callback.IError;
import com.lib.core.net.callback.IFailure;
import com.lib.core.net.callback.IRequest;
import com.lib.core.net.callback.ISuccess;
import com.lib.core.net.callback.RequestCallbacks;
import java.util.HashMap;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
/**
* @Description: 网络可用框架接口,提供给框架外使用的
* @Author itsdf07
* @E-Mail <EMAIL>
* @Github https://github.com/itsdf07
* @Date 2020/4/2
*/
public class NetClient {
private final HashMap<String, Object> PARAMS;
private final String URL;
private final IRequest REQUEST;
private final ISuccess SUCCESS;
private final IFailure FAILURE;
private final IError ERROR;
private final RequestBody BODY;
public NetClient(HashMap<String, Object> params,
String url,
IRequest request,
ISuccess success,
IFailure failure,
IError error,
RequestBody body) {
this.PARAMS = params;
this.URL = url;
this.REQUEST = request;
this.SUCCESS = success;
this.FAILURE = failure;
this.ERROR = error;
this.BODY = body;
}
public static NetClientBuilder create() {
return new NetClientBuilder();
}
/**
* 开始实现真实的网络操作
*
* @param method
*/
private void request(HttpMethod method) {
final ApiService service = NetCreator.getRestService();
Call<String> call = null;
if (REQUEST != null) {
REQUEST.onRequestStart();
}
switch (method) {
case GET:
if (null == PARAMS || PARAMS.size() == 0) {
call = service.get(URL);
} else {
call = service.get(URL, PARAMS);
}
break;
case POST:
call = service.post(URL, PARAMS);
break;
case POST_RAW:
call = service.postRaw(URL, BODY);
break;
default:
break;
}
if (call != null) {
call.enqueue(getReqeustCallback());
}
}
private Callback<String> getReqeustCallback() {
return new RequestCallbacks(REQUEST, SUCCESS, FAILURE, ERROR);
}
//各种请求
public final void get() {
request(HttpMethod.GET);
}
public final void post() {
request(HttpMethod.POST);
}
public final void postRaw() {
request(HttpMethod.POST_RAW);
}
}
|
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 "main.h"
/**
*print_number - prints an integer.
*only using the putchar function.
*noarrays and pointers.
*@n: integer to be printed.
*
*Return: void.
*/
void print_number(int n)
{
unsigned int num;
/*check if number is negative*/
num = n;
if (n < 0)
{
_putchar(45);
num = -n;
}
/* print number by recursion*/
if (num / 10)
{
print_number(num / 10);
}
_putchar((num % 10) + '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
| 4 |
#include "main.h"
/**
*print_number - prints an integer.
*only using the putchar function.
*noarrays and pointers.
*@n: integer to be printed.
*
*Return: void.
*/
void print_number(int n)
{
unsigned int num;
/*check if number is negative*/
num = n;
if (n < 0)
{
_putchar(45);
num = -n;
}
/* print number by recursion*/
if (num / 10)
{
print_number(num / 10);
}
_putchar((num % 10) + '0');
}
|
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:
insert into db_io.logs (when, msg, level, logger_name, thread) values (?, ?, ?, ?, ?)
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 |
insert into db_io.logs (when, msg, level, logger_name, thread) values (?, ?, ?, ?, ?)
|
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 io.ehdev.account.database.impl
import io.ehdev.account.database.api.AccessManager
import io.ehdev.account.db.tables.RuleGrantTable
import io.ehdev.account.model.resource.AccessRuleModel
import io.ehdev.account.model.resource.RoleId
import io.ehdev.account.model.resource.UserId
import io.ehdev.account.model.user.AccountManagerUser
import org.jooq.DSLContext
import org.jooq.impl.DSL
class DefaultAccessManager(private val dslContext: DSLContext) : AccessManager {
private val grantTable = RuleGrantTable.RULE_GRANT
override fun grantPermission(user: AccountManagerUser, role: AccessRuleModel) {
dslContext
.insertInto(grantTable)
.columns(grantTable.RULE_ID, grantTable.USER_ID)
.values(role.id, user.userId)
.onDuplicateKeyIgnore()
.execute()
}
override fun revokePermission(user: AccountManagerUser, role: AccessRuleModel) {
dslContext
.deleteFrom(grantTable)
.where(grantTable.RULE_ID.eq(role.id), grantTable.USER_ID.eq(user.userId))
.execute()
}
override fun hasPermission(user: AccountManagerUser, role: AccessRuleModel): Boolean {
val count = dslContext
.select(DSL.count())
.from(grantTable)
.where(grantTable.RULE_ID.eq(role.id), grantTable.USER_ID.eq(user.userId))
.fetchOne(0, Int::class.java)
return count == 1 || user.userType == AccountManagerUser.UserType.SuperAdmin
}
override fun getUsersForRole(role: AccessRuleModel): List<UserId> {
return dslContext
.select(grantTable.USER_ID)
.from(grantTable)
.where(grantTable.RULE_ID.eq(role.id))
.map { it -> createUserId(it.get(grantTable.USER_ID)) }
}
override fun getRolesForUser(user: AccountManagerUser): List<RoleId> {
return dslContext
.select(grantTable.RU
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
| 3 |
package io.ehdev.account.database.impl
import io.ehdev.account.database.api.AccessManager
import io.ehdev.account.db.tables.RuleGrantTable
import io.ehdev.account.model.resource.AccessRuleModel
import io.ehdev.account.model.resource.RoleId
import io.ehdev.account.model.resource.UserId
import io.ehdev.account.model.user.AccountManagerUser
import org.jooq.DSLContext
import org.jooq.impl.DSL
class DefaultAccessManager(private val dslContext: DSLContext) : AccessManager {
private val grantTable = RuleGrantTable.RULE_GRANT
override fun grantPermission(user: AccountManagerUser, role: AccessRuleModel) {
dslContext
.insertInto(grantTable)
.columns(grantTable.RULE_ID, grantTable.USER_ID)
.values(role.id, user.userId)
.onDuplicateKeyIgnore()
.execute()
}
override fun revokePermission(user: AccountManagerUser, role: AccessRuleModel) {
dslContext
.deleteFrom(grantTable)
.where(grantTable.RULE_ID.eq(role.id), grantTable.USER_ID.eq(user.userId))
.execute()
}
override fun hasPermission(user: AccountManagerUser, role: AccessRuleModel): Boolean {
val count = dslContext
.select(DSL.count())
.from(grantTable)
.where(grantTable.RULE_ID.eq(role.id), grantTable.USER_ID.eq(user.userId))
.fetchOne(0, Int::class.java)
return count == 1 || user.userType == AccountManagerUser.UserType.SuperAdmin
}
override fun getUsersForRole(role: AccessRuleModel): List<UserId> {
return dslContext
.select(grantTable.USER_ID)
.from(grantTable)
.where(grantTable.RULE_ID.eq(role.id))
.map { it -> createUserId(it.get(grantTable.USER_ID)) }
}
override fun getRolesForUser(user: AccountManagerUser): List<RoleId> {
return dslContext
.select(grantTable.RULE_ID)
.from(grantTable)
.where(grantTable.USER_ID.eq(user.userId))
.map { it -> createRoleId(it.get(grantTable.RULE_ID)) }
}
companion object {
fun createUserId(id: Long): UserId {
return object : UserId {
override fun getUserId(): Long = id
}
}
fun createRoleId(id: Long): RoleId {
return object : RoleId {
override fun getRoleId(): Long = id
}
}
}
}
|
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 COMMANDE_H
#define COMMANDE_H
#include <QWidget>
#include <clienttcp.h>
namespace Ui {
class commande;
}
class commande : public QWidget
{
Q_OBJECT
public:
explicit commande(QWidget *parent = 0);
~commande();
int number;
void connexion();
private slots:
void on_pushButton_camera1_clicked();
void on_pushButton_camera2_clicked();
void on_pushButton_camera3_clicked();
void on_pushButton_camera4_clicked();
private:
Ui::commande *ui;
ClientTcp ClientCamera;
};
#endif // COMMANDE_H
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 |
#ifndef COMMANDE_H
#define COMMANDE_H
#include <QWidget>
#include <clienttcp.h>
namespace Ui {
class commande;
}
class commande : public QWidget
{
Q_OBJECT
public:
explicit commande(QWidget *parent = 0);
~commande();
int number;
void connexion();
private slots:
void on_pushButton_camera1_clicked();
void on_pushButton_camera2_clicked();
void on_pushButton_camera3_clicked();
void on_pushButton_camera4_clicked();
private:
Ui::commande *ui;
ClientTcp ClientCamera;
};
#endif // COMMANDE_H
|
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
session_start(); ?>
<?php
if (empty($_SESSION['username'])) {
?>
<script language="JavaScript">
window.location="index.php";
</script><?php } else { ?>
<html>
<title>Mark | Student Management Tool</title>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<link rel="stylesheet" href="css/thickbox.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
</head>
<body>
<div id="grad1">
<div class="bodydiv">
<div id="logo" align="left">
<h1><a href="Home.php">UAPians.Net </a></h1>
<p>A Stack of Uap Students ...UNOFFICIAL...</p>
</div>
<div class="realbody">
<?php
//$connect=mysql_connect("localhost","root","");
//$select_db=mysql_select_db("mylab");
$strquery="SELECT SPortrait,username FROM s_info INNER JOIN userinfo ON s_info.SID=userinfo.SID WHERE username='{$b}'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$SPortrait=mysql_result($results,$i,"SPortrait");
$username=mysql_result($results,$i,"username");
?>
<div id='cssmenu' align="center" style="vertical-align:middle">
<ul>
<li style="vertical-align:middle;"><a href='My_Profile.php'><span><img style="width:15px; height:15px; border:1px solid white; vertical-align:middle"src="<?php echo $SPortrait; ?>" alt="Profile Picture"><span> Profile</span></a></li>
<li><a href='Home.php'><span>Home</span></a></li>
<li><a href='Student_List.php'><span>Students</span></a></li>
<li><a href='Employee_List.php'><span>Employees</span></a></li>
<li><a href='Blog_List.php'><span>CSE Blog</span></a></li>
<li><a href='Blood_List.php'><span>Blood</span></a></li>
<li><a href='About.php'><span>About</span></a></li>
</ul>
</div>
<div align="center">
<div>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("my
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
session_start(); ?>
<?php
if (empty($_SESSION['username'])) {
?>
<script language="JavaScript">
window.location="index.php";
</script><?php } else { ?>
<html>
<title>Mark | Student Management Tool</title>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<link rel="stylesheet" href="css/thickbox.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
</head>
<body>
<div id="grad1">
<div class="bodydiv">
<div id="logo" align="left">
<h1><a href="Home.php">UAPians.Net </a></h1>
<p>A Stack of Uap Students ...UNOFFICIAL...</p>
</div>
<div class="realbody">
<?php
//$connect=mysql_connect("localhost","root","");
//$select_db=mysql_select_db("mylab");
$strquery="SELECT SPortrait,username FROM s_info INNER JOIN userinfo ON s_info.SID=userinfo.SID WHERE username='{$b}'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$SPortrait=mysql_result($results,$i,"SPortrait");
$username=mysql_result($results,$i,"username");
?>
<div id='cssmenu' align="center" style="vertical-align:middle">
<ul>
<li style="vertical-align:middle;"><a href='My_Profile.php'><span><img style="width:15px; height:15px; border:1px solid white; vertical-align:middle"src="<?php echo $SPortrait; ?>" alt="Profile Picture"><span> Profile</span></a></li>
<li><a href='Home.php'><span>Home</span></a></li>
<li><a href='Student_List.php'><span>Students</span></a></li>
<li><a href='Employee_List.php'><span>Employees</span></a></li>
<li><a href='Blog_List.php'><span>CSE Blog</span></a></li>
<li><a href='Blood_List.php'><span>Blood</span></a></li>
<li><a href='About.php'><span>About</span></a></li>
</ul>
</div>
<div align="center">
<div>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SName FROM s_info WHERE SID='" . $_GET["SID"] . "'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$SName=mysql_result($results,$i,"SName");
?>
</div>
<div>
<p align="center" style="font-size:27px; font-weight:bold; padding-top:25; padding-bottom:25"><?php echo $SName ; ?></p>
<p align="center" style="font-size:25px">1st Year 1st Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='1st Year 1st Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">1st Year 2nd Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='1st Year 2nd Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">2nd Year 1st Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='2nd Year 1st Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">2nd Year 2nd Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='2nd Year 2nd Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">3rd Year 1st Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='3rd Year 1st Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">3rd Year 2nd Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='3rd Year 2nd Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">4th Year 1st Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='4th Year 1st Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
<div>
<p align="center" style="font-size:25px">4th Year 2nd Semister</p>
<table align="center"width="900" border="1">
<tr>
<td height="50" align="center" style="width:300">Subject Code</td>
<td align="center" style="width:300">subject Name</td>
<td align="center" style="width:300">Mark</td>
</tr>
<?php
$connect=mysql_connect("localhost","root","");
$select_db=mysql_select_db("mylab");
$strquery="SELECT SMName,SName,CCode, CName,Mark FROM c_info INNER JOIN m_info ON m_info.CID=c_info.CID INNER JOIN s_info ON s_info.SID=m_info.SID INNER JOIN sm_info ON s_info.SMID=sm_info.SMID WHERE m_info.SID='" . $_GET["SID"] . "' AND SMName='4th Year 2nd Semister'";
$results=mysql_query($strquery);
$num=mysql_numrows($results);
$i=0;
while ($i< $num)
{
$SName=mysql_result($results,$i,"SName");
$Semester_Name=mysql_result($results,$i,"SMName");
$Student_Name=mysql_result($results,$i,"SName");
$Course_Code=mysql_result($results,$i,"CCode");
$Course_Name=mysql_result($results,$i,"CName");
$Obtained_Mark=mysql_result($results,$i,"Mark");
?>
<tr>
<td align="center" style="width:300"><?php echo $Course_Code ; ?></td>
<td align="center" style="width:300"><?php echo $Course_Name ; ?></td>
<td align="center" style="width:300"><?php echo $Obtained_Mark ; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
<br>
<br>
<br>
<br>
</div>
</div>
</div>
</body>
</html>
<?php
}?>
|
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 factlin_sample.junit4
import com.maeharin.factlin.fixtures.UsersFixture
import com.maeharin.factlin.fixtures.insertUsersFixture
import com.maeharin.factlin.fixtures_ext.active
import com.maeharin.factlin.fixtures_ext.stopped
import com.maeharin.factlin_sample.usecase.showUsers
import com.maeharin.factlin_sample.domain.UserJobType
import com.maeharin.factlin_sample.usecase.CreateOrUpdateUserInput
import com.maeharin.factlin_sample.usecase.createUser
import com.maeharin.factlin_sample.usecase.showUserById
import com.ninja_squad.dbsetup.destination.DriverManagerDestination
import com.ninja_squad.dbsetup_kotlin.dbSetup
import org.jetbrains.exposed.sql.Database
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.LocalDate
class UserUseCaseTest {
val dbUrl = "jdbc:postgresql://${System.getenv("DB_HOST")}/dvdrental"
val dbUser = "postgres"
val dbPassword = ""
val dbDriver = "org.postgresql.Driver"
val dest = DriverManagerDestination(dbUrl, dbUser, dbPassword)
init {
Class.forName(dbDriver)
Database.connect(url = dbUrl, driver = dbDriver, user = dbUser, password = dbPassword)
}
@Test
fun `show users`() {
dbSetup(dest) {
deleteAllFrom(listOf("users"))
insertUsersFixture(UsersFixture().active().copy(id = 1, name = "テスト1"))
insertUsersFixture(UsersFixture().stopped().copy(id = 2, name = "テスト2"))
}.launch()
val users = showUsers()
users[0].also { user ->
assertEquals(1, user.id)
assertEquals("テスト1", user.name)
assertEquals(UserJobType.ENGINEER, user.job)
}
users[1].also { user ->
assertEquals(2, user.id)
assertEquals("テスト2", user.name)
assertEquals(UserJobType.ENGINEER, user.job)
}
}
@Test
fun `show user by id`() {
dbSetup(dest) {
deleteAllFrom(listOf("users"))
insertUsersFixture(Us
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 factlin_sample.junit4
import com.maeharin.factlin.fixtures.UsersFixture
import com.maeharin.factlin.fixtures.insertUsersFixture
import com.maeharin.factlin.fixtures_ext.active
import com.maeharin.factlin.fixtures_ext.stopped
import com.maeharin.factlin_sample.usecase.showUsers
import com.maeharin.factlin_sample.domain.UserJobType
import com.maeharin.factlin_sample.usecase.CreateOrUpdateUserInput
import com.maeharin.factlin_sample.usecase.createUser
import com.maeharin.factlin_sample.usecase.showUserById
import com.ninja_squad.dbsetup.destination.DriverManagerDestination
import com.ninja_squad.dbsetup_kotlin.dbSetup
import org.jetbrains.exposed.sql.Database
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.LocalDate
class UserUseCaseTest {
val dbUrl = "jdbc:postgresql://${System.getenv("DB_HOST")}/dvdrental"
val dbUser = "postgres"
val dbPassword = ""
val dbDriver = "org.postgresql.Driver"
val dest = DriverManagerDestination(dbUrl, dbUser, dbPassword)
init {
Class.forName(dbDriver)
Database.connect(url = dbUrl, driver = dbDriver, user = dbUser, password = dbPassword)
}
@Test
fun `show users`() {
dbSetup(dest) {
deleteAllFrom(listOf("users"))
insertUsersFixture(UsersFixture().active().copy(id = 1, name = "テスト1"))
insertUsersFixture(UsersFixture().stopped().copy(id = 2, name = "テスト2"))
}.launch()
val users = showUsers()
users[0].also { user ->
assertEquals(1, user.id)
assertEquals("テスト1", user.name)
assertEquals(UserJobType.ENGINEER, user.job)
}
users[1].also { user ->
assertEquals(2, user.id)
assertEquals("テスト2", user.name)
assertEquals(UserJobType.ENGINEER, user.job)
}
}
@Test
fun `show user by id`() {
dbSetup(dest) {
deleteAllFrom(listOf("users"))
insertUsersFixture(UsersFixture().active().copy(id = 1, name = "テスト1"))
}.launch()
val user = showUserById(1)
assertEquals(1, user.id)
assertEquals("テスト1", user.name)
assertEquals(UserJobType.ENGINEER, user.job)
}
@Test
fun `create user` () {
dbSetup(dest) {
deleteAllFrom(listOf("users"))
}.launch()
val input = CreateOrUpdateUserInput(
name = "<NAME>",
job = UserJobType.TEACHER,
age = 0,
birthDay = LocalDate.parse("1982-10-07"),
nickName = "maeharin"
)
val id = createUser(input)
val user = showUserById(id)
assertEquals(id, user.id)
assertEquals("前原 秀徳", user.name)
assertEquals(UserJobType.TEACHER, user.job)
assertEquals( 0, user.age)
assertEquals(LocalDate.parse("1982-10-07"), user.birthDay)
assertEquals("maeharin", user.nickName)
}
}
|
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::sync::mpsc::{channel, Receiver, Sender};
const KEY_NUM_TYPES: usize = 5;
pub enum Key {
Left,
Up,
Right,
Down,
// Space,
}
fn key_to_int(key: Key) -> usize {
match key {
Key::Left => 0,
Key::Up => 1,
Key::Right => 2,
Key::Down => 3,
// Key::Space => 4,
}
}
#[derive(Clone)]
pub struct InputInfo {
pub keys: [bool; KEY_NUM_TYPES], // note: we may consider the pressure.
pub triggers: [bool; KEY_NUM_TYPES],
}
impl InputInfo {
pub fn new() -> InputInfo {
InputInfo {
keys: [false; KEY_NUM_TYPES],
triggers: [false; KEY_NUM_TYPES],
}
}
pub fn is_pressed(&self, key: Key) -> bool {
self.keys[key_to_int(key)]
}
pub fn update(&mut self, input: InputDriverInputInfo) {
for i in 0..KEY_NUM_TYPES {
self.keys[i] = input.keys[i];
self.triggers[i] |= input.keys[i];
}
}
pub fn down_trigger(&mut self) {
self.triggers.fill(false);
}
}
pub struct Input {
input_info: InputInfo,
input_driver_rx: Receiver<InputDriverInputInfo>,
}
impl Input {
pub fn create_with_driver() -> (Input, InputDriver) {
let (tx, rx) = channel::<InputDriverInputInfo>();
(
Input {
input_info: InputInfo::new(),
input_driver_rx: rx,
},
InputDriver::new(tx),
)
}
pub fn owned_input(&self) -> InputInfo {
self.input_info.clone()
}
pub fn down_trigger(&mut self) {
self.input_info.down_trigger();
}
pub fn procedure_events(&mut self) {
for info in self.input_driver_rx.try_iter() {
self.input_info.update(info);
}
}
}
#[derive(Clone)]
pub struct InputDriverInputInfo {
// pressure の実装を考慮して、毎回全てのデータを送る
pub keys: [bool; KEY_NUM_TYPES],
}
impl InputDriverInputInfo {
pub fn new() -> InputDriverInputInfo {
InputDriverInp
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::sync::mpsc::{channel, Receiver, Sender};
const KEY_NUM_TYPES: usize = 5;
pub enum Key {
Left,
Up,
Right,
Down,
// Space,
}
fn key_to_int(key: Key) -> usize {
match key {
Key::Left => 0,
Key::Up => 1,
Key::Right => 2,
Key::Down => 3,
// Key::Space => 4,
}
}
#[derive(Clone)]
pub struct InputInfo {
pub keys: [bool; KEY_NUM_TYPES], // note: we may consider the pressure.
pub triggers: [bool; KEY_NUM_TYPES],
}
impl InputInfo {
pub fn new() -> InputInfo {
InputInfo {
keys: [false; KEY_NUM_TYPES],
triggers: [false; KEY_NUM_TYPES],
}
}
pub fn is_pressed(&self, key: Key) -> bool {
self.keys[key_to_int(key)]
}
pub fn update(&mut self, input: InputDriverInputInfo) {
for i in 0..KEY_NUM_TYPES {
self.keys[i] = input.keys[i];
self.triggers[i] |= input.keys[i];
}
}
pub fn down_trigger(&mut self) {
self.triggers.fill(false);
}
}
pub struct Input {
input_info: InputInfo,
input_driver_rx: Receiver<InputDriverInputInfo>,
}
impl Input {
pub fn create_with_driver() -> (Input, InputDriver) {
let (tx, rx) = channel::<InputDriverInputInfo>();
(
Input {
input_info: InputInfo::new(),
input_driver_rx: rx,
},
InputDriver::new(tx),
)
}
pub fn owned_input(&self) -> InputInfo {
self.input_info.clone()
}
pub fn down_trigger(&mut self) {
self.input_info.down_trigger();
}
pub fn procedure_events(&mut self) {
for info in self.input_driver_rx.try_iter() {
self.input_info.update(info);
}
}
}
#[derive(Clone)]
pub struct InputDriverInputInfo {
// pressure の実装を考慮して、毎回全てのデータを送る
pub keys: [bool; KEY_NUM_TYPES],
}
impl InputDriverInputInfo {
pub fn new() -> InputDriverInputInfo {
InputDriverInputInfo {
keys: [false; KEY_NUM_TYPES],
}
}
}
pub struct InputDriver {
sender: Sender<InputDriverInputInfo>,
input_info: InputDriverInputInfo,
}
impl InputDriver {
pub fn new(sender: Sender<InputDriverInputInfo>) -> InputDriver {
InputDriver {
sender: sender,
input_info: InputDriverInputInfo::new(),
}
}
pub fn handle_key_press_event(&mut self, key: gdk::keys::Key) {
if let Some(ikey) = convert_gdk_key(key) {
self.input_info.keys[key_to_int(ikey)] = true;
// ignore failure
let _ = self.sender.send(self.input_info.clone());
}
}
pub fn handle_key_release_event(&mut self, key: gdk::keys::Key) {
if let Some(ikey) = convert_gdk_key(key) {
self.input_info.keys[key_to_int(ikey)] = false;
// ignore failure
let _ = self.sender.send(self.input_info.clone());
}
}
}
fn convert_gdk_key(key: gdk::keys::Key) -> Option<Key> {
// match key {
// gdk::keys::constants::leftarrow => self.key_left = true,
// gdk::keys::constants::uparrow => self.key_up = true,
// gdk::keys::constants::rightarrow => self.key_right = true,
// gdk::keys::constants::downarrow => self.key_down = true,
// _ => (),
// };
// TODO: 妥協策
match key.name().unwrap().as_str() {
"Left" => Some(Key::Left),
"Up" => Some(Key::Up),
"Right" => Some(Key::Right),
"Down" => Some(Key::Down),
_ => None,
}
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import java.util.List;
import java.util.ArrayList;
class Solution {
private List<List<Integer>> solutions = new ArrayList<>();
int k;
public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
dfs(new ArrayList<Integer>(), 1, n);
return this.solutions;
}
private void dfs(List<Integer> nums, int i, int target)
{
if (nums.size() == this.k) {
if (target == 0)
this.solutions.add(new ArrayList<Integer>(nums));
return;
}
if (target < 0) return;
for (; i <= 9; i++) {
nums.add(i);
dfs(nums, i + 1, target - i);
nums.remove(nums.size() - 1);
}
}
}
public class CombinationSum3a {
public static void main(String args[]) {
List<List<Integer>> solutions = new Solution().combinationSum3(3, 15);
}
}
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 |
import java.util.List;
import java.util.ArrayList;
class Solution {
private List<List<Integer>> solutions = new ArrayList<>();
int k;
public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
dfs(new ArrayList<Integer>(), 1, n);
return this.solutions;
}
private void dfs(List<Integer> nums, int i, int target)
{
if (nums.size() == this.k) {
if (target == 0)
this.solutions.add(new ArrayList<Integer>(nums));
return;
}
if (target < 0) return;
for (; i <= 9; i++) {
nums.add(i);
dfs(nums, i + 1, target - i);
nums.remove(nums.size() - 1);
}
}
}
public class CombinationSum3a {
public static void main(String args[]) {
List<List<Integer>> solutions = new Solution().combinationSum3(3, 15);
}
}
|
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<iostream>
#include"SDL2/SDL_mixer.h"
#include"SDL2/SDL.h"
int main(){
//SDL_setenv("SDL_AUDIODRIVER","alsa",0);
//putenv((char *)"SDL_AUDIODRIVER=alsa");
// start SDL with audio support
if(SDL_Init(SDL_INIT_AUDIO)==-1) {
printf("SDL_Init: %s\n", SDL_GetError());
exit(1);
}
// Get current audio driver
printf("Current audio driver: %s\n", SDL_GetCurrentAudioDriver());
std::cout<<"Number of available audio drivers:" << SDL_GetNumAudioDrivers()<<std::endl;
const char* driver_name = "pulseaudio";
SDL_AudioInit(driver_name);
printf("Current audio driver: %s\n", SDL_GetCurrentAudioDriver());
// open 44.1KHz, signed 16bit, system byte order,
// stereo audio, using 1024 byte chunks
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1) {
printf("Mix_OpenAudio: %s\n", Mix_GetError());
exit(2);
}
}
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<iostream>
#include"SDL2/SDL_mixer.h"
#include"SDL2/SDL.h"
int main(){
//SDL_setenv("SDL_AUDIODRIVER","alsa",0);
//putenv((char *)"SDL_AUDIODRIVER=alsa");
// start SDL with audio support
if(SDL_Init(SDL_INIT_AUDIO)==-1) {
printf("SDL_Init: %s\n", SDL_GetError());
exit(1);
}
// Get current audio driver
printf("Current audio driver: %s\n", SDL_GetCurrentAudioDriver());
std::cout<<"Number of available audio drivers:" << SDL_GetNumAudioDrivers()<<std::endl;
const char* driver_name = "pulseaudio";
SDL_AudioInit(driver_name);
printf("Current audio driver: %s\n", SDL_GetCurrentAudioDriver());
// open 44.1KHz, signed 16bit, system byte order,
// stereo audio, using 1024 byte chunks
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1) {
printf("Mix_OpenAudio: %s\n", Mix_GetError());
exit(2);
}
}
|
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:
// Generated with goxc v0.1.13 - rev f5cc87998c35abe9b532e49b5672e8667bcbd00c
package h005
import w3c "github.com/openyard/ebics/3.0/w3c"
// Attribute
type ReadyToBeSigned struct {
Value *w3c.Boolean `xml:"readyToBeSigned,attr"`
}
func NewReadyToBeSigned() *ReadyToBeSigned {
return new(ReadyToBeSigned)
}
func (me *ReadyToBeSigned) SetValue(value *w3c.Boolean) {
me.Value = 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>"
|
go
| 1 |
// Generated with goxc v0.1.13 - rev f5cc87998c35abe9b532e49b5672e8667bcbd00c
package h005
import w3c "github.com/openyard/ebics/3.0/w3c"
// Attribute
type ReadyToBeSigned struct {
Value *w3c.Boolean `xml:"readyToBeSigned,attr"`
}
func NewReadyToBeSigned() *ReadyToBeSigned {
return new(ReadyToBeSigned)
}
func (me *ReadyToBeSigned) SetValue(value *w3c.Boolean) {
me.Value = value
}
|
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:
/* death.c */
/**/
#include "imoria.h"
#include "master.h"
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void ud__get_username(char *name)
{
user_name(name);
};
//////////////////////////////////////////////////////////////////////
static char* ud__fill_str(char *centered_str, char *in_str)
{
/*{ Centers a string within a 31 character string -JWT- }*/
register int i, j;
i = strlen(in_str);
j = 15 - i/2;
(void) sprintf (centered_str, "%*s%s%*s", j, "", in_str, 31 - i - j, "");
return centered_str;
};
//////////////////////////////////////////////////////////////////////
void dprint(vtype str, integer row)
{
/*{ Prints a line to the screen efficiently -RAK- }*/
integer i1,i2,nblanks,xpos,slen;
vtype prt_str;
prt_str[0] = 0;
nblanks = 0;
xpos = 0;
slen = strlen(str);
for (i1 = 0; i1 < slen; i1++) {
//printf("\tdo a char: %d >%c<\n",i1,str[i1]); fflush(stdout);
if (str[i1] == ' ') {
if (xpos > 0) {
nblanks++;
if (nblanks > 5) {
nblanks = 0;
put_buffer(prt_str,row,xpos);
prt_str[0] = 0;
xpos = 0;
}
}
} else {
if (xpos == 0) {
xpos = i1;
}
if (nblanks > 0) {
for (i2 = 0; i2 < nblanks; i2++) {
strcat(prt_str, " ");
}
nblanks = 0;
}
strncat(prt_str, &(str[i1]), 1);
}
} /* end for */
if (xpos > 0) {
// printf("doing final put_buffer >%s<\n",prt_str); fflush(stdout);
put_buffer(prt_str,row,xpos);
}
}
//////////////////////////////////////////////////////////////////////
void ud__kingly()
{
/*{ Change the player into a King! -RAK- }*/
/* { Change the character attributes... }*/
dun_level = 0;
strcpy(died_from, "Ripe Old Age");
if ( characters_sex() == MALE ) {
strcpy(PM.title, "Magnificent");
strcat(PM.tclass, " King");
} else {
strcpy(PM.title, "Beautiful");
strcat(PM.tclass, " Queen");
}
PM.lev +
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 |
/* death.c */
/**/
#include "imoria.h"
#include "master.h"
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void ud__get_username(char *name)
{
user_name(name);
};
//////////////////////////////////////////////////////////////////////
static char* ud__fill_str(char *centered_str, char *in_str)
{
/*{ Centers a string within a 31 character string -JWT- }*/
register int i, j;
i = strlen(in_str);
j = 15 - i/2;
(void) sprintf (centered_str, "%*s%s%*s", j, "", in_str, 31 - i - j, "");
return centered_str;
};
//////////////////////////////////////////////////////////////////////
void dprint(vtype str, integer row)
{
/*{ Prints a line to the screen efficiently -RAK- }*/
integer i1,i2,nblanks,xpos,slen;
vtype prt_str;
prt_str[0] = 0;
nblanks = 0;
xpos = 0;
slen = strlen(str);
for (i1 = 0; i1 < slen; i1++) {
//printf("\tdo a char: %d >%c<\n",i1,str[i1]); fflush(stdout);
if (str[i1] == ' ') {
if (xpos > 0) {
nblanks++;
if (nblanks > 5) {
nblanks = 0;
put_buffer(prt_str,row,xpos);
prt_str[0] = 0;
xpos = 0;
}
}
} else {
if (xpos == 0) {
xpos = i1;
}
if (nblanks > 0) {
for (i2 = 0; i2 < nblanks; i2++) {
strcat(prt_str, " ");
}
nblanks = 0;
}
strncat(prt_str, &(str[i1]), 1);
}
} /* end for */
if (xpos > 0) {
// printf("doing final put_buffer >%s<\n",prt_str); fflush(stdout);
put_buffer(prt_str,row,xpos);
}
}
//////////////////////////////////////////////////////////////////////
void ud__kingly()
{
/*{ Change the player into a King! -RAK- }*/
/* { Change the character attributes... }*/
dun_level = 0;
strcpy(died_from, "Ripe Old Age");
if ( characters_sex() == MALE ) {
strcpy(PM.title, "Magnificent");
strcat(PM.tclass, " King");
} else {
strcpy(PM.title, "Beautiful");
strcat(PM.tclass, " Queen");
}
PM.lev += MAX_PLAYER_LEVEL;
PM.account += 250000;
PM.max_exp += 5000000;
PM.exp = PM.max_exp;
/*{ Let the player know that he did good... }*/
clear_from(1);
dprint(" #",2);
dprint(" #####",3);
dprint(" #",4);
dprint(" ,,, $$$ ,,,",5);
dprint(" ,,=$ \"$$$$$\" $=,,",6);
dprint(" ,$$ $$$ $$,",7);
dprint(" *> <*> <*",8);
dprint(" $$ $$$ $$",9);
dprint(" \"$$ $$$ $$\"",10);
dprint(" \"$$ $$$ $$\"",11);
dprint(" *#########*#########*",12);
dprint(" *#########*#########*",13);
dprint(" Veni, Vidi, Vici!",16);
dprint(" I came, I saw, I conquered!",17);
dprint(" All Hail the Mighty King!",18);
flush();
pause_game(24);
};
//////////////////////////////////////////////////////////////////////
void ud__print_tomb(vtype dstr[])
{
/*{ Prints the gravestone of the character -RAK- }*/
vtype user, temp;
FILE *f1;
if (py.misc.lev > 10) {
ud__get_username(user);
user[12] = 0;
f1 = priv_fopen(MORIA_DTH,"r+");
if (f1 != NULL) {
fseek(f1,0,SEEK_END);
if (py.misc.cheated) {
fprintf(f1, "*%-12s %1d %2d %2d %2d %4ld %4d %s\n",
user, py.misc.diffic, py.misc.prace,
py.misc.pclass, py.misc.lev, dun_level,
py.misc.max_lev, died_from);
fprintf(f1,"%50s %s\n", "",show_current_time(temp));
} else {
fprintf(f1, " %-12s %1d %2d %2d %2d %4ld %4d %s\n",
user, py.misc.diffic, py.misc.prace,
py.misc.pclass, py.misc.lev, dun_level,
py.misc.max_lev, died_from);
fprintf(f1,"%50s %s\n", "",show_current_time(temp));
//fprintf(f1," %44s %s\n", py.misc.ssn, show_current_time(temp));
}
fclose(f1);
} /* endif f1 != NULL */
} /* endif level > 10 */
make_tomb(dstr);
write_tomb(dstr);
};
//////////////////////////////////////////////////////////////////////
integer total_points()
{
/* { Calculates the total number of points earned -JWT- }*/
/* { The formula was changed to reflect the difficulty of low exp. */
/* modifier classes like warriors -Cap'n- }*/
integer return_value;
if (PM.expfact == 0) {
return_value = PM.max_exp + 100*PM.max_lev;
} else {
return_value = trunc(PM.max_exp / PM.expfact) + 100*PM.max_lev;
}
return return_value;
};
//////////////////////////////////////////////////////////////////////
void upon_death()
{
/*{ Handles the gravestone and top-twenty routines -RAK- }*/
GDBM_FILE f2;
master_key mkey;
vtype dstr[20];
/*{ What happens upon dying... -RAK- }*/
if (!master_file_open(&f2)) {
msg_print("ERROR opening file MASTER. Contact your local wizard.");
//msg_print("Status = "+itos(status(f1)));
msg_print(" ");
} else {
mkey.creation_time = PM.creation_time;
master_file_delete(f2, &mkey);
master_file_close(&f2);
}
/* I think this says "delete the file"...
open(f1,file_name:=finam,record_length:=1024,history:=old,
disposition:=delete,error:=continue);
*/
unlink(finam);
if (total_winner) {
ud__kingly();
}
ud__print_tomb(dstr);
print_dead_character();
top_twenty(max_score);
exit_game();
};
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void print_dead_character()
{
/*{ Allow the bozo to print out his dead character... -KRC- }*/
char command;
if (get_com("Print character sheet to file? (Y/N)",&command)) {
if (command == 'y' || command == 'Y') {
file_character();
}
}
};
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void top_twenty(integer this_many)
{
/*{ Enters a players name on the top twenty list -JWT- }*/
string list[MAX_HIGH_SCORES+2];
integer players_line = 0;
integer i1,i2,i3,i4;
int n1;
vtype o1,s1;
FILE *f1;
boolean flag;
char ch;
if (py.misc.cheated) {
exit_game();
}
clear_screen();
if (!read_top_scores(&f1, MORIA_TOP, list, MAX_HIGH_SCORES, &n1, s1)) {
prt(s1,2,1);
prt("",3,1);
} else {
i3 = total_points();
flag = false;
if (i3 == 0) {
i1 = n1;
} else {
for (i1=1; (i1 <= n1) && !flag ; ) { /* XXXX check for corruption */
sscanf(&(list[i1][13]),"%ld",&i4);
if (i4 < i3) {
flag = true;
} else {
i1++;
}
}
}
if ((i3 > 0) && ((flag) || (n1 == 0) || (n1 < MAX_HIGH_SCORES))) {
for (i2 = MAX_HIGH_SCORES-1; i2 >= i1 ; i2--) {
strcpy(list[i2+1], list[i2]);
}
user_name(o1);
format_top_score(list[i1], o1, i3, PM.diffic, PM.name,
PM.lev, PM.race, PM.tclass);
if (n1 < MAX_HIGH_SCORES) {
n1++;
}
max_score = n1;
players_line = i1;
flag = false;
write_top_scores(&f1, list, n1);
} else {
/* did not get a high score */
max_score = 20;
}
if (!close_top_scores(&f1)) {
prt("Error unlocking score file.",2,1);
prt("",3,1);
}
put_buffer("Username Points Diff Character name Level Race Class",1,1);
put_buffer("____________ ________ _ ________________________ __ __________ ________________",2,1);
i2 = 3;
if (max_score > n1) {
max_score = n1;
}
if (this_many > 0) {
if (this_many > MAX_HIGH_SCORES) {
max_score = MAX_HIGH_SCORES;
} else {
max_score = this_many;
}
}
for (i1 = 1; i1 <= max_score; i1++) {
/*insert_str(list[i1],chr(7),''); XXXX why? */
if (i1 == players_line) {
put_buffer_attr(list[i1],i2,1, A_REVERSE);
} else {
put_buffer(list[i1],i2,1);
}
if ((i1 != 1) && ((i1 % 20) == 0) && (i1 != max_score)) {
prt("[Press any key to continue, or <Control>-Z to exit]",
24,1);
ch = inkey();
switch (ch) {
case 3: case 25: case 26:
erase_line(24,1);
put_buffer(" ",23,13);
exit_game();
break;
}
clear_rc(3,1);
i2 = 2;
}
i2++;
} /* end for */
erase_line(23,1);
put_qio();
} /* end if read_top_scores */
};
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void sc(char *out_str, char *in_str)
{
strcpy(out_str, in_str);
}
//////////////////////////////////////////////////////////////////////
void si(char *out_str, char *part1, char *part2, char *part3)
{
sprintf(out_str, "%s%s%s", part1, part2, part3);
}
//////////////////////////////////////////////////////////////////////
static void date(day)
char *day;
{
register char *tmp;
long clockvar;
clockvar = time((long *) 0);
tmp = (char *)ctime(&clockvar);
tmp[10] = '\0';
(void) strcpy(day, tmp);
}
//////////////////////////////////////////////////////////////////////
void make_tomb(vtype dd[])
{
vtype str1,str2,str3,str4,str5,str6,str7,str8;
vtype temp;
integer i1;
char day[11];
date(day);
ud__fill_str(str1, py.misc.name);
ud__fill_str(str2, py.misc.title);
ud__fill_str(str3, py.misc.tclass);
sprintf(temp,"Level : %d",py.misc.lev);
ud__fill_str(str4, temp);
sprintf(temp,"%ld Exp",py.misc.exp);
ud__fill_str(str5, temp);
sprintf(temp,"%ld Au",(py.misc.account+py.misc.money[TOTAL_]));
ud__fill_str(str6, temp);
sprintf(temp,"Died on Level : %ld",dun_level);
ud__fill_str(str7, temp);
sprintf(temp,"%s.",died_from);
ud__fill_str(str8, temp);
sc(dd[ 0]," ");
sc(dd[ 1]," _______________________");
sc(dd[ 2]," / \\ ___");
sc(dd[ 3]," / \\ ___ / \\ ___");
sc(dd[ 4]," / RIP \\ \\ : : / \\");
sc(dd[ 5]," / \\ : _;,,,;_ : :");
si(dd[ 6]," /",str1, "\\,;_ _;,,,;_");
sc(dd[ 7]," | the | ___");
si(dd[ 8]," | ",str2, " | / \\");
sc(dd[ 9]," | | : :");
si(dd[10]," | ",str3, " | _;,,,;_ ____");
si(dd[11]," | ",str4, " | / \\");
si(dd[12]," | ",str5, " | : :");
si(dd[13]," | ",str6, " | : :");
si(dd[14]," | ",str7, " | _;,,,,;_");
sc(dd[15]," | killed by |");
si(dd[16]," | ",str8, " |");
si(dd[17]," | ",day, " |");
sc(dd[18]," *| * * * * * * | *");
sc(dd[19]," _______)/\\\\_)_/___(\\/___(//_\\)/_\\//__\\\\(/_|_)_______");
clear_from(1);
for (i1 = 0; i1 < 20; i1++) {
//printf(">%s<\n",dd[i1]);
dprint(dd[i1],i1+1);
}
flush();
};
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void write_tomb(vtype dstr[])
{
vtype out_str;
vtype fnam;
char command;
FILE *f1;
integer i1;
boolean flag;
if (get_com("Print to file? (Y/N)",&command)) {
if (command == 'y' || command == 'Y') {
prt("Enter Filename:",1,1);
flag = false;
do {
if (get_string(fnam,1,17,60)) {
if (strlen(fnam) == 0) {
strcpy(fnam, "MORIACHR.DIE");
}
f1 = (FILE *)fopen(fnam, "w");
if (f1 == NULL) {
sprintf(out_str, "Error creating> %s",fnam);
prt(out_str,2,1);
} else {
flag = true;
for (i1 = 0; i1 < 20; i1++) {
fprintf(f1,"%s\n",dstr[i1]);
}
}
fclose(f1);
} else {
flag = true;
}
} while (!flag);
} /* end if command == Y */
} /* end if get command */
};
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/* END FILE death.c */
|
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:
/**************************************************************************
* Copyright (c) 2008 by Ronin Capital, LLC
*
* All Rights Reserved
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include "config_loader.h"
#include "parser_func.h"
#include "hashmap.h"
struct config_loader {
pthread_mutex_t config_init_mutex;
hashmap_t header_map;
char *filename;
};
static char *get_file_contents(const char *filename, long *size)
{
FILE *map_file;
long result;
char *buff;
buff = NULL;
*size = -1;
map_file = NULL;
map_file = fopen(filename, "r+b");
if (map_file != NULL) {
fseek(map_file, 0, SEEK_END);
*size = ftell(map_file);
rewind(map_file);
buff = calloc(*size + 1, 1);
if (buff != NULL) {
result = fread(buff, 1, *size, map_file);
if (result == *size) {
//do nothing
} else {
printf("File read error on this file: %s \n", filename);
*size = -1;
free(buff);
buff = NULL;
}
}
fclose(map_file);
}
return buff;
}
static void add_to_map(hashmap_t map, char *buffer, long len)
{
char comma[2] = { '=', '\0' };
long c_offset = 0;
c_offset = find_offset(buffer, len, comma, 1);
if (c_offset > 0) {
char *tag;
char *val;
char *val_off;
long val_len;
tag = calloc(c_offset + 1, 1);
if (tag != NULL) {
memcpy(tag, buffer, c_offset);
val_off = buffer;
val_off += c_offset + 1;
val_len = len - (c_offset + 1);
val = calloc(val_len, 1);
if (val != NULL) {
memcpy(val, val_off, val_len);
insert_map(map, tag, c_offset, val, val_len);
//printf("Inserted this tag: %s and 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>"
|
c
| 3 |
/**************************************************************************
* Copyright (c) 2008 by Ronin Capital, LLC
*
* All Rights Reserved
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include "config_loader.h"
#include "parser_func.h"
#include "hashmap.h"
struct config_loader {
pthread_mutex_t config_init_mutex;
hashmap_t header_map;
char *filename;
};
static char *get_file_contents(const char *filename, long *size)
{
FILE *map_file;
long result;
char *buff;
buff = NULL;
*size = -1;
map_file = NULL;
map_file = fopen(filename, "r+b");
if (map_file != NULL) {
fseek(map_file, 0, SEEK_END);
*size = ftell(map_file);
rewind(map_file);
buff = calloc(*size + 1, 1);
if (buff != NULL) {
result = fread(buff, 1, *size, map_file);
if (result == *size) {
//do nothing
} else {
printf("File read error on this file: %s \n", filename);
*size = -1;
free(buff);
buff = NULL;
}
}
fclose(map_file);
}
return buff;
}
static void add_to_map(hashmap_t map, char *buffer, long len)
{
char comma[2] = { '=', '\0' };
long c_offset = 0;
c_offset = find_offset(buffer, len, comma, 1);
if (c_offset > 0) {
char *tag;
char *val;
char *val_off;
long val_len;
tag = calloc(c_offset + 1, 1);
if (tag != NULL) {
memcpy(tag, buffer, c_offset);
val_off = buffer;
val_off += c_offset + 1;
val_len = len - (c_offset + 1);
val = calloc(val_len, 1);
if (val != NULL) {
memcpy(val, val_off, val_len);
insert_map(map, tag, c_offset, val, val_len);
//printf("Inserted this tag: %s and this val: %d\n", tag, *val);
free(val);
}
free(tag);
}
}
}
static hashmap_t create_map_for_header(hashmap_t mmap, char *d_off,
long end_pos)
{
char e_bracket[2] = { ']', '\0' };
char *name = NULL;
long end;
char *l_off = d_off;
hashmap_t l_map = create_map(10);
l_off += 1;
end = find_offset(l_off, (end_pos - 1), e_bracket, 1);
if (end < 0) {
end = end_pos - 1;
}
name = calloc(end + 1, 1);
if (name != NULL) {
memcpy(name, l_off, end);
no_copy_insert(mmap, name, end, l_map);
free(name);
}
return l_map;
}
static int build_map_from_file(const char *filename, hashmap_t map)
{
int result = -1;
long size = 0;
char *buffer = get_file_contents(filename, &size);
if (size > 0) {
long cur_pos = 0;
long eol_len;
long end_pos = 0;
int should_parse = 1;
char *d_off = buffer;
hashmap_t l_map = NULL;
char eol[2] = { '\n', '\0' };
eol_len = 1;
result = 0;
while (cur_pos < size && should_parse) {
end_pos = find_offset(d_off, (size - cur_pos), eol, eol_len);
if (end_pos > 0) {
long bracket_off = 0;
bracket_off = find_offset(d_off, (end_pos - 1), "[", 1);
if (bracket_off >= 0) {
char *h_off = d_off;
h_off += bracket_off;
l_map = create_map_for_header(map, h_off, end_pos);
} else if (l_map) {
add_to_map(l_map, d_off, end_pos);
}
d_off += end_pos + eol_len;
cur_pos += end_pos + eol_len;
} else if (end_pos == 0 && (cur_pos + 1) < size) {
d_off += 1;
cur_pos += 1;
} else {
should_parse = 0;
}
}
free(buffer);
}
return result;
}
void dart_reset_maps(dart_config * df)
{
pthread_mutex_lock(&df->config_init_mutex);
delete_map(df->header_map);
df->header_map = create_map(50);
build_map_from_file(df->filename, df->header_map);
pthread_mutex_unlock(&df->config_init_mutex);
}
void dart_load_map(dart_config * df)
{
pthread_mutex_lock(&df->config_init_mutex);
delete_map(df->header_map);
df->header_map = create_map(50);
build_map_from_file(df->filename, df->header_map);
pthread_mutex_unlock(&df->config_init_mutex);
}
dart_config *initialize_config(const char *filename, int len)
{
dart_config *df = malloc(sizeof(struct config_loader));
df->filename = calloc(len + 1, 1);
memcpy(df->filename, filename, len);
df->header_map = create_map(50);
if (pthread_mutex_init(&df->config_init_mutex, NULL) != 0) {
printf("Failed to init obj manager mutex.\n");
}
if (build_map_from_file(df->filename, df->header_map) == -1) {
free(df->filename);
delete_map(df->header_map);
free(df);
df = 0;
}
return df;
}
char *get_val_for_tag(dart_config * df, const char *section, int sec_len,
const char *tag, int tag_len, int *val_len)
{
char *temp;
int ret_val;
char *data;
hashmap_t l_map;
pthread_mutex_lock(&df->config_init_mutex);
temp = NULL;
ret_val =
get_map_entry(df->header_map, section, sec_len, (void *) &l_map);
if (ret_val <= 0) {
pthread_mutex_unlock(&df->config_init_mutex);
*val_len = 0;
return NULL;
}
ret_val = get_map_entry(l_map, tag, tag_len, (void *) &temp);
if (ret_val <= 0) {
pthread_mutex_unlock(&df->config_init_mutex);
*val_len = 0;
return NULL;
}
data = calloc(ret_val + 1, 1);
if (data != NULL) {
memcpy(data, temp, ret_val);
*val_len = ret_val;
} else {
*val_len = 0;
}
pthread_mutex_unlock(&df->config_init_mutex);
return data;
}
static void write_val_to_file(FILE * map_file, long bytes_to_write,
char *val)
{
int written = 0;
char *val_to_write = val;
long b_to_w = bytes_to_write;
while (written < b_to_w) {
written += fwrite(val_to_write, 1, bytes_to_write, map_file);
bytes_to_write -= written;
val_to_write += written;
}
}
void set_val_for_tag(dart_config * df, const char *section,
int sec_len, const char *tag, int tag_len, char *val,
int val_len)
{
char e_bracket = '[';
FILE *map_file;
long result;
char *buff;
char *tag_off;
char *sec_off;
char *next_sec;
long eol_len;
long size = 0;
char eol[2] = { '\n', '\0' };
eol_len = 1;
pthread_mutex_lock(&df->config_init_mutex);
buff = NULL;
map_file = NULL;
map_file = fopen(df->filename, "r+b");
if (map_file != NULL) {
fseek(map_file, 0, SEEK_END);
size = ftell(map_file);
rewind(map_file);
buff = calloc(size + 1, 1);
if (buff != NULL) {
result = fread(buff, 1, size, map_file);
if (result == size) {
int keep_looking = 1;
sec_off = strstr(buff, section);
while (sec_off != NULL && keep_looking) {
if ((sec_off - 1) != NULL && *(sec_off - 1) != '[') {
sec_off = strstr((sec_off + sec_len), section);
} else {
keep_looking = 0;
}
}
if (sec_off != NULL) {
tag_off = strstr(sec_off, tag);
while(tag_off) {
if((tag_off - 1)[0] == '\n') {
char* next_eq = strchr(tag_off, '=');
if(next_eq && next_eq - tag_off == tag_len) {
break;
} else if(next_eq) {
tag_off = strstr(tag_off + (next_eq - tag_off), tag);
}
} else {
tag_off = strstr(tag_off +1, tag);
}
}
next_sec = strchr(sec_off, e_bracket);
if ((tag_off != NULL && next_sec == NULL) ||
(next_sec != NULL && tag_off != NULL &&
((next_sec - sec_off) > (tag_off - sec_off)))) {
int offset;
int written;
char *val_to_write = val;
int bytes_to_write = val_len;
char *old_eol = 0;
tag_off += tag_len + 1;
offset = tag_off - buff;
fseek(map_file, offset, SEEK_SET);
written = 0;
while (written < val_len) {
written +=
fwrite(val_to_write, 1, bytes_to_write,
map_file);
bytes_to_write -= written;
val_to_write += written;
}
old_eol = strstr(tag_off, eol);
if (old_eol != NULL) {
long b_to_w = size - ((old_eol) - buff);
fseek(map_file, (offset + val_len), SEEK_SET);
write_val_to_file(map_file, b_to_w, old_eol);
}
} else {
int offset = 0;
if (next_sec != NULL) {
offset = ((next_sec - 1) - buff);
} else {
offset = size - 1;
}
fseek(map_file, offset, SEEK_SET);
if (next_sec == NULL) {
write_val_to_file(map_file, 1, "\n");
}
write_val_to_file(map_file, tag_len, (char *) tag);
write_val_to_file(map_file, 1, "=");
write_val_to_file(map_file, val_len, val);
write_val_to_file(map_file, 1, "\n");
if (next_sec != NULL) {
long b_to_w = size - ((next_sec - 1) - buff);
fseek(map_file,
(offset + (2 + tag_len + val_len)),
SEEK_SET);
write_val_to_file(map_file, b_to_w,
(next_sec - 1));
}
}
}
free(buff);
} else {
printf("File read error on this file: %s \n",
df->filename);
free(buff);
buff = NULL;
}
fclose(map_file);
}
}
pthread_mutex_unlock(&df->config_init_mutex);
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
namespace AdventOfCode2019.Tests.Day07
{
using NUnit.Framework;
using System.Numerics;
using System.Threading.Tasks;
public partial class PuzzleTests
{
[Test]
public async Task Puzzle07_Impl1_Part1()
{
var p = new Puzzles.Day07.Impl();
await p.ResetInputsAsync();
var a = await p.RunPart1Async();
Assert.AreEqual(new BigInteger(22012), a);
}
[Test]
public async Task Puzzle07_Impl1_Part2()
{
var p = new Puzzles.Day07.Impl();
await p.ResetInputsAsync();
var a = await p.RunPart2Async();
Assert.AreEqual(new BigInteger(4039164), a);
}
}
}
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
| 1 |
namespace AdventOfCode2019.Tests.Day07
{
using NUnit.Framework;
using System.Numerics;
using System.Threading.Tasks;
public partial class PuzzleTests
{
[Test]
public async Task Puzzle07_Impl1_Part1()
{
var p = new Puzzles.Day07.Impl();
await p.ResetInputsAsync();
var a = await p.RunPart1Async();
Assert.AreEqual(new BigInteger(22012), a);
}
[Test]
public async Task Puzzle07_Impl1_Part2()
{
var p = new Puzzles.Day07.Impl();
await p.ResetInputsAsync();
var a = await p.RunPart2Async();
Assert.AreEqual(new BigInteger(4039164), a);
}
}
}
|
Below is an extract of SQL code. Evaluate whether it has a high educational value and could help teach SQL and database concepts. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the code contains valid SQL syntax, even if it's just basic queries or simple table operations.
- Add another point if the code addresses practical SQL concepts (e.g., JOINs, subqueries), even if it lacks comments.
- Award a third point if the code is suitable for educational use and introduces key concepts in SQL and database management, even if the topic is somewhat advanced (e.g., indexes, transactions). The code should be well-structured and contain some comments.
- Give a fourth point if the code is self-contained and highly relevant to teaching SQL. It should be similar to a database course exercise, demonstrating good practices in query writing and database design.
- Grant a fifth point if the code is outstanding in its educational value and is perfectly suited for teaching SQL and database concepts. It should be well-written, easy to understand, and contain explanatory comments that clarify the purpose and impact of each part of the code.
The extract:
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 17, 2020 at 06:42 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `login`
--
-- --------------------------------------------------------
--
-- Table structure for table `contact`
--
CREATE TABLE `contact` (
`sno` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`concern` varchar(200) NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `contact`
--
INSERT INTO `contact` (`sno`, `name`, `email`, `concern`, `date`) VALUES
(1, 'admin', '<EMAIL>', 'sdfghjkl;', '2020-05-13 14:27:18'),
(2, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:27:25'),
(3, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:29:45'),
(4, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:30:55');
-- --------------------------------------------------------
--
-- Table structure for table `dbmedi`
--
CREATE TABLE `dbmedi` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` varchar(20) NOT NULL,
`department` varchar(50) NOT NULL,
`time` datetime NOT NULL DEFAULT current_timestamp(),
`age` int(11) NOT NULL,
`description` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `hospitalq`
--
CREATE TABLE `hospitalq` (
`sno` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`gender` varchar(10) NOT NULL,
`department` varchar(20) NOT NULL,
`age` int(11) NOT N
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
sql
| 3 |
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 17, 2020 at 06:42 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `login`
--
-- --------------------------------------------------------
--
-- Table structure for table `contact`
--
CREATE TABLE `contact` (
`sno` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`concern` varchar(200) NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `contact`
--
INSERT INTO `contact` (`sno`, `name`, `email`, `concern`, `date`) VALUES
(1, 'admin', '<EMAIL>', 'sdfghjkl;', '2020-05-13 14:27:18'),
(2, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:27:25'),
(3, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:29:45'),
(4, 'admin', '<EMAIL>', 'aqswdfgbnhm,', '2020-05-13 14:30:55');
-- --------------------------------------------------------
--
-- Table structure for table `dbmedi`
--
CREATE TABLE `dbmedi` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` varchar(20) NOT NULL,
`department` varchar(50) NOT NULL,
`time` datetime NOT NULL DEFAULT current_timestamp(),
`age` int(11) NOT NULL,
`description` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `hospitalq`
--
CREATE TABLE `hospitalq` (
`sno` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`gender` varchar(10) NOT NULL,
`department` varchar(20) NOT NULL,
`age` int(11) NOT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
`descr` varchar(200) NOT NULL,
`user_id` int(11) NOT NULL,
`appointment` date NOT NULL,
`uniqueid` varchar(30) NOT NULL,
`statusapp` varchar(30) NOT NULL,
`time_slot` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `hospitalq`
--
INSERT INTO `hospitalq` (`sno`, `name`, `email`, `gender`, `department`, `age`, `date`, `descr`, `user_id`, `appointment`, `uniqueid`, `statusapp`, `time_slot`) VALUES
(68, 'zaptainblade', '<EMAIL>', 'female', 'Physician', 10, '2020-05-16 11:59:25', 'wertyui', 9, '2020-05-26', '9', 'OK fixed', '10:54'),
(69, 'nasdfg', '<EMAIL>', 'male', 'Physician', 26, '2020-05-16 11:59:50', 'swdefghjk,.', 9, '2020-05-20', '9', 'sorry no appointment', ''),
(73, 'zaptainblade', '<EMAIL>', 'male', 'Neuro', 100, '2020-05-16 15:12:11', 'asdftyuio', 9, '2020-05-26', '9', 'OK ', '18:30'),
(74, 'apples', '<EMAIL>', 'male', 'Digestive', 89, '2020-05-16 23:09:57', 'asdfghjkl;zxcvbnm,./', 13, '2020-05-30', '13', 'OK fixed', ''),
(75, 'trapped in the web', '<EMAIL>', 'male', 'Digestive', 100, '2020-05-17 00:21:14', 'asdfghzxcvbnmdfgh', 14, '2020-05-31', '14', 'sorry no appointment', ''),
(76, 'xeaea-12', '<EMAIL>', 'male', 'Cardio', 45, '2020-05-17 00:22:11', 'asdfghjkxcvbnm', 14, '2020-05-26', '14', 'OK fixed', '13:45');
-- --------------------------------------------------------
--
-- Table structure for table `medhist`
--
CREATE TABLE `medhist` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` char(20) NOT NULL,
`department` varchar(50) NOT NULL,
`time` datetime NOT NULL,
`age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `post`
--
CREATE TABLE `post` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` char(20) NOT NULL,
`department` varchar(50) NOT NULL,
`time` datetime NOT NULL,
`age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `post2`
--
CREATE TABLE `post2` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` char(20) NOT NULL,
`department` varchar(50) NOT NULL,
`time` datetime NOT NULL,
`age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `created_at`) VALUES
(8, 'asdf', <PASSWORD>', '2020-05-14 23:26:15'),
(9, 'zaptianblade', '$2y$10$OzmTx96cDncHw2dFgblFdu35.VmkLIySUnCkmEN0jFln/M5VyWtpS', '2020-05-14 23:29:51'),
(10, 'watsup', '$2y$10$MFolt0ccC9cotzzGW2BEU.hqyUCUPwihuXLgid/u46LQnoNhe7Oby', '2020-05-15 10:02:21'),
(12, 'alphaadmin', '$2y$10$bR5ce6fzRfanxmNHp8ur..2yLoOoMhnnw9A6Esrenk2qOZjOqyb3C', '2020-05-15 10:14:57'),
(13, 'apples', '$2y$10$.0cLYgPse1/p1iGRFTmrHOZQiwqj6sv6/WicD7t5ibSdG.8ybbxJ6', '2020-05-16 23:09:09'),
(14, 'trapped in the web', '$2y$10$dAoXYZt/269IwzzsxUTv/OprthrkC.3NYX5oaW4QYSyNkSd1L4bU.', '2020-05-17 00:19:55');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `contact`
--
ALTER TABLE `contact`
ADD PRIMARY KEY (`sno`);
--
-- Indexes for table `dbmedi`
--
ALTER TABLE `dbmedi`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `hospitalq`
--
ALTER TABLE `hospitalq`
ADD PRIMARY KEY (`sno`);
--
-- Indexes for table `medhist`
--
ALTER TABLE `medhist`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `post`
--
ALTER TABLE `post`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `post2`
--
ALTER TABLE `post2`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `contact`
--
ALTER TABLE `contact`
MODIFY `sno` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `dbmedi`
--
ALTER TABLE `dbmedi`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `hospitalq`
--
ALTER TABLE `hospitalq`
MODIFY `sno` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=77;
--
-- AUTO_INCREMENT for table `medhist`
--
ALTER TABLE `medhist`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `post`
--
ALTER TABLE `post`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `post2`
--
ALTER TABLE `post2`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Below is an extract from a 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:
<div itemscope itemtype="http://developers.google.com/ReferenceObject">
<meta itemprop="name" content="ranking.model.make_groupwise_ranking_fn" />
<meta itemprop="path" content="Stable" />
</div>
# ranking.model.make_groupwise_ranking_fn
``` python
ranking.model.make_groupwise_ranking_fn(
group_score_fn,
group_size,
ranking_head,
transform_fn=None
)
```
Defined in [`python/model.py`](https://github.com/tensorflow/ranking/tree/master/tensorflow_ranking/python/model.py).
<!-- Placeholder for "Used in" -->
Builds an `Estimator` model_fn for groupwise comparison ranking models.
#### Args:
* <b>`group_score_fn`</b>: Scoring function for a group of examples with `group_size`
that returns a score per example. It has to follow signature:
* Args:
`context_features`: A dict of `Tensor`s with shape [batch_size, ...].
`per_example_features`: A dict of `Tensor`s with shape [batch_size,
group_size, ...]
`mode`: Optional. Specifies if this is training, evaluation or
inference. See `ModeKeys`.
`params`: Optional dict of hyperparameters, same value passed in the
`Estimator` constructor.
`config`: Optional configuration object, same value passed in the
`Estimator` constructor.
* Returns: Tensor of shape [batch_size, group_size] containing per-example
scores.
* <b>`group_size`</b>: An integer denoting the number of examples in `group_score_fn`.
* <b>`ranking_head`</b>: A `head._RankingHead` object.
* <b>`transform_fn`</b>: Function transforming the raw features into dense tensors. It
has the following signature:
* Args:
`features`: A dict of `Tensor`s contains the raw input.
`mode`: Optional. See estimator `ModeKeys`.
* Returns:
`context_features`: A dict of `Tensor`s with shape [batch_size, ...]
`per_example_features`: A dict of `Tensor`s with shape [batch_size,
list_size, ...]
#### Returns:
An `Estimator` `model_fn` (see estimator.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>"
|
markdown
| 3 |
<div itemscope itemtype="http://developers.google.com/ReferenceObject">
<meta itemprop="name" content="ranking.model.make_groupwise_ranking_fn" />
<meta itemprop="path" content="Stable" />
</div>
# ranking.model.make_groupwise_ranking_fn
``` python
ranking.model.make_groupwise_ranking_fn(
group_score_fn,
group_size,
ranking_head,
transform_fn=None
)
```
Defined in [`python/model.py`](https://github.com/tensorflow/ranking/tree/master/tensorflow_ranking/python/model.py).
<!-- Placeholder for "Used in" -->
Builds an `Estimator` model_fn for groupwise comparison ranking models.
#### Args:
* <b>`group_score_fn`</b>: Scoring function for a group of examples with `group_size`
that returns a score per example. It has to follow signature:
* Args:
`context_features`: A dict of `Tensor`s with shape [batch_size, ...].
`per_example_features`: A dict of `Tensor`s with shape [batch_size,
group_size, ...]
`mode`: Optional. Specifies if this is training, evaluation or
inference. See `ModeKeys`.
`params`: Optional dict of hyperparameters, same value passed in the
`Estimator` constructor.
`config`: Optional configuration object, same value passed in the
`Estimator` constructor.
* Returns: Tensor of shape [batch_size, group_size] containing per-example
scores.
* <b>`group_size`</b>: An integer denoting the number of examples in `group_score_fn`.
* <b>`ranking_head`</b>: A `head._RankingHead` object.
* <b>`transform_fn`</b>: Function transforming the raw features into dense tensors. It
has the following signature:
* Args:
`features`: A dict of `Tensor`s contains the raw input.
`mode`: Optional. See estimator `ModeKeys`.
* Returns:
`context_features`: A dict of `Tensor`s with shape [batch_size, ...]
`per_example_features`: A dict of `Tensor`s with shape [batch_size,
list_size, ...]
#### Returns:
An `Estimator` `model_fn` (see estimator.py) with the following signature:
* Args:
* `features`: dict of Tensors of shape [batch_size, list_size, ...] for
per-example features and shape [batch_size, ...] for non-example context
features.
* `labels`: Tensor with shape [batch_size, list_size] denoting relevance.
* `mode`: No difference.
* `params`: No difference.
* `config`: No difference..
* Returns:
`EstimatorSpec`
#### Raises:
* <b>`ValueError`</b>: when group_size is invalid.
|
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
#
# SCRIPT: spreport
# AUTHOR: duckie68 - <NAME>
# https://github.com/duckie68
# DATE: 02-February-2019
# REV: 1.1.A
#
# PLATFORM: Linux
#
# PURPOSE: Provide reports and other actions for fountain screenplay
# files.
#
# USAGE: spreport
IFS=$'\n'
characters=($(grep -oP '^[A-Z\s]+\(?[OV]?\.?[SO]?\.?\)?$' $1 | sort | uniq))
unset IFS
n=""
for i in "${characters[@]}"
do
echo -e "$i\t$(grep -c "^$i$" $1)"
# echo "$n"
done
echo -e "\n"
read -p "Do you wish to save this as a report? (y/n) " yn
case $yn in
[Yy]* ) if [ -f "report.txt" ]
then
rm report.txt
fi
for i in "${characters[@]}"
do
echo -e "$i\t$(grep -c "^$i$" $1)" >> report.txt
done;;
* ) echo "Skipping report generation.";;
esac
echo -e "\n"
read -p "Would you like to generate individual character scripts? (y/n) " yn
case $yn in
[Yy]* ) for i in "${characters[@]}"
do
f=`echo $i | tr ' ' '_' `
awk /^$i$/,/^$/ $1 > ${f}.fountain
done;;
* ) echo "Skipping individual script file generation.";;
esac
echo -e "\nHave a nice day!"
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
| 3 |
#!/bin/bash
#
# SCRIPT: spreport
# AUTHOR: duckie68 - <NAME>
# https://github.com/duckie68
# DATE: 02-February-2019
# REV: 1.1.A
#
# PLATFORM: Linux
#
# PURPOSE: Provide reports and other actions for fountain screenplay
# files.
#
# USAGE: spreport
IFS=$'\n'
characters=($(grep -oP '^[A-Z\s]+\(?[OV]?\.?[SO]?\.?\)?$' $1 | sort | uniq))
unset IFS
n=""
for i in "${characters[@]}"
do
echo -e "$i\t$(grep -c "^$i$" $1)"
# echo "$n"
done
echo -e "\n"
read -p "Do you wish to save this as a report? (y/n) " yn
case $yn in
[Yy]* ) if [ -f "report.txt" ]
then
rm report.txt
fi
for i in "${characters[@]}"
do
echo -e "$i\t$(grep -c "^$i$" $1)" >> report.txt
done;;
* ) echo "Skipping report generation.";;
esac
echo -e "\n"
read -p "Would you like to generate individual character scripts? (y/n) " yn
case $yn in
[Yy]* ) for i in "${characters[@]}"
do
f=`echo $i | tr ' ' '_' `
awk /^$i$/,/^$/ $1 > ${f}.fountain
done;;
* ) echo "Skipping individual script file generation.";;
esac
echo -e "\nHave a nice day!"
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.pl.mapper.xbms;
import com.pl.model.xbms.Suggestion;
public interface SuggestionMapper {
int insertSuggestion(Suggestion suggestion);
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package com.pl.mapper.xbms;
import com.pl.model.xbms.Suggestion;
public interface SuggestionMapper {
int insertSuggestion(Suggestion suggestion);
}
|
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 <stdlib.h>
int main(int argc, char* argv[])
{
int after = 765071;
int after_len = 6;
int after_digits[6] = {7, 6, 5, 0, 7, 1};
int players = 2;
int current_player = 0;
int* recipes = malloc(100 * after * sizeof(int));
recipes[0] = 3;
recipes[1] = 7;
int recipes_count = 2;
int* current_recipes = malloc(players * sizeof(int));
current_recipes[0] = 0;
current_recipes[1] = 1;
int i;
int steps;
int sum;
int start_index = -1;
int after_index = -1;
do {
sum = 0;
for (current_player = 0; current_player < players; current_player++) {
steps = recipes[current_recipes[current_player]] + 1;
current_recipes[current_player] = (current_recipes[current_player] + steps) % recipes_count;
sum += recipes[current_recipes[current_player]];
}
if (sum > 9) {
recipes[recipes_count++] = 1;
}
recipes[recipes_count++] = sum % 10;
if (start_index != -1 && after_index == -1) {
for (i = start_index; i < recipes_count; i++) {
if (i - start_index < after_len && recipes[i] != after_digits[i - start_index]) {
start_index = -1;
break;
}
}
if (after_index == -1 && start_index != -1 && recipes_count - start_index >= after_len) {
after_index = start_index;
}
}
if (start_index == -1 ) {
if (recipes[recipes_count - 2] == after_digits[0] && recipes[recipes_count - 1] == after_digits[1]) {
start_index = recipes_count - 2;
} else if (recipes[recipes_count - 1] == after_digits[0]) {
start_index = recipes_count - 1;
}
}
} while (after_index == -1);
printf("score 10 recipes after recipe %d: ", after);
for (i = after; i < after + 10; i++) {+
printf("%d", rec
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 <stdlib.h>
int main(int argc, char* argv[])
{
int after = 765071;
int after_len = 6;
int after_digits[6] = {7, 6, 5, 0, 7, 1};
int players = 2;
int current_player = 0;
int* recipes = malloc(100 * after * sizeof(int));
recipes[0] = 3;
recipes[1] = 7;
int recipes_count = 2;
int* current_recipes = malloc(players * sizeof(int));
current_recipes[0] = 0;
current_recipes[1] = 1;
int i;
int steps;
int sum;
int start_index = -1;
int after_index = -1;
do {
sum = 0;
for (current_player = 0; current_player < players; current_player++) {
steps = recipes[current_recipes[current_player]] + 1;
current_recipes[current_player] = (current_recipes[current_player] + steps) % recipes_count;
sum += recipes[current_recipes[current_player]];
}
if (sum > 9) {
recipes[recipes_count++] = 1;
}
recipes[recipes_count++] = sum % 10;
if (start_index != -1 && after_index == -1) {
for (i = start_index; i < recipes_count; i++) {
if (i - start_index < after_len && recipes[i] != after_digits[i - start_index]) {
start_index = -1;
break;
}
}
if (after_index == -1 && start_index != -1 && recipes_count - start_index >= after_len) {
after_index = start_index;
}
}
if (start_index == -1 ) {
if (recipes[recipes_count - 2] == after_digits[0] && recipes[recipes_count - 1] == after_digits[1]) {
start_index = recipes_count - 2;
} else if (recipes[recipes_count - 1] == after_digits[0]) {
start_index = recipes_count - 1;
}
}
} while (after_index == -1);
printf("score 10 recipes after recipe %d: ", after);
for (i = after; i < after + 10; i++) {+
printf("%d", recipes[i]);
}
printf("\n");
printf("%d appears after %d recipes\n", after, after_index);
return 0;
}
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// from pcm_format in tinyalsa
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PcmFormat {
PcmFormatS16BitLe = 0,
PcmFormatS8Bit,
PcmFormatS16BitBe,
PcmFormatS24BitLe,
PcmFormatS24BitBe,
PcmFormatS24Bit3Le,
PcmFormatS24Bit3Be,
PcmFormatS32BitLe,
PcmFormatS32BitBe,
PcmFormatMax,
}
// From alsalib asound.h
// tinyalsa doesn't provide this, but it's needed to check if a format is valid
// in params.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum AlsaFormatBitMask {
/** Signed 8 bit */
SND_PCM_FORMAT_S8 = 0,
/** Unsigned 8 bit */
SND_PCM_FORMAT_U8,
/** Signed 16 bit Little Endian */
SND_PCM_FORMAT_S16_LE,
/** Signed 16 bit Big
* Endian */
SND_PCM_FORMAT_S16_BE,
/** Unsigned 16 bit Little Endian */
SND_PCM_FORMAT_U16_LE,
/** Unsigned 16 bit Big Endian */
SND_PCM_FORMAT_U16_BE,
/** Signed 24 bit Little Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_S24_LE,
/** Signed 24 bit Big Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_S24_BE,
/** Unsigned 24 bit Little Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_U24_LE,
/** Unsigned 24 bit Big Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_U24_BE,
/** Signed 32 bit Little Endian */
SND_PCM_FORMAT_S32_LE,
/** Signed 32 bit Big Endian */
SND_PCM_FORMAT_S32_BE,
/** Unsigned 32 bit Little Endian */
SND_PCM_FORMAT_U32_LE,
/** Unsigned 32 bit Big Endian */
SND_PCM_FORMAT_U32_BE,
/** Float 32 bit Little Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT_LE,
/** Float 32 bit Big Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT_BE,
/** Float 64 bit Little Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT64_LE,
/** Float 64 bit Big Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT64_BE,
/** IEC-958 Little Endian */
SND_PCM_FORMAT_IEC958_SUBFRAME_LE,
/** IEC-958 Big Endian */
SND_PCM_FORMAT_IEC958_SUBFRAME_BE,
/** Mu-Law */
SND_PCM_FORMAT_MU_LAW,
/** A-Law */
SND_PCM_FORM
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 |
// from pcm_format in tinyalsa
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PcmFormat {
PcmFormatS16BitLe = 0,
PcmFormatS8Bit,
PcmFormatS16BitBe,
PcmFormatS24BitLe,
PcmFormatS24BitBe,
PcmFormatS24Bit3Le,
PcmFormatS24Bit3Be,
PcmFormatS32BitLe,
PcmFormatS32BitBe,
PcmFormatMax,
}
// From alsalib asound.h
// tinyalsa doesn't provide this, but it's needed to check if a format is valid
// in params.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum AlsaFormatBitMask {
/** Signed 8 bit */
SND_PCM_FORMAT_S8 = 0,
/** Unsigned 8 bit */
SND_PCM_FORMAT_U8,
/** Signed 16 bit Little Endian */
SND_PCM_FORMAT_S16_LE,
/** Signed 16 bit Big
* Endian */
SND_PCM_FORMAT_S16_BE,
/** Unsigned 16 bit Little Endian */
SND_PCM_FORMAT_U16_LE,
/** Unsigned 16 bit Big Endian */
SND_PCM_FORMAT_U16_BE,
/** Signed 24 bit Little Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_S24_LE,
/** Signed 24 bit Big Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_S24_BE,
/** Unsigned 24 bit Little Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_U24_LE,
/** Unsigned 24 bit Big Endian using low three bytes in 32-bit word */
SND_PCM_FORMAT_U24_BE,
/** Signed 32 bit Little Endian */
SND_PCM_FORMAT_S32_LE,
/** Signed 32 bit Big Endian */
SND_PCM_FORMAT_S32_BE,
/** Unsigned 32 bit Little Endian */
SND_PCM_FORMAT_U32_LE,
/** Unsigned 32 bit Big Endian */
SND_PCM_FORMAT_U32_BE,
/** Float 32 bit Little Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT_LE,
/** Float 32 bit Big Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT_BE,
/** Float 64 bit Little Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT64_LE,
/** Float 64 bit Big Endian, Range -1.0 to 1.0 */
SND_PCM_FORMAT_FLOAT64_BE,
/** IEC-958 Little Endian */
SND_PCM_FORMAT_IEC958_SUBFRAME_LE,
/** IEC-958 Big Endian */
SND_PCM_FORMAT_IEC958_SUBFRAME_BE,
/** Mu-Law */
SND_PCM_FORMAT_MU_LAW,
/** A-Law */
SND_PCM_FORMAT_A_LAW,
/** Ima-ADPCM */
SND_PCM_FORMAT_IMA_ADPCM,
/** MPEG */
SND_PCM_FORMAT_MPEG,
/** GSM */
SND_PCM_FORMAT_GSM,
/** Special */
SND_PCM_FORMAT_SPECIAL = 31,
/** Signed 24bit Little Endian in 3bytes format */
SND_PCM_FORMAT_S24_3LE = 32,
/** Signed 24bit Big Endian in 3bytes format */
SND_PCM_FORMAT_S24_3BE,
/** Unsigned 24bit Little Endian in 3bytes format */
SND_PCM_FORMAT_U24_3LE,
/** Unsigned 24bit Big Endian in 3bytes format */
SND_PCM_FORMAT_U24_3BE,
/** Signed 20bit Little Endian in 3bytes format */
SND_PCM_FORMAT_S20_3LE,
/** Signed 20bit Big Endian in 3bytes format */
SND_PCM_FORMAT_S20_3BE,
/** Unsigned 20bit Little Endian in 3bytes format */
SND_PCM_FORMAT_U20_3LE,
/** Unsigned 20bit Big Endian in 3bytes format */
SND_PCM_FORMAT_U20_3BE,
/** Signed 18bit Little Endian in 3bytes format */
SND_PCM_FORMAT_S18_3LE,
/** Signed 18bit Big Endian in 3bytes format */
SND_PCM_FORMAT_S18_3BE,
/** Unsigned 18bit Little Endian in 3bytes format */
SND_PCM_FORMAT_U18_3LE,
/** Unsigned 18bit Big Endian in 3bytes format */
SND_PCM_FORMAT_U18_3BE,
/* G.723 (ADPCM) 24 kbit/s, 8 samples in 3 bytes */
SND_PCM_FORMAT_G723_24,
/* G.723 (ADPCM) 24 kbit/s, 1 sample in 1 byte */
SND_PCM_FORMAT_G723_24_1B,
/* G.723 (ADPCM) 40 kbit/s, 8 samples in 3 bytes */
SND_PCM_FORMAT_G723_40,
/* G.723 (ADPCM) 40 kbit/s, 1 sample in 1 byte */
SND_PCM_FORMAT_G723_40_1B,
/* Direct Stream Digital (DSD) in 1-byte samples (x8) */
SND_PCM_FORMAT_DSD_U8,
/* Direct Stream Digital (DSD) in 2-byte samples (x16) */
SND_PCM_FORMAT_DSD_U16_LE,
/* Direct Stream Digital (DSD) in 4-byte samples (x32) */
SND_PCM_FORMAT_DSD_U32_LE,
/* Direct Stream Digital (DSD) in 2-byte samples (x16) */
SND_PCM_FORMAT_DSD_U16_BE,
/* Direct Stream Digital (DSD) in 4-byte samples (x32) */
SND_PCM_FORMAT_DSD_U32_BE,
SND_PCM_FORMAT_LAST = SND_PCM_FORMAT_DSD_U32_BE,
}
// From pcm_mask in tinyalsa
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PcmMask {
bits: [u8; 32],
}
// From pcm_config in tinyalsa
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PcmConfig {
channels: ::libc::c_uint,
rate: ::libc::c_uint,
period_size: ::libc::c_uint,
period_count: ::libc::c_uint,
format: PcmFormat,
start_threshold: ::libc::c_uint,
stop_threshold: ::libc::c_uint,
silence_threshold: ::libc::c_uint,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct SndPcmChannelArea {
addr: *mut ::libc::c_void,
first: ::libc::c_uint,
step: ::libc::c_uint,
}
// All flags from pcm.h in tinyalsa.
pub const PCM_OUT: ::libc::c_uint = 0x00000000;
pub const PCM_IN: ::libc::c_uint = 0x10000000;
pub const PCM_MMAP: ::libc::c_uint = 0x00000001;
pub const PCM_NOIRQ: ::libc::c_uint = 0x00000002;
pub const PCM_NORESTART: ::libc::c_uint = 0x00000004;
pub const PCM_MONOTONIC: ::libc::c_uint = 0x00000008;
// Enumeration of a PCM's hardware parameters.
// Each of these parameters is either a mask or an interval.
// @ingroup libtinyalsa-pcm
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PcmParam {
/** A mask that represents the type of read or write method available (e.g. interleaved, mmap). */
Access,
/** A mask that represents the @ref pcm_format available (e.g. @ref PCM_FORMAT_S32_LE) */
Format,
/** A mask that represents the subformat available */
Subformat,
/** An interval representing the range of sample bits available (e.g. 8 to 32) */
SampleBits,
/** An interval representing the range of frame bits available (e.g. 8 to 64) */
FrameBits,
/** An interval representing the range of channels available (e.g. 1 to 2) */
Channels,
/** An interval representing the range of rates available (e.g. 44100 to 192000) */
Rate,
PeriodTime,
/** The number of frames in a period */
PeriodSize,
/** The number of bytes in a period */
PeriodBytes,
/** The number of periods for a PCM */
Periods,
BufferTime,
BufferSize,
BufferBytes,
TickTime,
} /* enum pcm_param */
pub enum Pcm {} // struct pcm in tinyalsa
pub enum PcmParams {} // struct pcm_params in tinyalsa
#[link(name = "tinyalsa")]
extern "C" {
pub fn pcm_open(card: ::libc::c_uint,
device: ::libc::c_uint,
flags: ::libc::c_uint,
config: *const PcmConfig)
-> Option<&mut Pcm>;
pub fn pcm_close(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_is_ready(pcm: *const Pcm) -> ::libc::c_int;
pub fn pcm_get_channels(pcm: *const Pcm) -> ::libc::c_uint;
pub fn pcm_get_rate(pcm: *const Pcm) -> ::libc::c_uint;
pub fn pcm_get_format(pcm: *const Pcm) -> PcmFormat;
pub fn pcm_get_error(pcm: *const Pcm) -> *const ::libc::c_char;
pub fn pcm_get_subdevice(pcm: *const Pcm) -> ::libc::c_uint;
pub fn pcm_format_to_bits(format: PcmFormat) -> ::libc::c_uint;
pub fn pcm_frames_to_bytes(pcm: *const Pcm, frames: ::libc::c_uint) -> ::libc::c_uint;
pub fn pcm_get_htimestamp(pcm: *mut Pcm,
avail: *mut ::libc::c_uint,
timespec: *mut ::libc::timespec)
-> ::libc::c_int;
pub fn pcm_writei(pcm: *mut Pcm,
data: *const ::libc::c_void,
frames: ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_readi(pcm: *mut Pcm,
data: *mut ::libc::c_void,
frames: ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_params_get(card: ::libc::c_uint,
device: ::libc::c_uint,
flags: ::libc::c_uint)
-> Option<&mut PcmParams>;
pub fn pcm_params_free(pcm_params: *mut PcmParams);
pub fn pcm_params_get_mask(pcm_params: *const PcmParams, param: PcmParam) -> Option<&PcmMask>;
pub fn pcm_params_get_min(pcm_params: *const PcmParams, param: PcmParam) -> ::libc::c_uint;
pub fn pcm_params_get_max(pcm_params: *const PcmParams, param: PcmParam) -> ::libc::c_uint;
pub fn pcm_link(pcm: *mut Pcm, pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_unlink(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_prepare(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_start(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_stop(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_avail_update(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_state(pcm: *mut Pcm) -> ::libc::c_int;
pub fn pcm_wait(pcm: *mut Pcm, timeout_ms: ::libc::c_int) -> ::libc::c_int;
pub fn pcm_get_delay(pcm: *mut Pcm) -> ::libc::c_long;
pub fn pcm_mmap_begin(pcm: *mut Pcm,
areas: *mut *const SndPcmChannelArea,
offset: *mut ::libc::c_uint,
frames: *mut ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_mmap_commit(pcm: *mut Pcm,
offset: ::libc::c_uint,
frames: ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_mmap_transfer(pcm: *mut Pcm,
buffer: *const ::libc::c_void,
bytes: ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_mmap_write(pcm: *mut Pcm,
data: *const ::libc::c_void,
count: ::libc::c_uint)
-> ::libc::c_int;
pub fn pcm_mmap_read(pcm: *mut Pcm,
data: *mut ::libc::c_void,
count: ::libc::c_uint)
-> ::libc::c_int;
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CStr;
const PCM_CARD: u32 = 1;
const PCM_DEV: u32 = 0;
const PCM_DEV_CONFIG: PcmConfig = PcmConfig {
channels: 2,
rate: 48000,
period_size: 512,
period_count: 2,
format: PcmFormat::PcmFormatS16BitLe,
start_threshold: 0,
stop_threshold: 0,
silence_threshold: 0,
};
#[test]
fn basic_pcm_config() {
unsafe {
let pcm = pcm_open(PCM_CARD, PCM_DEV, 0, &PCM_DEV_CONFIG).unwrap();
assert_eq!(1, pcm_is_ready(pcm));
assert_eq!(2, pcm_get_channels(pcm));
assert_eq!(48000, pcm_get_rate(pcm));
assert_eq!(0, pcm_get_subdevice(pcm));
assert_eq!(PcmFormat::PcmFormatS16BitLe, pcm_get_format(pcm));
assert_eq!(0, pcm_close(pcm));
}
}
#[test]
fn params_test() {
unsafe {
let params = pcm_params_get(PCM_CARD, PCM_DEV, PCM_OUT);
assert!(params.is_some());
if let Some(params) = params {
assert!(pcm_params_get_min(params, PcmParam::Rate) <= 48000);
assert!(pcm_params_get_max(params, PcmParam::Rate) >= 48000);
let format_mask = pcm_params_get_mask(params, PcmParam::Format);
assert!(format_mask.is_some());
assert_ne!(0, format_mask.unwrap().bits[0]);
pcm_params_free(params);
}
}
}
#[test]
fn config_error_string() {
let mut this_config = PCM_DEV_CONFIG;
this_config.rate = 55;
unsafe {
let pcm = pcm_open(PCM_CARD, PCM_DEV, 0, &this_config).unwrap();
assert_eq!(0, pcm_is_ready(pcm));
assert_eq!(CStr::from_bytes_with_nul(b"cannot set hw params: Invalid argument\0")
.unwrap(),
CStr::from_ptr(pcm_get_error(pcm)));
}
}
#[test]
fn format_to_bits() {
unsafe {
assert_eq!(16, pcm_format_to_bits(PcmFormat::PcmFormatS16BitLe));
assert_eq!(8, pcm_format_to_bits(PcmFormat::PcmFormatS8Bit));
assert_eq!(16, pcm_format_to_bits(PcmFormat::PcmFormatS16BitBe));
assert_eq!(32, pcm_format_to_bits(PcmFormat::PcmFormatS24BitLe));
assert_eq!(32, pcm_format_to_bits(PcmFormat::PcmFormatS24BitBe));
assert_eq!(24, pcm_format_to_bits(PcmFormat::PcmFormatS24Bit3Le));
assert_eq!(24, pcm_format_to_bits(PcmFormat::PcmFormatS24Bit3Be));
assert_eq!(32, pcm_format_to_bits(PcmFormat::PcmFormatS32BitLe));
assert_eq!(32, pcm_format_to_bits(PcmFormat::PcmFormatS32BitBe));
}
}
#[test]
fn frames_to_bytes() {
unsafe {
let pcm = pcm_open(PCM_CARD, PCM_DEV, 0, &PCM_DEV_CONFIG).unwrap();
assert_eq!(1, pcm_is_ready(pcm));
assert_eq!(256, pcm_frames_to_bytes(pcm, 64));
assert_eq!(0, pcm_close(pcm));
}
}
#[test]
fn mmap_output() {
unsafe {
if let Some(pcm) = pcm_open(PCM_CARD, PCM_DEV, PCM_OUT | PCM_MMAP, &PCM_DEV_CONFIG) {
assert_eq!(1, pcm_is_ready(pcm));
assert_eq!(0, pcm_start(pcm));
let mut areas: *const SndPcmChannelArea = ::std::ptr::null();
let mut offset: ::libc::c_uint = 0;
let mut frames: ::libc::c_uint = 512;
assert_eq!(0,
pcm_mmap_begin(pcm,
&mut areas as *mut *const SndPcmChannelArea,
&mut offset,
&mut frames));
println!("offset {}, frames {}", offset, frames);
assert_eq!(0, pcm_mmap_commit(pcm, offset, 0));
assert_eq!(0, pcm_close(pcm));
} else {
assert!(false);
}
}
}
#[test]
fn basic_writei() {
unsafe {
let zero_buf: [i16; 1024] = [0; 1024];
let pcm = pcm_open(PCM_CARD, PCM_DEV, 0, &PCM_DEV_CONFIG).unwrap();
let mut avail: ::libc::c_uint = 0;
let mut ht = ::libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
assert_eq!(1, pcm_is_ready(pcm));
assert_eq!(512,
pcm_writei(pcm, &zero_buf[0] as *const _ as *const ::libc::c_void, 512));
assert_eq!(0, pcm_get_htimestamp(pcm, &mut avail, &mut ht));
assert_eq!(512, avail);
assert_eq!(0, pcm_close(pcm));
}
}
#[test]
fn basic_readi() {
unsafe {
let mut zero_buf: [i16; 1024] = [0; 1024];
let pcm = pcm_open(PCM_CARD, PCM_DEV, PCM_IN, &PCM_DEV_CONFIG).unwrap();
assert_eq!(1, pcm_is_ready(pcm));
assert_eq!(512,
pcm_readi(pcm, &mut zero_buf[0] as *mut _ as *mut ::libc::c_void, 512));
assert_eq!(0, pcm_close(pcm));
}
}
}
|
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:
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status = transactionManager.getTransaction(def);
try {
// mapper invoke
examinationMapper.updateById(examinationPo);
//commit
transactionManager.commit(status);
System.out.println("done");
} catch (Exception e) {
log.error(e.getMessage(), e);
//rollback
transactionManager.rollback(status);
}
事务提交
transactionManager.commit(status);
事务开始:
TransactionStatus status = transactionManager.getTransaction(def);
============================================================================================================
additional 场景:
对于 REQUIRES_NEW 要刮起当前事务。
PROPAGATION_REQUIRES_NEW
// unbind
// 1.
SqlSessionUtils.suspend()
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
// 2.
DataSourceTransactionManager.doSuspend
TransactionSynchronizationManager.unbindResource(obtainDataSource());
============================================================================================================
!!!事务开始!!!
//bind 操作
① Spring事务管理:
DataSourceTransactionManager.doBegin
// Bind the connection holder to the thread.
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
}
↓
↓
② mapper invoke 当遇到mapper执行。开始绑定SQLSession相关。 即 getSqlSession() 获取代理mapper时
SqlSessionUtils.registerSessionHolder
holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
TransactionSynchronizationManager.bindResource(sessionFactory, holder);
↓
执行sql,完成。
↓
↓
↓
// unbind 由transactionManager.commit(status); 触发
triggerBeforeCompletion
TransactionSynchronizationUtils.triggerBeforeCompletion();
==> B1
processCommit
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 |
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status = transactionManager.getTransaction(def);
try {
// mapper invoke
examinationMapper.updateById(examinationPo);
//commit
transactionManager.commit(status);
System.out.println("done");
} catch (Exception e) {
log.error(e.getMessage(), e);
//rollback
transactionManager.rollback(status);
}
事务提交
transactionManager.commit(status);
事务开始:
TransactionStatus status = transactionManager.getTransaction(def);
============================================================================================================
additional 场景:
对于 REQUIRES_NEW 要刮起当前事务。
PROPAGATION_REQUIRES_NEW
// unbind
// 1.
SqlSessionUtils.suspend()
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
// 2.
DataSourceTransactionManager.doSuspend
TransactionSynchronizationManager.unbindResource(obtainDataSource());
============================================================================================================
!!!事务开始!!!
//bind 操作
① Spring事务管理:
DataSourceTransactionManager.doBegin
// Bind the connection holder to the thread.
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
}
↓
↓
② mapper invoke 当遇到mapper执行。开始绑定SQLSession相关。 即 getSqlSession() 获取代理mapper时
SqlSessionUtils.registerSessionHolder
holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
TransactionSynchronizationManager.bindResource(sessionFactory, holder);
↓
执行sql,完成。
↓
↓
↓
// unbind 由transactionManager.commit(status); 触发
triggerBeforeCompletion
TransactionSynchronizationUtils.triggerBeforeCompletion();
==> B1
processCommit
==> B2
.
a》
AbstractPlatformTransactionManager.triggerBeforeCompletion
TransactionSynchronizationUtils.triggerBeforeCompletion();
TransactionSynchronizationManager.getSynchronizations().foreach( synchronization -> synchronization.beforeCompletion() )
.
synchronization ==> SqlSessionUtils 中的内部类: SqlSessionSynchronization
TransactionSynchronizationAdapter implements TransactionSynchronization
private static final class SqlSessionSynchronization extends TransactionSynchronizationAdapter
SqlSessionSynchronization.beforeCompletion()
.
b》
finally {
AbstractPlatformTransactionManager.cleanupAfterCompletion(status);
}
.
.
B1
SqlSessionUtils.beforeCompletion()
TransactionSynchronizationManager.unbindResource(sessionFactory);
B2
DataSourceTransactionManager.doCleanupAfterCompletion()
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
|
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:
# ssr 6系列更新仓库
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 |
# ssr 6系列更新仓库
|
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
/**
* Copyright © 2018 OpenGento, All rights reserved.
* See LICENSE bundled with this library for license details.
*/
declare(strict_types=1);
namespace Opengento\Gdpr\Controller\Privacy;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Archive\Zip;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Phrase;
use Opengento\Gdpr\Controller\AbstractPrivacy;
use Opengento\Gdpr\Model\Config;
use Opengento\Gdpr\Service\ExportManagement;
use Opengento\Gdpr\Service\ExportStrategy;
/**
* Action Export Export
*/
class Export extends AbstractPrivacy implements ActionInterface
{
/**
* @var \Magento\Framework\App\Response\Http\FileFactory
*/
private $fileFactory;
/**
* @var \Magento\Framework\Archive\Zip
*/
private $zip;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
private $file;
/**
* @var \Opengento\Gdpr\Model\Config
*/
private $config;
/**
* @var \Opengento\Gdpr\Service\ExportManagement
*/
private $exportManagement;
/**
* @var \Opengento\Gdpr\Service\ExportStrategy
*/
private $exportStrategy;
/**
* @var \Magento\Customer\Model\Session
*/
private $customerSession;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
* @param \Magento\Framework\Archive\Zip $zip
* @param \Magento\Framework\Filesystem\Driver\File $file
* @param \Opengento\Gdpr\Model\Config $config
* @param \Opengento\Gdpr\Service\ExportManagement $exportManagement
* @param \Opengento\Gdpr\Service\ExportStrategy $exportStrategy
* @param
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
/**
* Copyright © 2018 OpenGento, All rights reserved.
* See LICENSE bundled with this library for license details.
*/
declare(strict_types=1);
namespace Opengento\Gdpr\Controller\Privacy;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Archive\Zip;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Phrase;
use Opengento\Gdpr\Controller\AbstractPrivacy;
use Opengento\Gdpr\Model\Config;
use Opengento\Gdpr\Service\ExportManagement;
use Opengento\Gdpr\Service\ExportStrategy;
/**
* Action Export Export
*/
class Export extends AbstractPrivacy implements ActionInterface
{
/**
* @var \Magento\Framework\App\Response\Http\FileFactory
*/
private $fileFactory;
/**
* @var \Magento\Framework\Archive\Zip
*/
private $zip;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
private $file;
/**
* @var \Opengento\Gdpr\Model\Config
*/
private $config;
/**
* @var \Opengento\Gdpr\Service\ExportManagement
*/
private $exportManagement;
/**
* @var \Opengento\Gdpr\Service\ExportStrategy
*/
private $exportStrategy;
/**
* @var \Magento\Customer\Model\Session
*/
private $customerSession;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
* @param \Magento\Framework\Archive\Zip $zip
* @param \Magento\Framework\Filesystem\Driver\File $file
* @param \Opengento\Gdpr\Model\Config $config
* @param \Opengento\Gdpr\Service\ExportManagement $exportManagement
* @param \Opengento\Gdpr\Service\ExportStrategy $exportStrategy
* @param \Magento\Customer\Model\Session $customerSession
*/
public function __construct(
Context $context,
FileFactory $fileFactory,
Zip $zip,
File $file,
Config $config,
ExportManagement $exportManagement,
ExportStrategy $exportStrategy,
Session $customerSession
) {
$this->fileFactory = $fileFactory;
$this->zip = $zip;
$this->file = $file;
$this->config = $config;
$this->exportManagement = $exportManagement;
$this->exportStrategy = $exportStrategy;
$this->customerSession = $customerSession;
parent::__construct($context);
}
/**
* {@inheritdoc}
*/
public function execute()
{
if (!$this->config->isExportEnabled()){
return $this->forwardNoRoute();
}
try {
return $this->download();
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, new Phrase('Something went wrong. Try again later.'));
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('customer/privacy/settings');
}
}
/**
* Download zip of a csv with customer privacy data
*
* @return \Magento\Framework\App\ResponseInterface
* @throws \Exception
* @throws \Magento\Framework\Exception\FileSystemException
* @throws \Magento\Framework\Exception\LocalizedException
* @deprecated
* @todo debug
*/
public function download(): ResponseInterface
{
$privacyData = $this->exportManagement->execute($this->customerSession->getCustomerId());
$fileName = $this->exportStrategy->saveData('personalData.html', $privacyData);//todo fix file name
$zipFileName = 'customer_privacy_data_' . $this->customerSession->getCustomerId() . '.zip';
$this->zip->pack($fileName, $zipFileName);
$this->unlinkFile($fileName);
return $this->fileFactory->create(
$zipFileName,
[
'type' => 'filename',
'value' => $zipFileName,
'rm' => true,
],
DirectoryList::PUB,
'zip',
null
);
}
/**
* Unlink a file
*
* @param string $fileName
* @throws \Magento\Framework\Exception\FileSystemException
*/
private function unlinkFile(string $fileName)
{
if ($this->file->isExists($fileName)) {
$this->file->deleteFile($fileName);
}
}
}
|
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 { SET } from '../actions/visiting-account';
const defaultState = null;
export default function visitingAccount(state = defaultState, action) {
switch (action.type) {
case SET: {
const { accountData } = action.payload;
return Object.assign({}, accountData);
}
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>"
|
javascript
| 2 |
import { SET } from '../actions/visiting-account';
const defaultState = null;
export default function visitingAccount(state = defaultState, action) {
switch (action.type) {
case SET: {
const { accountData } = action.payload;
return Object.assign({}, accountData);
}
default:
return state;
}
}
|
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:
import UIKit
class DefaultNavigationControllerAdapter: NSObject {
private let navigationController: UINavigationController
var delegate: NavigationControllerAdapterDelegate?
var viewControllers: [UIViewController] {
get {
return navigationController.viewControllers
}
set {
navigationController.viewControllers = newValue
}
}
init(navigationController: UINavigationController) {
self.navigationController = navigationController
super.init()
navigationController.delegate = self
}
}
extension DefaultNavigationControllerAdapter: NavigationControllerAdapter {
func pushViewController(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
navigationController.pushViewController(viewController, animated: animated)
guard let completion = completion else { return }
guard animated, let coordinator = navigationController.transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
func popToViewController(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
navigationController.popToViewController(viewController, animated: animated)
guard let completion = completion else { return }
guard animated, let coordinator = navigationController.transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
extension DefaultNavigationControllerAdapter: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
delegate?.navigationController(self, willShow: viewControl
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 |
import UIKit
class DefaultNavigationControllerAdapter: NSObject {
private let navigationController: UINavigationController
var delegate: NavigationControllerAdapterDelegate?
var viewControllers: [UIViewController] {
get {
return navigationController.viewControllers
}
set {
navigationController.viewControllers = newValue
}
}
init(navigationController: UINavigationController) {
self.navigationController = navigationController
super.init()
navigationController.delegate = self
}
}
extension DefaultNavigationControllerAdapter: NavigationControllerAdapter {
func pushViewController(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
navigationController.pushViewController(viewController, animated: animated)
guard let completion = completion else { return }
guard animated, let coordinator = navigationController.transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
func popToViewController(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
navigationController.popToViewController(viewController, animated: animated)
guard let completion = completion else { return }
guard animated, let coordinator = navigationController.transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
extension DefaultNavigationControllerAdapter: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
delegate?.navigationController(self, willShow: viewController, animated: animated)
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
delegate?.navigationController(self, didShow: viewController, animated: animated)
}
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
namespace Scheduler.Services.Data.Tests.Services.EventServiceTestsAsets
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using MockQueryable.Moq;
using Moq;
using Scheduler.Data.Common.Repositories;
using Scheduler.Data.Models;
using Scheduler.Services.Interfaces;
using Scheduler.Services.Mapping;
using Scheduler.Web.ViewModels.EventViewModel;
using Xunit;
public class EventServiceTests
{
public Mock<IDeletableEntityRepository<Event>> MockeEventRepository;
public IMapper Mapper;
public Mock<IRepository<ApplicationUserEvent>> MockApplicationUserEventRepository;
public Mock<IUserService> MockUserService;
public UriBuilder UriBuilder;
public IEventService eventService;
public EventServiceTests()
{
this.MockeEventRepository = new Mock<IDeletableEntityRepository<Event>>();
this.Mapper = new Mapper();
this.UriBuilder = new UriBuilder();
this.MockApplicationUserEventRepository = new Mock<IRepository<ApplicationUserEvent>>();
this.MockUserService = new Mock<IUserService>();
this.eventService = new EventService(
this.MockeEventRepository.Object,
this.Mapper,
this.MockApplicationUserEventRepository.Object,
this.UriBuilder,
this.MockUserService.Object);
}
[Theory]
[InlineData("SomeDescription", "someOwnerId", "Name", "10/10/2000", "18-18", "09/09/2100", "19-19")]
public async Task ShudCreateEvent(
string descriptionm,
string ownerId,
string name,
string startDate,
string s
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
| 1 |
namespace Scheduler.Services.Data.Tests.Services.EventServiceTestsAsets
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using MockQueryable.Moq;
using Moq;
using Scheduler.Data.Common.Repositories;
using Scheduler.Data.Models;
using Scheduler.Services.Interfaces;
using Scheduler.Services.Mapping;
using Scheduler.Web.ViewModels.EventViewModel;
using Xunit;
public class EventServiceTests
{
public Mock<IDeletableEntityRepository<Event>> MockeEventRepository;
public IMapper Mapper;
public Mock<IRepository<ApplicationUserEvent>> MockApplicationUserEventRepository;
public Mock<IUserService> MockUserService;
public UriBuilder UriBuilder;
public IEventService eventService;
public EventServiceTests()
{
this.MockeEventRepository = new Mock<IDeletableEntityRepository<Event>>();
this.Mapper = new Mapper();
this.UriBuilder = new UriBuilder();
this.MockApplicationUserEventRepository = new Mock<IRepository<ApplicationUserEvent>>();
this.MockUserService = new Mock<IUserService>();
this.eventService = new EventService(
this.MockeEventRepository.Object,
this.Mapper,
this.MockApplicationUserEventRepository.Object,
this.UriBuilder,
this.MockUserService.Object);
}
[Theory]
[InlineData("SomeDescription", "someOwnerId", "Name", "10/10/2000", "18-18", "09/09/2100", "19-19")]
public async Task ShudCreateEvent(
string descriptionm,
string ownerId,
string name,
string startDate,
string startTime,
string endDate,
string endTime)
{
var model = new EventAddViewModel()
{
Description = descriptionm,
StartDate = DateTime.Parse(startDate),
StartTime = DateTime.ParseExact(startTime, "mm-ss", CultureInfo.InvariantCulture),
EndDate = DateTime.Parse(endDate),
EndTime = DateTime.ParseExact(endTime, "mm-ss", CultureInfo.InvariantCulture),
Name = name,
OwnerId = ownerId,
};
this.MockeEventRepository.Setup(a => a.AddAsync(It.IsAny<Event>()))
.Returns(Task.CompletedTask);
this.MockApplicationUserEventRepository.Setup(a => a.AddAsync(It.IsAny<ApplicationUserEvent>()))
.Returns(Task.CompletedTask);
var result = await this.eventService.CreateEvent(model);
Assert.True(result);
}
[Theory]
[InlineData("1234", "12345")]
[InlineData("SomeId", "SomeOther")]
public async Task ShudAddUserToEvent(string userId, string eventId)
{
var userEvent = new ApplicationUserEvent()
{
ApplicationUserId = userId,
EventId = eventId,
};
this.MockApplicationUserEventRepository.Setup(a => a.AddAsync(It.IsAny<ApplicationUserEvent>()))
.Returns(Task.CompletedTask);
var result = await this.eventService.AddUserToEvent(userId, eventId);
Assert.True(result);
}
[Theory]
[InlineData("1234", 1)]
[InlineData("12345", 2)]
[InlineData("SomeInvalidIncurentCase", 0)]
public async Task ShudGetAllEventsForUser(string appUserId, int expectedResult)
{
var data = new List<ApplicationUserEvent>()
{
new ApplicationUserEvent()
{
ApplicationUserId = "1234",
EventId = "1234",
Event = new Event()
{
Id = "1234",
IsDeleted = false,
},
},
new ApplicationUserEvent()
{
ApplicationUserId = "12345",
EventId = "12345",
Event = new Event()
{
Id = "12345",
IsDeleted = false,
},
},
new ApplicationUserEvent()
{
ApplicationUserId = "12345",
EventId = "123456",
Event = new Event()
{
Id = "123456",
IsDeleted = false,
},
},
new ApplicationUserEvent()
{
ApplicationUserId = "12345",
EventId = "1234567",
Event = new Event()
{
Id = "1234567",
IsDeleted = true,
},
},
};
var mockDbset = data.AsQueryable().BuildMockDbSet();
this.MockApplicationUserEventRepository.Setup(a => a.All())
.Returns(mockDbset.Object);
var result = await this.eventService.GetAllEventsForUser(appUserId);
Assert.Equal(expectedResult, result.Count());
}
[Theory]
[InlineData("12345", "SomeName1")]
[InlineData("1234", "SomeName2")]
[InlineData("123456", null)]
public async Task ShudGetEvent(string eventId, string expectedResult)
{
var data = new List<Event>()
{
new Event()
{
Id = "12345",
Name = "SomeName1",
IsDeleted = false,
Owner = new ApplicationUser(),
},
new Event()
{
Id = "1234",
Name = "SomeName2",
IsDeleted = false,
Owner = new ApplicationUser(),
},
new Event()
{
Id = "123456",
Name = "SomeName3",
IsDeleted = true,
Owner = new ApplicationUser(),
},
};
var mockDbset = data.AsQueryable().BuildMockDbSet();
this.MockeEventRepository.Setup(e => e.All())
.Returns(mockDbset.Object);
Event result = await this.eventService.GetEvent(eventId);
if (string.IsNullOrEmpty(expectedResult))
{
Assert.Null(result);
}
else
{
Assert.Equal(expectedResult, result.Name);
}
}
}
}
|
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:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_DOMAIN=simbok.loc
APP_URL=http://localhost
ADMIN_DOMAIN="admin.${APP_DOMAIN}"
LOG_CHANNEL=daily
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=".${APP_DOMAIN}"
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=<PASSWORD>
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
GOOGLE_ID=
GOOGLE_SECRET=
FACEBOOK_ID=
FACEBOOK_SECRET=
TELESCOPE_ENABLED=false
INITIAL_USER_NAME=
INITIAL_USER_EMAIL=
INITIAL_USER_PASSWORDHASH=
VACANCIES_COMPANY_ID=
CONTACT_EMAILS=
DEBUGBAR_EMAIL=
CASHIER_MODEL=
CASHIER_CURRENCY=
CASHIER_LOGGER=
STRIPE_KEY=
STRIPE_SECRET=
STRIPE_WEBHOOK_SECRET=
PLAN_1_ID=
PLAN_2_ID=
PLAN_3_ID=
PLAN_4_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>"
|
shell
| 0 |
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_DOMAIN=simbok.loc
APP_URL=http://localhost
ADMIN_DOMAIN="admin.${APP_DOMAIN}"
LOG_CHANNEL=daily
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=".${APP_DOMAIN}"
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=<PASSWORD>
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
GOOGLE_ID=
GOOGLE_SECRET=
FACEBOOK_ID=
FACEBOOK_SECRET=
TELESCOPE_ENABLED=false
INITIAL_USER_NAME=
INITIAL_USER_EMAIL=
INITIAL_USER_PASSWORDHASH=
VACANCIES_COMPANY_ID=
CONTACT_EMAILS=
DEBUGBAR_EMAIL=
CASHIER_MODEL=
CASHIER_CURRENCY=
CASHIER_LOGGER=
STRIPE_KEY=
STRIPE_SECRET=
STRIPE_WEBHOOK_SECRET=
PLAN_1_ID=
PLAN_2_ID=
PLAN_3_ID=
PLAN_4_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:
<?php
session_start();
//connect to database
$db=mysqli_connect("localhost","root","","music");
if(isset($_POST['register_btn']))
{
$username=mysql_real_escape_string($_POST['username']);
$email=mysql_real_escape_string($_POST['email']);
$album_name=mysql_real_escape_string($_POST['album_name']);
$password=mysql_real_escape_string($_POST['password']);
$password2=mysql_real_escape_string($_POST['password2']);
if($password==$password2)
{ //Create User
$password=md5($password); //hash password before storing for security purposes
$sql="INSERT INTO artist(username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db,$sql);
$_SESSION['message']="You are now logged in";
$_SESSION['username']=$username;
$_SESSION['album_name']=$album_name;
header("location:adddet.php"); //redirect home page
}
else
{
$_SESSION['message']="The two password do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div class="header">
<h1> <a href="index.php" class="p">Crazy Tunes</a></h1>
</div>
<div class="header" >
<h1><a class="p">Register</a></h1>
</div>
<?php
if(isset($_SESSION['message']))
{
echo "<div id='error_msg'>".$_SESSION['message']."</div>";
unset($_SESSION['message']);
}
?>
<form method="post" action="register.php">
<table>
<tr>
<td><a class="p">Username : </a></td>
<td><input type="varchar" name="username" class="textInput"></td>
</tr>
<tr>
<td><a class="p">Email : </a> </td>
<td><input type="varchar" name="email" class="textInput"></td>
</tr>
<tr>
<td><a class="p">Password : </a></td>
<td><input type="<PASSWORD>" name="pass
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
session_start();
//connect to database
$db=mysqli_connect("localhost","root","","music");
if(isset($_POST['register_btn']))
{
$username=mysql_real_escape_string($_POST['username']);
$email=mysql_real_escape_string($_POST['email']);
$album_name=mysql_real_escape_string($_POST['album_name']);
$password=mysql_real_escape_string($_POST['password']);
$password2=mysql_real_escape_string($_POST['password2']);
if($password==$password2)
{ //Create User
$password=md5($password); //hash password before storing for security purposes
$sql="INSERT INTO artist(username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db,$sql);
$_SESSION['message']="You are now logged in";
$_SESSION['username']=$username;
$_SESSION['album_name']=$album_name;
header("location:adddet.php"); //redirect home page
}
else
{
$_SESSION['message']="The two password do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div class="header">
<h1> <a href="index.php" class="p">Crazy Tunes</a></h1>
</div>
<div class="header" >
<h1><a class="p">Register</a></h1>
</div>
<?php
if(isset($_SESSION['message']))
{
echo "<div id='error_msg'>".$_SESSION['message']."</div>";
unset($_SESSION['message']);
}
?>
<form method="post" action="register.php">
<table>
<tr>
<td><a class="p">Username : </a></td>
<td><input type="varchar" name="username" class="textInput"></td>
</tr>
<tr>
<td><a class="p">Email : </a> </td>
<td><input type="varchar" name="email" class="textInput"></td>
</tr>
<tr>
<td><a class="p">Password : </a></td>
<td><input type="<PASSWORD>" name="password" class="textInput"></td>
</tr>
<tr>
<td><a class="p">Password again: </a></td>
<td><input type="<PASSWORD>" name="<PASSWORD>" class="textInput"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="register_btn" class="Register"></td>
</tr>
</table>
</form>
</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:
SELECT *
FROM Products
ORDER BY ProductName
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
sql
| 1 |
SELECT *
FROM Products
ORDER BY ProductName
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
extern mod language;
use language :: *;
fn main () {
let exp = make_exps ();
test_atomicity (exp);
test_let_bindings (exp);
}
fn make_exps () -> ~ [CoreExpr] {
~ [EVar (~ "x"), ENum (7),
ELet (false, ~ [(~ "y", @ ENum (13)), (~ "z", @ ENum (33))],
@ EVar (~ "y"))]
}
fn test_atomicity (exp : & [CoreExpr]) {
assert is_atomic_expr (& exp [0]);
assert is_atomic_expr (& exp [1]);
assert ! is_atomic_expr (& exp [2]);
io :: println ("is_atomic_expr: passed");
}
fn test_let_bindings (exp : & [CoreExpr]) {
match exp [2] {
ELet (_, bindings, _) => {
test_bound_names (copy bindings);
test_bound_vals (copy bindings);
},
_ => fail
};
}
fn test_bound_names (bindings : ~ [CoreEquate]) {
let names : ~ [~ str] = binders_of (bindings);
assert names . len () == 2;
assert names . all (|n| {* n == ~ "y" || * n == ~ "z"});
io :: println ("binders_of: passed");
}
fn test_bound_vals (bindings : ~ [CoreEquate]) {
let vals = rhss_of (bindings);
assert vals . len () == 2;
let nums =
vals . map (|v| match * * v {ENum (n) => n, _ => fail});
assert nums [0] + nums [1] == 13 + 33;
io :: println ("rhss_of: passed");
}
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 |
extern mod language;
use language :: *;
fn main () {
let exp = make_exps ();
test_atomicity (exp);
test_let_bindings (exp);
}
fn make_exps () -> ~ [CoreExpr] {
~ [EVar (~ "x"), ENum (7),
ELet (false, ~ [(~ "y", @ ENum (13)), (~ "z", @ ENum (33))],
@ EVar (~ "y"))]
}
fn test_atomicity (exp : & [CoreExpr]) {
assert is_atomic_expr (& exp [0]);
assert is_atomic_expr (& exp [1]);
assert ! is_atomic_expr (& exp [2]);
io :: println ("is_atomic_expr: passed");
}
fn test_let_bindings (exp : & [CoreExpr]) {
match exp [2] {
ELet (_, bindings, _) => {
test_bound_names (copy bindings);
test_bound_vals (copy bindings);
},
_ => fail
};
}
fn test_bound_names (bindings : ~ [CoreEquate]) {
let names : ~ [~ str] = binders_of (bindings);
assert names . len () == 2;
assert names . all (|n| {* n == ~ "y" || * n == ~ "z"});
io :: println ("binders_of: passed");
}
fn test_bound_vals (bindings : ~ [CoreEquate]) {
let vals = rhss_of (bindings);
assert vals . len () == 2;
let nums =
vals . map (|v| match * * v {ENum (n) => n, _ => fail});
assert nums [0] + nums [1] == 13 + 33;
io :: println ("rhss_of: passed");
}
|
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 'test_helper'
class FullAnimeControllerTest < ActionController::TestCase
test "can get anime details" do
get :show, format: :json, id: 'sword-art-online'
assert_response 200
assert_equal FullAnimeSerializer.new(anime(:sword_art_online)).to_json, @response.body
end
# TODO: needs updating when editing is available to all users
test "can edit an anime as staff" do
sign_in users(:josh)
data = {
synopsis: "Hello, World!",
episode_count: 32
}
put :update, format: :json, id: 'sword-art-online', full_anime: data
assert_response 200
assert_equal 4, Version.count # 3 fixtures + new
version = Version.last
assert_equal data[:synopsis], version.object["synopsis"]
assert_equal data[:episode_count], version.object["episode_count"]
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 |
require 'test_helper'
class FullAnimeControllerTest < ActionController::TestCase
test "can get anime details" do
get :show, format: :json, id: 'sword-art-online'
assert_response 200
assert_equal FullAnimeSerializer.new(anime(:sword_art_online)).to_json, @response.body
end
# TODO: needs updating when editing is available to all users
test "can edit an anime as staff" do
sign_in users(:josh)
data = {
synopsis: "Hello, World!",
episode_count: 32
}
put :update, format: :json, id: 'sword-art-online', full_anime: data
assert_response 200
assert_equal 4, Version.count # 3 fixtures + new
version = Version.last
assert_equal data[:synopsis], version.object["synopsis"]
assert_equal data[:episode_count], version.object["episode_count"]
end
end
|
Below is an extract from a shell script. Evaluate whether it has a high educational value and could help teach shell scripting. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the script contains valid shell commands, even if it's not educational, like simple system calls or basic file operations.
- Add another point if the script addresses practical shell scripting concepts (e.g., variables, conditionals), even if it lacks comments.
- Award a third point if the script is suitable for educational use and introduces key concepts in shell scripting, even if the topic is somewhat advanced (e.g., functions, process management). The script should be well-structured and contain some comments.
- Give a fourth point if the script is self-contained and highly relevant to teaching shell scripting. It should be similar to a tutorial example or a shell scripting course section, demonstrating good practices in script organization.
- Grant a fifth point if the script is outstanding in its educational value and is perfectly suited for teaching shell scripting. It should be well-written, easy to understand, and contain step-by-step explanations in comments.
The extract:
#!/bin/sh
DIR=`dirname $0`
cd ~; cd Pictures
export DYLD_LIBRARY_PATH=$DIR/lib
exec $DIR/pyldin -t -d $DIR/share/pyldin
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
DIR=`dirname $0`
cd ~; cd Pictures
export DYLD_LIBRARY_PATH=$DIR/lib
exec $DIR/pyldin -t -d $DIR/share/pyldin
|
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 { authenticator } from 'otplib';
import 'cypress-axe';
import { clearCookiesAndLogin } from '../helpers/login';
describe('Public Form', () => {
before(() => {
const env = { DATABASE_NAME: 'uwazi_e2e', INDEX_NAME: 'uwazi_e2e' };
cy.exec('yarn blank-state', { env });
clearCookiesAndLogin('admin', 'change this password now');
cy.get('.only-desktop a[aria-label="Settings"]').click();
cy.injectAxe();
cy.wrap(
Cypress.automation('remote:debugger:protocol', {
command: 'Browser.grantPermissions',
params: {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: window.location.origin,
},
})
);
});
it('should have no detectable accessibility violations on load', () => {
cy.contains('Account');
cy.checkA11y();
});
describe('Update user', () => {
it('should change the password to a new one', () => {
cy.get('input[name=email]').type('<EMAIL>');
cy.get('input[name=password]').type('<PASSWORD>');
cy.get('input[name=passwordConfirm]').type('123');
cy.contains('button', 'Update').click();
cy.contains('Passwords do not match');
cy.get('input[name=passwordConfirm]').type('4');
cy.intercept('POST', '/api/users').as('updateUser');
cy.contains('Update').click();
cy.wait('@updateUser');
cy.contains('Dismiss').click();
});
it('should login with the new password', () => {
cy.getByTestId('account-logout').click();
cy.get('input[name=username]').type('admin');
cy.get('input[name=password]').type('<PASSWORD>');
cy.contains('button', 'Login').click();
cy.get('.only-desktop a[aria-label="Settings"]').click();
cy.injectAxe();
});
});
describe('Enable 2FA', () => {
let secret: string;
it('pass accessibility tests', () => {
cy.contains('button', 'Enable').click();
cy.checkA11y();
});
it('should enable 2FA', () => {
cy.
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 { authenticator } from 'otplib';
import 'cypress-axe';
import { clearCookiesAndLogin } from '../helpers/login';
describe('Public Form', () => {
before(() => {
const env = { DATABASE_NAME: 'uwazi_e2e', INDEX_NAME: 'uwazi_e2e' };
cy.exec('yarn blank-state', { env });
clearCookiesAndLogin('admin', 'change this password now');
cy.get('.only-desktop a[aria-label="Settings"]').click();
cy.injectAxe();
cy.wrap(
Cypress.automation('remote:debugger:protocol', {
command: 'Browser.grantPermissions',
params: {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: window.location.origin,
},
})
);
});
it('should have no detectable accessibility violations on load', () => {
cy.contains('Account');
cy.checkA11y();
});
describe('Update user', () => {
it('should change the password to a new one', () => {
cy.get('input[name=email]').type('<EMAIL>');
cy.get('input[name=password]').type('<PASSWORD>');
cy.get('input[name=passwordConfirm]').type('123');
cy.contains('button', 'Update').click();
cy.contains('Passwords do not match');
cy.get('input[name=passwordConfirm]').type('4');
cy.intercept('POST', '/api/users').as('updateUser');
cy.contains('Update').click();
cy.wait('@updateUser');
cy.contains('Dismiss').click();
});
it('should login with the new password', () => {
cy.getByTestId('account-logout').click();
cy.get('input[name=username]').type('admin');
cy.get('input[name=password]').type('<PASSWORD>');
cy.contains('button', 'Login').click();
cy.get('.only-desktop a[aria-label="Settings"]').click();
cy.injectAxe();
});
});
describe('Enable 2FA', () => {
let secret: string;
it('pass accessibility tests', () => {
cy.contains('button', 'Enable').click();
cy.checkA11y();
});
it('should enable 2FA', () => {
cy.getByTestId('copy-value-button').click();
cy.window()
.then(async win => win.navigator.clipboard.readText())
.then(value => {
secret = value;
const token = authenticator.generate(value);
cy.get('input[name=token]').type(token);
cy.contains('aside button', 'Enable').click();
cy.contains('Activated');
cy.contains('Dismiss').click();
});
});
it('should login with 2FA', () => {
cy.getByTestId('account-logout').click();
cy.get('input[name=username]').type('admin');
cy.get('input[name=password]').type('<PASSWORD>');
cy.contains('button', 'Login').click();
cy.get('input[name=token]').type(authenticator.generate(secret));
cy.contains('button', 'Verify').click();
});
});
});
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.elenverve.dvo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class SocialProductDvo implements Serializable{
private String socialProductId;
private long fbLikesCtr;
private long fbShareCtr;
private long tweetsCtr;
private long recomendationCtr;
private long dislikeCtr;
private List<TestimonialDvo> reviews= new ArrayList<TestimonialDvo>();
public String getSocialProductId() {
return socialProductId;
}
public void setSocialProductId(String socialProductId) {
this.socialProductId = socialProductId;
}
public long getFbLikesCtr() {
return fbLikesCtr;
}
public void setFbLikesCtr(long fbLikesCtr) {
this.fbLikesCtr = fbLikesCtr;
}
public long getFbShareCtr() {
return fbShareCtr;
}
public void setFbShareCtr(long fbShareCtr) {
this.fbShareCtr = fbShareCtr;
}
public long getTweetsCtr() {
return tweetsCtr;
}
public void setTweetsCtr(long tweetsCtr) {
this.tweetsCtr = tweetsCtr;
}
public long getRecomendationCtr() {
return recomendationCtr;
}
public void setRecomendationCtr(long recomendationCtr) {
this.recomendationCtr = recomendationCtr;
}
public long getDislikeCtr() {
return dislikeCtr;
}
public void setDislikeCtr(long dislikeCtr) {
this.dislikeCtr = dislikeCtr;
}
public List<TestimonialDvo> getReviews() {
return reviews;
}
public void addReview(TestimonialDvo review) {
this.reviews.add(review);
}
}
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 com.elenverve.dvo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class SocialProductDvo implements Serializable{
private String socialProductId;
private long fbLikesCtr;
private long fbShareCtr;
private long tweetsCtr;
private long recomendationCtr;
private long dislikeCtr;
private List<TestimonialDvo> reviews= new ArrayList<TestimonialDvo>();
public String getSocialProductId() {
return socialProductId;
}
public void setSocialProductId(String socialProductId) {
this.socialProductId = socialProductId;
}
public long getFbLikesCtr() {
return fbLikesCtr;
}
public void setFbLikesCtr(long fbLikesCtr) {
this.fbLikesCtr = fbLikesCtr;
}
public long getFbShareCtr() {
return fbShareCtr;
}
public void setFbShareCtr(long fbShareCtr) {
this.fbShareCtr = fbShareCtr;
}
public long getTweetsCtr() {
return tweetsCtr;
}
public void setTweetsCtr(long tweetsCtr) {
this.tweetsCtr = tweetsCtr;
}
public long getRecomendationCtr() {
return recomendationCtr;
}
public void setRecomendationCtr(long recomendationCtr) {
this.recomendationCtr = recomendationCtr;
}
public long getDislikeCtr() {
return dislikeCtr;
}
public void setDislikeCtr(long dislikeCtr) {
this.dislikeCtr = dislikeCtr;
}
public List<TestimonialDvo> getReviews() {
return reviews;
}
public void addReview(TestimonialDvo review) {
this.reviews.add(review);
}
}
|
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:
# sort_command_3.sh
cat /dev/stdin | sort -n
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 2 |
# sort_command_3.sh
cat /dev/stdin | sort -n
|
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 test.action;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
public class actiontest_category {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void findAll() {
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package test.action;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
public class actiontest_category {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void findAll() {
}
}
|
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: mojifan [<https://github.com/mojifan>]
*/
namespace common\components;
use yii;
use yii\helpers\Html;
use common\models\Meta;
use common\models\Relationship;
class CategoryComp extends BaseComp{
private $_allCategoryList=[];
private $_parentIdList=[];
private $_childrenIdList=[];
public function __construct(){
parent::__construct();
$allList=Meta::find()->where(['type'=>Meta::TYPE_CATEGORY])->asArray()->all();
//循环获取层次关系
foreach($allList as $v){
$this->_allCategoryList[$v['mid']]=$v;//将id作为key
if(!array_key_exists($v['mid'],$this->_childrenIdList)){
$this->_childrenIdList[$v['mid']]=[];
}
$this->_childrenIdList[$v['parent']][]=$v['mid'];
$this->_parentIdList[$v['mid']]=$v['parent'];
}
}
public function getAllChildren(){
$list=[];
if(!empty($this->_childrenIdList)){
foreach($this->_childrenIdList[0] as $v){
$list=array_merge($list,$this->getChildren($v));
}
return $list;
}
}
public function getChildren($parent,$depth=1){
$parent=intval($parent);
if($parent!=0&&!$this->isCategoryExist($parent)){
return [];
}
$cate=$this->_allCategoryList[$parent];
$cate['depth']=$depth;
$list[]=$cate;
foreach($this->_childrenIdList[$parent] as $v){
$list=array_merge($list,$this->getChildren($v,$depth+1));
}
return $list;
}
//获取所有父类
public function getParents($child){
$child=intval($child);
if($child!=0&&!$this->isCategoryExist($child)){
return [];
}
$parent=array_key_exists($child,$this->_parentIdList)?$this->_parentIdList[$child]:0;
$list=[];
while($parent>0){
$list[]=$this->isCategoryExist($parent)?$this->_allCategoryList[$parent]:[];
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: mojifan [<https://github.com/mojifan>]
*/
namespace common\components;
use yii;
use yii\helpers\Html;
use common\models\Meta;
use common\models\Relationship;
class CategoryComp extends BaseComp{
private $_allCategoryList=[];
private $_parentIdList=[];
private $_childrenIdList=[];
public function __construct(){
parent::__construct();
$allList=Meta::find()->where(['type'=>Meta::TYPE_CATEGORY])->asArray()->all();
//循环获取层次关系
foreach($allList as $v){
$this->_allCategoryList[$v['mid']]=$v;//将id作为key
if(!array_key_exists($v['mid'],$this->_childrenIdList)){
$this->_childrenIdList[$v['mid']]=[];
}
$this->_childrenIdList[$v['parent']][]=$v['mid'];
$this->_parentIdList[$v['mid']]=$v['parent'];
}
}
public function getAllChildren(){
$list=[];
if(!empty($this->_childrenIdList)){
foreach($this->_childrenIdList[0] as $v){
$list=array_merge($list,$this->getChildren($v));
}
return $list;
}
}
public function getChildren($parent,$depth=1){
$parent=intval($parent);
if($parent!=0&&!$this->isCategoryExist($parent)){
return [];
}
$cate=$this->_allCategoryList[$parent];
$cate['depth']=$depth;
$list[]=$cate;
foreach($this->_childrenIdList[$parent] as $v){
$list=array_merge($list,$this->getChildren($v,$depth+1));
}
return $list;
}
//获取所有父类
public function getParents($child){
$child=intval($child);
if($child!=0&&!$this->isCategoryExist($child)){
return [];
}
$parent=array_key_exists($child,$this->_parentIdList)?$this->_parentIdList[$child]:0;
$list=[];
while($parent>0){
$list[]=$this->isCategoryExist($parent)?$this->_allCategoryList[$parent]:[];
$parent=array_key_exists($parent,$this->_parentIdList)?$this->_parentIdList[$parent]:0;
}
return $list;
}
//获取父类
public function getParent($child){
$parent=array_key_exists($child,$this->_parentIdList)?$this->_parentIdList[$child]:0;
if($parent>0){
return $this->isCategoryExist($parent)?$this->_allCategoryList[$parent]:null;
}else{
return null;
}
}
/**
* 根据id判断分类是否存在
* @param string $id 分类id
* @return bool
*/
public function isCategoryExist($id){
return array_key_exists($id,$this->_allCategoryList);
}
/**
* 获取直接子分类列表
* @param $parent
* @return array
*/
public function getSubCategoryList($parent){
$parent=intval($parent);
if($parent!=0&&!$this->isCategoryExist($parent)){
return [];
}
$list=[];
if(!empty($this->_childrenIdList)){
foreach($this->_childrenIdList[$parent] as $v){
$list[$v]=$this->_allCategoryList[$v];
}
}
return $list;
}
//直接子分类数量
public function subCategoryCount($parent){
$parent=intval($parent);
if($parent!=0&&!$this->isCategoryExist($parent)){
return 0;
}
return count($this->_childrenIdList[$parent]);
}
//显示子分类链接还是创建链接
public function displayCategoryCountOrCreateLink($parent){
$count=$this->subCategoryCount($parent);
if($count==0){
return Html::a('新增',['category/create','parent'=>$parent]);
}else{
return Html::a($count.'个分类',['category','parent'=>$parent]);
}
}
//删除分类
public function deleteCategory($id){
$model=Meta::findOne(['mid'=>$id,'type'=>Meta::TYPE_CATEGORY]);
if(!$model){
return false;
}
//修改直接子类的父级id
Meta::updateAll(['parent'=>$model->parent],'parent=:parent AND type=:type',[':parent'=>$id,':type'=>Meta::TYPE_CATEGORY]);
//删除和文章的关联
Relationship::deleteAll(['mid'=>$id]);
//删除分类
return $model->delete();
}
//获取文章所属分类
public function getCategoryWithPostId($cid){
$list=Relationship::findAll(['cid'=>$cid]);
$categoryArr=[];
foreach($list as $v){
if($this->isCategoryExist($v->mid)){
$categoryArr[]=$this->_allCategoryList[$v->mid];
}
}
return $categoryArr;
}
public function insertPostCategory($cid,$category){
if(!is_array($category)){
return false;
}
//删除文章的关联分类
Relationship::deleteAll(['cid'=>$cid]);
//todo:更新分类文章数量
foreach($category as $v){
if(!$this->isCategoryExist($v)){
continue;
}
$model=new Relationship();
$model->cid=$cid;
$model->mid=$v;
$model->insert(false);
}
return true;
}
public function getCategoryCount(){
return Meta::find()->where(['type'=>Meta::TYPE_CATEGORY])->count();
}
public function getSingleCategory($mid){
$cate=[];
if($this->isCategoryExist($mid)){
$cate=$this->_allCategoryList[$mid];
}
return $cate;
}
}
|
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:
Since The End
-------------
Pure billows of dull shades of transluscent
sepia smoke shines the hooves and you perform like a cathedral and everybody here is waiting for the next soul.
Lighthouse. You appreciated yourself for conducting.
In my field at morning you are like a pencil
and your form and colour the way I breathe them.
Directionless mothers and people.
For me they are overtone.
Blushing a door
drank in the resolute thunder.
Conducting from harsh copper.
One individual option and a iridescent rug making an absent minded thing of a unlikely meeting with a fisherman.
We get the faith
they must lots to protect
to each other
or perhaps nothing but lonely roads.
Perhaps they are not soddened.
Against the chimney like graphite.
The nauesous oyster carries outside the lovely darkness.
When you wet like quiver perched by the heat.
Purity is gone, the subject has mingled.
It was the early light of day of the toucan.
A natural sunshine of apples.
Of a black sailor that divulges dews.
It was the holiday of the jaguar.
Respect is gone, the subject has dawned.
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
| 0 |
Since The End
-------------
Pure billows of dull shades of transluscent
sepia smoke shines the hooves and you perform like a cathedral and everybody here is waiting for the next soul.
Lighthouse. You appreciated yourself for conducting.
In my field at morning you are like a pencil
and your form and colour the way I breathe them.
Directionless mothers and people.
For me they are overtone.
Blushing a door
drank in the resolute thunder.
Conducting from harsh copper.
One individual option and a iridescent rug making an absent minded thing of a unlikely meeting with a fisherman.
We get the faith
they must lots to protect
to each other
or perhaps nothing but lonely roads.
Perhaps they are not soddened.
Against the chimney like graphite.
The nauesous oyster carries outside the lovely darkness.
When you wet like quiver perched by the heat.
Purity is gone, the subject has mingled.
It was the early light of day of the toucan.
A natural sunshine of apples.
Of a black sailor that divulges dews.
It was the holiday of the jaguar.
Respect is gone, the subject has dawned.
|
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 'microsoft_kiota_abstractions'
require_relative '../microsoft_graph'
require_relative './models'
module MicrosoftGraph
module Models
class EducationSchool < MicrosoftGraph::Models::EducationOrganization
include MicrosoftKiotaAbstractions::Parsable
##
# Address of the school.
@address
##
# The underlying administrativeUnit for this school.
@administrative_unit
##
# Classes taught at the school. Nullable.
@classes
##
# Entity who created the school.
@created_by
##
# ID of school in syncing system.
@external_id
##
# ID of principal in syncing system.
@external_principal_id
##
# The fax property
@fax
##
# Highest grade taught.
@highest_grade
##
# Lowest grade taught.
@lowest_grade
##
# Phone number of school.
@phone
##
# Email address of the principal.
@principal_email
##
# Name of the principal.
@principal_name
##
# School Number.
@school_number
##
# Users in the school. Nullable.
@users
##
## Gets the address property value. Address of the school.
## @return a physical_address
##
def address
return @address
end
##
## Sets the address property value. Address of the school.
## @param value Value to set for the address property.
## @return a void
##
def address=(value)
@address = value
end
##
## Gets the administrativ
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 'microsoft_kiota_abstractions'
require_relative '../microsoft_graph'
require_relative './models'
module MicrosoftGraph
module Models
class EducationSchool < MicrosoftGraph::Models::EducationOrganization
include MicrosoftKiotaAbstractions::Parsable
##
# Address of the school.
@address
##
# The underlying administrativeUnit for this school.
@administrative_unit
##
# Classes taught at the school. Nullable.
@classes
##
# Entity who created the school.
@created_by
##
# ID of school in syncing system.
@external_id
##
# ID of principal in syncing system.
@external_principal_id
##
# The fax property
@fax
##
# Highest grade taught.
@highest_grade
##
# Lowest grade taught.
@lowest_grade
##
# Phone number of school.
@phone
##
# Email address of the principal.
@principal_email
##
# Name of the principal.
@principal_name
##
# School Number.
@school_number
##
# Users in the school. Nullable.
@users
##
## Gets the address property value. Address of the school.
## @return a physical_address
##
def address
return @address
end
##
## Sets the address property value. Address of the school.
## @param value Value to set for the address property.
## @return a void
##
def address=(value)
@address = value
end
##
## Gets the administrativeUnit property value. The underlying administrativeUnit for this school.
## @return a administrative_unit
##
def administrative_unit
return @administrative_unit
end
##
## Sets the administrativeUnit property value. The underlying administrativeUnit for this school.
## @param value Value to set for the administrativeUnit property.
## @return a void
##
def administrative_unit=(value)
@administrative_unit = value
end
##
## Gets the classes property value. Classes taught at the school. Nullable.
## @return a education_class
##
def classes
return @classes
end
##
## Sets the classes property value. Classes taught at the school. Nullable.
## @param value Value to set for the classes property.
## @return a void
##
def classes=(value)
@classes = value
end
##
## Instantiates a new educationSchool and sets the default values.
## @return a void
##
def initialize()
super
@odata_type = "#microsoft.graph.educationSchool"
end
##
## Gets the createdBy property value. Entity who created the school.
## @return a identity_set
##
def created_by
return @created_by
end
##
## Sets the createdBy property value. Entity who created the school.
## @param value Value to set for the createdBy property.
## @return a void
##
def created_by=(value)
@created_by = value
end
##
## Creates a new instance of the appropriate class based on discriminator value
## @param parse_node The parse node to use to read the discriminator value and create the object
## @return a education_school
##
def self.create_from_discriminator_value(parse_node)
raise StandardError, 'parse_node cannot be null' if parse_node.nil?
return EducationSchool.new
end
##
## Gets the externalId property value. ID of school in syncing system.
## @return a string
##
def external_id
return @external_id
end
##
## Sets the externalId property value. ID of school in syncing system.
## @param value Value to set for the externalId property.
## @return a void
##
def external_id=(value)
@external_id = value
end
##
## Gets the externalPrincipalId property value. ID of principal in syncing system.
## @return a string
##
def external_principal_id
return @external_principal_id
end
##
## Sets the externalPrincipalId property value. ID of principal in syncing system.
## @param value Value to set for the externalPrincipalId property.
## @return a void
##
def external_principal_id=(value)
@external_principal_id = value
end
##
## Gets the fax property value. The fax property
## @return a string
##
def fax
return @fax
end
##
## Sets the fax property value. The fax property
## @param value Value to set for the fax property.
## @return a void
##
def fax=(value)
@fax = value
end
##
## The deserialization information for the current model
## @return a i_dictionary
##
def get_field_deserializers()
return super.merge({
"address" => lambda {|n| @address = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::PhysicalAddress.create_from_discriminator_value(pn) }) },
"administrativeUnit" => lambda {|n| @administrative_unit = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::AdministrativeUnit.create_from_discriminator_value(pn) }) },
"classes" => lambda {|n| @classes = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::EducationClass.create_from_discriminator_value(pn) }) },
"createdBy" => lambda {|n| @created_by = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::IdentitySet.create_from_discriminator_value(pn) }) },
"externalId" => lambda {|n| @external_id = n.get_string_value() },
"externalPrincipalId" => lambda {|n| @external_principal_id = n.get_string_value() },
"fax" => lambda {|n| @fax = n.get_string_value() },
"highestGrade" => lambda {|n| @highest_grade = n.get_string_value() },
"lowestGrade" => lambda {|n| @lowest_grade = n.get_string_value() },
"phone" => lambda {|n| @phone = n.get_string_value() },
"principalEmail" => lambda {|n| @principal_email = n.get_string_value() },
"principalName" => lambda {|n| @principal_name = n.get_string_value() },
"schoolNumber" => lambda {|n| @school_number = n.get_string_value() },
"users" => lambda {|n| @users = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::EducationUser.create_from_discriminator_value(pn) }) },
})
end
##
## Gets the highestGrade property value. Highest grade taught.
## @return a string
##
def highest_grade
return @highest_grade
end
##
## Sets the highestGrade property value. Highest grade taught.
## @param value Value to set for the highestGrade property.
## @return a void
##
def highest_grade=(value)
@highest_grade = value
end
##
## Gets the lowestGrade property value. Lowest grade taught.
## @return a string
##
def lowest_grade
return @lowest_grade
end
##
## Sets the lowestGrade property value. Lowest grade taught.
## @param value Value to set for the lowestGrade property.
## @return a void
##
def lowest_grade=(value)
@lowest_grade = value
end
##
## Gets the phone property value. Phone number of school.
## @return a string
##
def phone
return @phone
end
##
## Sets the phone property value. Phone number of school.
## @param value Value to set for the phone property.
## @return a void
##
def phone=(value)
@phone = value
end
##
## Gets the principalEmail property value. Email address of the principal.
## @return a string
##
def principal_email
return @principal_email
end
##
## Sets the principalEmail property value. Email address of the principal.
## @param value Value to set for the principalEmail property.
## @return a void
##
def principal_email=(value)
@principal_email = value
end
##
## Gets the principalName property value. Name of the principal.
## @return a string
##
def principal_name
return @principal_name
end
##
## Sets the principalName property value. Name of the principal.
## @param value Value to set for the principalName property.
## @return a void
##
def principal_name=(value)
@principal_name = value
end
##
## Gets the schoolNumber property value. School Number.
## @return a string
##
def school_number
return @school_number
end
##
## Sets the schoolNumber property value. School Number.
## @param value Value to set for the schoolNumber property.
## @return a void
##
def school_number=(value)
@school_number = value
end
##
## Serializes information the current object
## @param writer Serialization writer to use to serialize this model
## @return a void
##
def serialize(writer)
raise StandardError, 'writer cannot be null' if writer.nil?
super
writer.write_object_value("address", @address)
writer.write_object_value("administrativeUnit", @administrative_unit)
writer.write_collection_of_object_values("classes", @classes)
writer.write_object_value("createdBy", @created_by)
writer.write_string_value("externalId", @external_id)
writer.write_string_value("externalPrincipalId", @external_principal_id)
writer.write_string_value("fax", @fax)
writer.write_string_value("highestGrade", @highest_grade)
writer.write_string_value("lowestGrade", @lowest_grade)
writer.write_string_value("phone", @phone)
writer.write_string_value("principalEmail", @principal_email)
writer.write_string_value("principalName", @principal_name)
writer.write_string_value("schoolNumber", @school_number)
writer.write_collection_of_object_values("users", @users)
end
##
## Gets the users property value. Users in the school. Nullable.
## @return a education_user
##
def users
return @users
end
##
## Sets the users property value. Users in the school. Nullable.
## @param value Value to set for the users property.
## @return a void
##
def users=(value)
@users = value
end
end
end
end
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import React, { useState, useEffect } from 'react';
import './App.css';
import { Title } from '../components/Title';
import { Footer } from '../components/Footer';
import { Filter } from '../components/Filter';
import { Card } from '../components/Card';
import { fetchPrograms } from '../api';
import Loader from 'react-loader-spinner';
export const App = React.memo(({ launchPrograms }) => {
const [programs, setPrograms] = useState(launchPrograms);
const [filterState, setFilterState] = useState({ launch_success: "", land_success: "", launch_year: "" });
const [loading, setLoading] = useState(false);
async function fetchData() {
const url = `https://api.spaceXdata.com/v3/launches?limit=100&launch_success=${filterState.launch_success}&land_success=${filterState.land_success}&launch_year=${filterState.launch_year}`;
const launches = await fetchPrograms(url);
setPrograms(launches);
setLoading(prev => !prev);
window.scroll(0,0);
}
useEffect(() => {
setLoading(prev => !prev);
fetchData();
return () => console.log('unmounting...');
}, [filterState])
return (
<div className="app-container">
<Title />
<div className="content-container">
<div className="filter-container">
<Filter setFilterState={setFilterState} />
</div>
<div className="cards-container">
{loading ? <LoadingIndicator /> : programs.map((program, index) => (<Card key={index} data={program} />))}
</div>
</div>
<Footer />
</div>
)
})
export const LoadingIndicator = React.memo(() => {
return (<div
style={{
width: "100%",
height: "100",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<Loader type="ThreeDots" color="#2BAD60" height="100" w
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
javascript
| 2 |
import React, { useState, useEffect } from 'react';
import './App.css';
import { Title } from '../components/Title';
import { Footer } from '../components/Footer';
import { Filter } from '../components/Filter';
import { Card } from '../components/Card';
import { fetchPrograms } from '../api';
import Loader from 'react-loader-spinner';
export const App = React.memo(({ launchPrograms }) => {
const [programs, setPrograms] = useState(launchPrograms);
const [filterState, setFilterState] = useState({ launch_success: "", land_success: "", launch_year: "" });
const [loading, setLoading] = useState(false);
async function fetchData() {
const url = `https://api.spaceXdata.com/v3/launches?limit=100&launch_success=${filterState.launch_success}&land_success=${filterState.land_success}&launch_year=${filterState.launch_year}`;
const launches = await fetchPrograms(url);
setPrograms(launches);
setLoading(prev => !prev);
window.scroll(0,0);
}
useEffect(() => {
setLoading(prev => !prev);
fetchData();
return () => console.log('unmounting...');
}, [filterState])
return (
<div className="app-container">
<Title />
<div className="content-container">
<div className="filter-container">
<Filter setFilterState={setFilterState} />
</div>
<div className="cards-container">
{loading ? <LoadingIndicator /> : programs.map((program, index) => (<Card key={index} data={program} />))}
</div>
</div>
<Footer />
</div>
)
})
export const LoadingIndicator = React.memo(() => {
return (<div
style={{
width: "100%",
height: "100",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<Loader type="ThreeDots" color="#2BAD60" height="100" width="100" />
</div>)
})
|
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.dferreira.numbers_teach.scores
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import androidx.fragment.app.Fragment
import com.dferreira.numbers_teach.R
import com.dferreira.numbers_teach.generic.ui.ILanguageActivity
/**
* Show a list of possible activities that the user could take to learn the numbers in the
* chosen language
*/
class GlobalScoresListFragment : Fragment() {
private lateinit var listOfScores: ListView
/**
* Create of inflate the Fragment's UI, and return it.
*
* @param inflater Responsible for inflating the view
* @param container container where the fragment is going to be included
* @param savedInstanceState bundle with data that was saved in on save instance if any
* @return view of fragment of the list of activities available to the user
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.global_scores_list_fragment, container, false)
}
/**
* @param savedInstanceState bundle with data that was saved in on save instance if any
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindViews(view)
setEvents()
}
/**
* Bind the the views to the respective variables
*/
private fun bindViews(view: View) {
listOfScores = view.findViewById<View>(R.id.list_of_scores) as ListView
}
/**
* Set the the on click listener to be the fragment
*/
private fun setEvents() {
val currentActivity = requireActivity()
val language = language()
val globalScoresListAdapter = GlobalScoresListAdapter(currentActivity,
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.dferreira.numbers_teach.scores
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import androidx.fragment.app.Fragment
import com.dferreira.numbers_teach.R
import com.dferreira.numbers_teach.generic.ui.ILanguageActivity
/**
* Show a list of possible activities that the user could take to learn the numbers in the
* chosen language
*/
class GlobalScoresListFragment : Fragment() {
private lateinit var listOfScores: ListView
/**
* Create of inflate the Fragment's UI, and return it.
*
* @param inflater Responsible for inflating the view
* @param container container where the fragment is going to be included
* @param savedInstanceState bundle with data that was saved in on save instance if any
* @return view of fragment of the list of activities available to the user
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.global_scores_list_fragment, container, false)
}
/**
* @param savedInstanceState bundle with data that was saved in on save instance if any
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindViews(view)
setEvents()
}
/**
* Bind the the views to the respective variables
*/
private fun bindViews(view: View) {
listOfScores = view.findViewById<View>(R.id.list_of_scores) as ListView
}
/**
* Set the the on click listener to be the fragment
*/
private fun setEvents() {
val currentActivity = requireActivity()
val language = language()
val globalScoresListAdapter = GlobalScoresListAdapter(currentActivity, language)
listOfScores.adapter = globalScoresListAdapter
listOfScores.onItemClickListener = globalScoresListAdapter
}
/**
* @return The language that the user selected to learn
*/
private fun language(): String {
return (activity as ILanguageActivity?)!!.languagePrefix()
}
}
|
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 { Component } from '@angular/core';
@Component({
selector: 'agl-maui-showcase-button',
templateUrl: './showcaseButton.component.html',
styleUrls: ['./showcaseButton.component.scss'],
})
export class ShowcaseButtonComponent {
public codeUsage: string = `
<!-- Default Button (Large Primary) -->
<agl-maui-button (clicked)="doSomethingInParentComponent()">
Primary Button
</agl-maui-button>
<!-- Small Secondary Button -->
<agl-maui-button (clicked)="doSomethingInParentComponent()"
type="secondary"
size="small">
Small Secondary Button
</agl-maui-button>
<!-- Button with Disabled state -->
<!-- Typically used with T&C checkbox -->
<agl-maui-button
[disabled]="!isChecked"
(clicked)="doSomethingInParentComponent()">
Inactive
</agl-maui-button>
<!-- Button with Loading state -->
<!-- Typically used when waiting for a response back from an api -->
<agl-maui-button
[loading]="!isLoading"
(clicked)="doSomethingInParentComponent()">
Inactive
</agl-maui-button>
<!-- Link -->
<agl-maui-button
type="link"
[loading]="!isLoading"
(clicked)="doSomethingInParentComponent()">
Link
</agl-maui-button>
`;
public showDisabledState: boolean;
public showLoadingState: boolean;
public isLoadingPrimaryLarge: boolean;
public isLoadingPrimarySmall: boolean;
public isLoadingSecondaryLarge: boolean;
public isLoadingSecondarySmall: boolean;
public isLoadingTertiaryLarge: boolean;
public isLoadingTertiarySmall: boolean;
public isLoadingLink: boolean;
private timeOut: any;
public toggleCheckBox() {
this.showDisabledState = !this.showDisabledState;
}
public toggleLoadingButtons() {
this.showLoadingState = !this.showLoadingState;
}
public submitButton(type: string) {
console.log('parent detected child clicked'
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 { Component } from '@angular/core';
@Component({
selector: 'agl-maui-showcase-button',
templateUrl: './showcaseButton.component.html',
styleUrls: ['./showcaseButton.component.scss'],
})
export class ShowcaseButtonComponent {
public codeUsage: string = `
<!-- Default Button (Large Primary) -->
<agl-maui-button (clicked)="doSomethingInParentComponent()">
Primary Button
</agl-maui-button>
<!-- Small Secondary Button -->
<agl-maui-button (clicked)="doSomethingInParentComponent()"
type="secondary"
size="small">
Small Secondary Button
</agl-maui-button>
<!-- Button with Disabled state -->
<!-- Typically used with T&C checkbox -->
<agl-maui-button
[disabled]="!isChecked"
(clicked)="doSomethingInParentComponent()">
Inactive
</agl-maui-button>
<!-- Button with Loading state -->
<!-- Typically used when waiting for a response back from an api -->
<agl-maui-button
[loading]="!isLoading"
(clicked)="doSomethingInParentComponent()">
Inactive
</agl-maui-button>
<!-- Link -->
<agl-maui-button
type="link"
[loading]="!isLoading"
(clicked)="doSomethingInParentComponent()">
Link
</agl-maui-button>
`;
public showDisabledState: boolean;
public showLoadingState: boolean;
public isLoadingPrimaryLarge: boolean;
public isLoadingPrimarySmall: boolean;
public isLoadingSecondaryLarge: boolean;
public isLoadingSecondarySmall: boolean;
public isLoadingTertiaryLarge: boolean;
public isLoadingTertiarySmall: boolean;
public isLoadingLink: boolean;
private timeOut: any;
public toggleCheckBox() {
this.showDisabledState = !this.showDisabledState;
}
public toggleLoadingButtons() {
this.showLoadingState = !this.showLoadingState;
}
public submitButton(type: string) {
console.log('parent detected child clicked');
if (this.showLoadingState) {
this.isLoadingPrimaryLarge = (type === 'primaryLarge');
this.isLoadingPrimarySmall = (type === 'primarySmall');
this.isLoadingSecondaryLarge = (type === 'secondaryLarge');
this.isLoadingSecondarySmall = (type === 'secondarySmall');
this.isLoadingTertiaryLarge = (type === 'tertiaryLarge');
this.isLoadingTertiarySmall = (type === 'tertiarySmall');
this.isLoadingLink = (type === 'link');
this.mockWaitingTime();
}
}
private mockWaitingTime() {
clearTimeout(this.timeOut);
this.timeOut = setTimeout(() => {
this.isLoadingPrimaryLarge = false;
this.isLoadingPrimarySmall = false;
this.isLoadingSecondaryLarge = false;
this.isLoadingSecondarySmall = false;
this.isLoadingTertiaryLarge = false;
this.isLoadingTertiarySmall = false;
this.isLoadingLink = false;
}, 3000);
}
}
|
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:
/*BSD 3-Clause License
Copyright (c) 2020, Blockception Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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 HOLDER 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.*/
import { GetProjectData, ProjectData } from "../code/ProjectData";
import { Database } from "../database/include";
import { Manager } from "../manager/Manager";
import { ProcessBehaviourPack } from "../types/minecraft/behavior/Process";
import { ProcessResourcePack } from "../types/minecraft/resource/Process";
export function Traverse(): void {
Manager.State.TraversingProject = true;
Manager.State.DataGathered = false;
Database.MinecraftProgramData.GetProjecDa
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 |
/*BSD 3-Clause License
Copyright (c) 2020, Blockception Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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 HOLDER 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.*/
import { GetProjectData, ProjectData } from "../code/ProjectData";
import { Database } from "../database/include";
import { Manager } from "../manager/Manager";
import { ProcessBehaviourPack } from "../types/minecraft/behavior/Process";
import { ProcessResourcePack } from "../types/minecraft/resource/Process";
export function Traverse(): void {
Manager.State.TraversingProject = true;
Manager.State.DataGathered = false;
Database.MinecraftProgramData.GetProjecData(TraverseProject);
}
export function TraverseProject(Project: ProjectData | undefined): void {
if (!Project) return;
Project.BehaviourPackFolders.forEach(ProcessBehaviourPack);
Project.ResourcePackFolders.forEach(ProcessResourcePack);
Manager.State.TraversingProject = false;
Manager.State.DataGathered = true;
}
|
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 Genre
INSERT INTO Artist (ArtistName, YearEstablished) VALUES ('Cohort37', '2020');
SELECT * From Album
INSERT INTO Album (AlbumLength, ArtistId, Label, ReleaseDate, Title) VALUES (2020, 29, 'NSS', '11/01/2019', 'AlbumFunTime')
INSERT INTO Song (Title, SongLength, ReleaseDate, GenreId, ArtistId, AlbumId) VALUES ('SQL', 10000, '03/18/2020', 9, 29, 24)
INSERT INTO Song (Title, SongLength, ReleaseDate, GenreId, ArtistId, AlbumId) VALUES ('SQL2', 10000, '03/18/2020', 9, 29, 24)
SELECT * From Song
SELECT s.title, al.title from song s
Left Join Album al on al.id = s.AlbumId
Left Join Artist ar on s.ArtistId = ar.id
WHERE al.title = 'AlbumFunTime'
SELECT al.title, COUNT(s.id) as NumberofSongs from Album al
left join Song s on s.AlbumId = al.Id
group by al.Title
SELECT ar.ArtistName, COUNT(s.id) as NumberofSongs from Artist ar
left join Song s on s.ArtistId = ar.Id
group by ar.ArtistName
SELECT ge.Label, COUNT(s.id) as NumberofSongs from Genre ge
left join Song s on s.GenreId = ge.Id
group by ge.Label
select title, AlbumLength from Album where AlbumLength = (select max(AlbumLength) from Album);
select s.title, SongLength, al.Title from Song s
left join Album al on s.AlbumId = al.Id
where SongLength = (select max(SongLength) from Song)
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
| 5 |
--SELECT * FROM Genre
INSERT INTO Artist (ArtistName, YearEstablished) VALUES ('Cohort37', '2020');
SELECT * From Album
INSERT INTO Album (AlbumLength, ArtistId, Label, ReleaseDate, Title) VALUES (2020, 29, 'NSS', '11/01/2019', 'AlbumFunTime')
INSERT INTO Song (Title, SongLength, ReleaseDate, GenreId, ArtistId, AlbumId) VALUES ('SQL', 10000, '03/18/2020', 9, 29, 24)
INSERT INTO Song (Title, SongLength, ReleaseDate, GenreId, ArtistId, AlbumId) VALUES ('SQL2', 10000, '03/18/2020', 9, 29, 24)
SELECT * From Song
SELECT s.title, al.title from song s
Left Join Album al on al.id = s.AlbumId
Left Join Artist ar on s.ArtistId = ar.id
WHERE al.title = 'AlbumFunTime'
SELECT al.title, COUNT(s.id) as NumberofSongs from Album al
left join Song s on s.AlbumId = al.Id
group by al.Title
SELECT ar.ArtistName, COUNT(s.id) as NumberofSongs from Artist ar
left join Song s on s.ArtistId = ar.Id
group by ar.ArtistName
SELECT ge.Label, COUNT(s.id) as NumberofSongs from Genre ge
left join Song s on s.GenreId = ge.Id
group by ge.Label
select title, AlbumLength from Album where AlbumLength = (select max(AlbumLength) from Album);
select s.title, SongLength, al.Title from Song s
left join Album al on s.AlbumId = al.Id
where SongLength = (select max(SongLength) from Song)
|
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 xml_parser;
import java.sql.*;
import xml_parser.Address;
public class database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Address";
static final String USER = "root";
static final String PASS = "";
public void store(String lines, String city, String state, String postalCode, String countryCode)
{
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
//sql = "INSERT into postal"+ "Values(""+) ";
stmt.executeUpdate("INSERT INTO POSTAL (city,state,postalcode,countrycode,street) VALUES ('"+city+"','"+state+"','"+postalCode+"','"+countryCode+"','"+lines+"')");
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
public String search(String lines, String city, String state, String postalCode, String countryCode)
{
Connection conn = null;
Statement stmt = null;
String k="";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
//sql = "INSERT into postal"+ "Values(""+) ";
String q="Select * from postal where
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package xml_parser;
import java.sql.*;
import xml_parser.Address;
public class database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Address";
static final String USER = "root";
static final String PASS = "";
public void store(String lines, String city, String state, String postalCode, String countryCode)
{
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
//sql = "INSERT into postal"+ "Values(""+) ";
stmt.executeUpdate("INSERT INTO POSTAL (city,state,postalcode,countrycode,street) VALUES ('"+city+"','"+state+"','"+postalCode+"','"+countryCode+"','"+lines+"')");
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
public String search(String lines, String city, String state, String postalCode, String countryCode)
{
Connection conn = null;
Statement stmt = null;
String k="";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
//sql = "INSERT into postal"+ "Values(""+) ";
String q="Select * from postal where city='"+city+"' and state='"+state+"'and postalcode='"+postalCode+"'and countrycode='"+countryCode+"'and street='"+lines+"'";
ResultSet rs=stmt.executeQuery(q);
//stmt.executeUpdate("INSERT INTO POSTAL (city,state,postalcode,countrycode,street) VALUES ('"+city+"','"+state+"','"+postalCode+"','"+countryCode+"','"+lines+"')");
if(rs.next())
{
do{
k=rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5);
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5));
}while(rs.next());
}
else
{
return null;
}
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return k;
}
}
|
Below is an extract from a Ruby program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Ruby code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Ruby concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., metaprogramming, blocks). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Ruby. It should be similar to a school exercise, a tutorial, or a Ruby course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Ruby. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
require 'spec_integration_helper'
RSpec.describe "UdSync/Operations", type: :request do
describe "GET /ud_sync/operations" do
context 'no user scope' do
it "signs the user in" do
user = User.create(
name: 'alex'
)
UdSync::Operation.create(
name: 'save',
record_id: 'record_id',
external_id: 'external_id',
entity_name: 'Post'
)
get "/ud_sync/operations", nil
expect(response.code).to eq('200')
expect(json_response).to eq({
'operations' => [{
'id' => '1',
'name' => 'save',
'record_id' => user.id.to_s,
'entity' => 'User',
'date' => UdSync::Operation.first.created_at.iso8601,
}, {
'id' => '2',
'name' => 'save',
'record_id' => 'external_id',
'entity' => 'Post',
'date' => UdSync::Operation.last.created_at.iso8601,
}]
})
end
end
context 'with user scope' do
let(:current_user) { double(User, id: 2) }
before do
UdSync::Operation.create(
name: 'save',
record_id: 'record-1',
external_id: 'external-1',
entity_name: 'Post',
owner_id: 1
)
UdSync::Operation.create(
name: 'save',
record_id: 'record-2',
external_id: 'external-2',
entity_name: 'Post',
owner_id: 2
)
end
context 'there is a logged in user' do
before do
allow_any_instance_of(ApplicationController)
.to receive(:current_user)
.and_return(current_user)
end
it "signs the user in" do
get "/ud_sync/operations", nil
expect(response.code).to eq('200')
expect(json_response).to eq({
'operations' => [{
'id' => '2',
'name' => 'save',
'record_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>"
|
ruby
| 1 |
require 'spec_integration_helper'
RSpec.describe "UdSync/Operations", type: :request do
describe "GET /ud_sync/operations" do
context 'no user scope' do
it "signs the user in" do
user = User.create(
name: 'alex'
)
UdSync::Operation.create(
name: 'save',
record_id: 'record_id',
external_id: 'external_id',
entity_name: 'Post'
)
get "/ud_sync/operations", nil
expect(response.code).to eq('200')
expect(json_response).to eq({
'operations' => [{
'id' => '1',
'name' => 'save',
'record_id' => user.id.to_s,
'entity' => 'User',
'date' => UdSync::Operation.first.created_at.iso8601,
}, {
'id' => '2',
'name' => 'save',
'record_id' => 'external_id',
'entity' => 'Post',
'date' => UdSync::Operation.last.created_at.iso8601,
}]
})
end
end
context 'with user scope' do
let(:current_user) { double(User, id: 2) }
before do
UdSync::Operation.create(
name: 'save',
record_id: 'record-1',
external_id: 'external-1',
entity_name: 'Post',
owner_id: 1
)
UdSync::Operation.create(
name: 'save',
record_id: 'record-2',
external_id: 'external-2',
entity_name: 'Post',
owner_id: 2
)
end
context 'there is a logged in user' do
before do
allow_any_instance_of(ApplicationController)
.to receive(:current_user)
.and_return(current_user)
end
it "signs the user in" do
get "/ud_sync/operations", nil
expect(response.code).to eq('200')
expect(json_response).to eq({
'operations' => [{
'id' => '2',
'name' => 'save',
'record_id' => 'external-2',
'entity' => 'Post',
'date' => UdSync::Operation.last.created_at.iso8601,
}]
})
end
end
context 'there is NO logged in user' do
before do
allow_any_instance_of(ApplicationController)
.to receive(:current_user)
.and_return(nil)
end
it "signs the user in" do
get "/ud_sync/operations", nil
expect(response.code).to eq('401')
end
end
end
end
describe "GET /ud_sync/operations?since=2016-01-01T10:10:10Z" do
context 'no user scope' do
it "signs the user in" do
UdSync::Operation.create(
name: 'save',
record_id: 'record-1',
external_id: 'external-1',
entity_name: 'Post',
created_at: DateTime.new(2015, 02, 02, 02, 02, 02).utc
)
newer = UdSync::Operation.create(
name: 'save',
record_id: 'record-2',
external_id: 'external-2',
entity_name: 'Post',
created_at: DateTime.new(2016, 02, 02, 02, 02, 02).utc
)
UdSync::Operation.create(
name: 'save',
record_id: 'record-3',
external_id: 'external-3',
entity_name: 'Post',
created_at: DateTime.new(2015, 12, 30, 23, 59, 59).utc
)
get "/ud_sync/operations?since=2016-01-01T10:10:10Z", nil
expect(response.code).to eq('200')
expect(json_response).to eq({
'operations' => [{
'id' => newer.id.to_s,
'name' => 'save',
'record_id' => 'external-2',
'entity' => 'Post',
'date' => '2016-02-02T02:02:02Z',
}]
})
end
end
end
end
|
Below is an extract from a Rust program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Rust code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Rust concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., ownership, lifetimes). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Rust. It should be similar to a school exercise, a tutorial, or a Rust course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Rust. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
#![feature(lang_items)]
#![feature(core_intrinsics)]
#![feature(const_fn)]
#![feature(asm)]
#![feature(optin_builtin_traits)]
#![feature(decl_macro)]
#![feature(repr_align)]
#![feature(attr_literals)]
#![feature(exclusive_range_pattern)]
#![feature(i128_type)]
#![feature(never_type)]
#![feature(unique)]
#![feature(pointer_methods)]
#![feature(naked_functions)]
#![feature(fn_must_use)]
#![feature(alloc, allocator_api, global_allocator)]
#[macro_use]
#[allow(unused_imports)]
extern crate alloc;
extern crate pi;
extern crate stack_vec;
extern crate fat32;
pub mod allocator;
pub mod lang_items;
pub mod mutex;
pub mod console;
pub mod shell;
pub mod fs;
pub mod traps;
pub mod aarch64;
pub mod process;
pub mod vm;
use pi::gpio::Gpio;
use pi::timer::spin_sleep_ms;
#[cfg(not(test))]
use allocator::Allocator;
use fs::FileSystem;
use process::GlobalScheduler;
use process::sys_sleep;
#[cfg(not(test))]
#[global_allocator]
pub static ALLOCATOR: Allocator = Allocator::uninitialized();
pub static FILE_SYSTEM: FileSystem = FileSystem::uninitialized();
pub static SCHEDULER: GlobalScheduler = GlobalScheduler::uninitialized();
#[no_mangle]
#[cfg(not(test))]
pub extern "C" fn kmain() {
let mut loading_leds = [
Gpio::new(5).into_output(),
Gpio::new(6).into_output(),
Gpio::new(13).into_output(),
Gpio::new(19).into_output(),
Gpio::new(26).into_output()];
for ref mut led in loading_leds.iter_mut() {
led.set();
spin_sleep_ms(100);
}
spin_sleep_ms(2000);
for ref mut led in loading_leds.iter_mut() {
led.clear();
spin_sleep_ms(100);
}
ALLOCATOR.initialize();
FILE_SYSTEM.initialize();
SCHEDULER.start();
}
pub extern fn run_shell() {
loop { shell::shell("user0> "); }
}
pub extern fn run_blinky() {
let mut ready_led = Gpio::new(16).into_output();
loop {
ready_led.set();
sys_sleep(500);
ready_led.clear();
sys_sleep(500);
}
}
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 |
#![feature(lang_items)]
#![feature(core_intrinsics)]
#![feature(const_fn)]
#![feature(asm)]
#![feature(optin_builtin_traits)]
#![feature(decl_macro)]
#![feature(repr_align)]
#![feature(attr_literals)]
#![feature(exclusive_range_pattern)]
#![feature(i128_type)]
#![feature(never_type)]
#![feature(unique)]
#![feature(pointer_methods)]
#![feature(naked_functions)]
#![feature(fn_must_use)]
#![feature(alloc, allocator_api, global_allocator)]
#[macro_use]
#[allow(unused_imports)]
extern crate alloc;
extern crate pi;
extern crate stack_vec;
extern crate fat32;
pub mod allocator;
pub mod lang_items;
pub mod mutex;
pub mod console;
pub mod shell;
pub mod fs;
pub mod traps;
pub mod aarch64;
pub mod process;
pub mod vm;
use pi::gpio::Gpio;
use pi::timer::spin_sleep_ms;
#[cfg(not(test))]
use allocator::Allocator;
use fs::FileSystem;
use process::GlobalScheduler;
use process::sys_sleep;
#[cfg(not(test))]
#[global_allocator]
pub static ALLOCATOR: Allocator = Allocator::uninitialized();
pub static FILE_SYSTEM: FileSystem = FileSystem::uninitialized();
pub static SCHEDULER: GlobalScheduler = GlobalScheduler::uninitialized();
#[no_mangle]
#[cfg(not(test))]
pub extern "C" fn kmain() {
let mut loading_leds = [
Gpio::new(5).into_output(),
Gpio::new(6).into_output(),
Gpio::new(13).into_output(),
Gpio::new(19).into_output(),
Gpio::new(26).into_output()];
for ref mut led in loading_leds.iter_mut() {
led.set();
spin_sleep_ms(100);
}
spin_sleep_ms(2000);
for ref mut led in loading_leds.iter_mut() {
led.clear();
spin_sleep_ms(100);
}
ALLOCATOR.initialize();
FILE_SYSTEM.initialize();
SCHEDULER.start();
}
pub extern fn run_shell() {
loop { shell::shell("user0> "); }
}
pub extern fn run_blinky() {
let mut ready_led = Gpio::new(16).into_output();
loop {
ready_led.set();
sys_sleep(500);
ready_led.clear();
sys_sleep(500);
}
}
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Affordable Plumbing Service ElCajon CA</title>
<meta name="description" content="Plumbing Contractors ElCajon California - We offer full transparency with our Calgary drain cleaning services so you always know what you will get.">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY> crossorigin="anonymous" />
</head>
<main>
<header id="navbar">
<div class="container">
<div class="flexbox flexRow alignItemCenter">
<div class="logobar">
<a href="index.html">Plumbing Services</a>
</div>
<div class="flexbox alignItemCenter alignItemEnd rightPhone">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
<span>24 Hour Emergency and Same Day Service!</span>
</div>
</div>
</div>
</header>
<section class="main-hero">
<div class="container">
<div class="hero">
<div class="left-img">
<img src="images/1.jpg" alt="">
</div>
<div class="right-text">
<div class="inner-right-text">
<p><strong>Need A Plumber?</strong></p>
<span>We are just a call away!</span>
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>Request Quote</a>
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div id="tab1" class="opTabContent">
<div class="tab-wrapper">
<div
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Affordable Plumbing Service ElCajon CA</title>
<meta name="description" content="Plumbing Contractors ElCajon California - We offer full transparency with our Calgary drain cleaning services so you always know what you will get.">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY> crossorigin="anonymous" />
</head>
<main>
<header id="navbar">
<div class="container">
<div class="flexbox flexRow alignItemCenter">
<div class="logobar">
<a href="index.html">Plumbing Services</a>
</div>
<div class="flexbox alignItemCenter alignItemEnd rightPhone">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
<span>24 Hour Emergency and Same Day Service!</span>
</div>
</div>
</div>
</header>
<section class="main-hero">
<div class="container">
<div class="hero">
<div class="left-img">
<img src="images/1.jpg" alt="">
</div>
<div class="right-text">
<div class="inner-right-text">
<p><strong>Need A Plumber?</strong></p>
<span>We are just a call away!</span>
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>Request Quote</a>
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div id="tab1" class="opTabContent">
<div class="tab-wrapper">
<div class="accordion-wrapper">
<div class="panel">
<a href="./index.html">Home</a><br><center><h1>Affordable Plumbing Service in ElCajon CA</h1></center>
<p style="font-size:18px">Plumbing problems always seem to pop up at the wrong time, don't they? If you need emergency plumbing repairs in ElCajon or the surrounding area, do not hesitate to give us a call.</p>
<p style="text-align: center;"><span style="color: #ff0000; font-size: 22px;">For plumbing problems big or small, we have the experience to handle it.</span></p>
<h2 style="text-align: center;"><span style="color: ##ffffff;">Some of the services we provide in ElCajon and surrounding areas</span></h2>
<p><img src="https://plumbingimages.s3-us-west-1.amazonaws.com/plumber1.jpg" alt="emergency plumber near ElCajon"><p>
<h2 style="text-align: center;"><span style="color: ##ffffff;">Why Choose Us?</span></h2>
<ul>
<li style="text-align: left; font-size: 18px;"><span style="color: #000000;">Providing 24 hour emergency plumbing service. 7 days a week.</li>
<p>
<li style="text-align: left; font-size: 18px;"><span style="color: #000000;">Our technicians are the best in the ElCajon market.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Professional services you can count on.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Committed to service that is thorough, timely, and honest.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Trusted by homeowners like you.</li>
<p>
<li style="text-align: left; font-size: 18px"><span style="color: #000000;">Customer satisfaction guaranteed.</li>
</ul>
<p style="text-align: center; font-size: 26px;"><strong><span style="color: #3366ff;">Call now to discuss your needs and get the process started</span></strong></p>
<center><div class="inner-right-text">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
</div></center>
<h2>Tips To Hire Professional Plumbing Contractors in ElCajon</h2>
<p><img src="https://plumbingimages.s3-us-west-1.amazonaws.com/plumbing.jpg" alt=""><p>
<p>We focus on tub and shower replacement and full bathroom redesigning at really competitive pricing. You can relax and use your gas piping without any concern when we handle your gas or gas pipe installation and gas pipe repair. While water overuse is an issue for your wallet, it's also an issue for the environment. Old-fashioned water softening systems that aren't saltless can use up to 25 gallons of water every day for their regeneration process. That's 700 gallons of water a month simply to keep your water softener up and running.</p>
<p>Foul smells originating from your sink or from your bathtub. Like sewage smells, nasty smells are an indicator that you are experiencing a plumbing problem. There might be obstructing in your pipe system or the trap on your drain may be broken or excessively dry. We provide energy efficient water heater solutions satisfying the NAECA efficiency standards. If you have an old water heater, you may think about upgrading to one of these energy efficient hot water heater that uses a cost savings on your utility costs, and quicker healing times.</p>
<h3>Shower Plumbing in ElCajon California</h2>
<p>Take a close look at the galvanized pipes on the right. After only a few years the inside of the pipe will start state to rust This dirty and abrasive sediment will wind up being transferred throughout your homes entire plumbing system. If you are not sure about what options are offered to you when selecting a new sink installation, or you are not familiar with the terms that obtain sinks, you may need to evaluate our list listed below. Design and style of your kitchen will usually figure out the selections which work well.</p>
<p>It's important to have access to reliable boiler repair service and boiler replacement when you need them. Boilers typically last for many years, however that doesn't mean there won't be issues from time to time. Since we offer high-quality repair and installation and extraordinary consumer service, you can trust Air Pros U.S.A. for all of your boiler services.</p>
<p>Time for a various waste disposal unit in Dallas? Look for no further than Levy & Child Service Professionals. Enbin, Liu, <NAME>, <NAME>, and <NAME>. "Detection Innovation for Pipeline Plugging Based on Barotropic Wave Method." Gas Market 26, no. 4 (2006 ): 112. The presence of excess iron or hydrogen sulfide can inhibit the efficiency of a water-softening system. Installation of the iron-removal devices may be needed (see the NDSU publication Iron and Manganese" (AE1030) Water test outcomes will help make that determination.</p>
<p style="text-align: center; font-size: 26px;"><strong><span style="color: #3366ff;">Emergency? Calls are answered 24/7</span></strong></p>
<center><div class="inner-right-text">
<a href="tel:844-407-5312"> <i class="fa fa-phone"></i>(844) 407-5312</a>
</div></center>
<h3>Everything You Ever Wanted To Know About Plumbers ElCajon CA</h3>
<p>Root Intrusion: Root intrusion describes what occurs when tree roots begin to grow around and into your drain and sewer lines This occurs because the wetness in these lines is a natural fertilizer for tree roots. When roots ultimately do piece your drain lines, they can trigger clogs, breaks, and back-ups which might result in extensive property damage. Keep an eye out for damp, green patches in your lawn, a persistent sewage smell in or around your house, an uptick in rodent and insect activity, and slow drains, as these are all typical indications of root intrusion.</p>
<p>Hydro jetting is a process in which the sewer pipes are scrubbed clean by streams of high-pressure water shooting from a hose at as much as 3,500 PSI. This enables the sewer lines to be cleaned rapidly and effectively with high-velocity water pressure. The streams of high-pressure water, emitting from the forward and reverse jets in the nozzle, propel the hose through the line to eliminate debris such as tough water scale, sand, grease, and silt deposits.</p>
<p><strong>We offer the following services in ElCajon:</strong><p>
<ul>
<li>Emergency Plumbing Services in ElCajon, CA</li>
<li>Trenchless Sewer Line Services in ElCajon, CA</li>
<li>Repiping Services in ElCajon, CA</li>
<li>Water Softeners in ElCajon, CA</li>
<li>Kitchen Plumbing and Garbage Disposals in ElCajon, CA</li>
<li>Water Leak Detection in ElCajon, CA</li>
<li>Slab Leak Repair in ElCajon, CA</li>
<li>Smart Water Leak Detector in ElCajon, CA</li>
<li>Hydrojetting Services in ElCajon, CA</li>
<li>Burst Pipe Repair in ElCajon, CA</li>
<li>Grease Trap Cleaning in ElCajon, CA</li>
<li>Gas Line Repair and Installation in ElCajon, CA</li>
<li>Toilet Repair and Installation in ElCajon, CA</li>
<li>Sewer Video Inspection in ElCajon, CA</li>
<li>Water Heater Repair and Installation in ElCajon, CA</li>
<li>Tankless Water Heaters Repair and Installation in ElCajon, CA</li>
<li>Sump Pump Services in ElCajon, CA</li>
<li>Water Filtration Systems in ElCajon, CA</li>
<li>Drain Cleaning in ElCajon, CA</li>
<li>Sewer Line Services in ElCajon, CA</li>
</ul>
<h3>Fixing A Clogged Toilet at ElCajon CA</h3>
<p>IRWD is committed to providing safe, high quality water to consumers. Our substantial water quality program operates 24 hr a day, 365 days a year, to make sure that the water delivered to our customers is kept devoid of hazardous impurities. A vital part of our water quality program is the backflow prevention program When a water line is connected to equipment containing a nonpotable compound, this is known as a cross-connection. Contamination may take place when water flows through a cross-connection from a nonpotable source, such as a sprinkler system or cooling and heating system, into the safe and clean water system. This can take place through a procedure known as backflow.</p>
<p>Hot water is critical to the needs of your home and household. Without hot water, you will not have the ability to shower easily, cook food correctly or wash your laundry effectively. If your water heater isn't working, our experienced group of professionals at Kramer and Sons is prepared to supply you with top-notch, same-day service.</p>
<p>A brand-new sink can considerably affect the look of a room. For the kitchen, numerous homeowners select the functionality and elegance of a stainless steel sink, which not only looks great however makes cleaning up inconvenience complimentary. For restrooms, a stylish or appealing sink can offer the room a look of elegance some house owners might have not thought possible.</p>
<p>Your company has been really valuable to me for a long time. The boy who came a couple of days earlier was so honest with me. I was prepared to invest a minimum of $500 for a warm water system and he stated it wasn't necessary!!!! He could have installed the system and I 'd never have actually known the distinction. That's a quality business. . Setting up a garbage disposal is a reasonably easy task for a skilled do-it-yourselfer. Get a couple of fundamental tools and follow our how-to.</p>
<p>
<iframe width="100%" height="250" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=ElCajon.CA+()&ie=UTF8&t=&z=14&iwloc=B&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0">
</iframe>
</p>
<br>
<p>
</p>
<br>
<div itemscope itemtype="http://schema.org/Product">
<span itemprop="name">Plumbing Service ElCajon California</span>
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
Rated <span itemprop="ratingValue">4.8</span>/5 based on <span itemprop="reviewCount">388</span> reviews.</div></div>
<br><a href="./Emergency-Plumber-Contractor-Earlimart-CA.html">Previous</a> <a href="./Emergency-Plumber-Companies-ElCerrito-CA.html">Next</a>
<br>Related Posts ElCajon California<br><a href="./Professional-Plumber-Contractors-Benicia-CA.html">Professional Plumber Contractors Benicia CA</a><br><a href="./24-Hour-Plumber-Colusa-CA.html">24 Hour Plumber Colusa CA</a><br><a href="./Affordable-Plumbing-Repairs-Moody-AL.html">Affordable Plumbing Repairs Moody AL</a><br><a href="./Local-Plumber-Near-Me-Bonita-CA.html">Local Plumber Near Me Bonita CA</a><br><a href="./Emergency-Plumber-Companies-ElCerrito-CA.html">Emergency Plumber Companies ElCerrito CA</a><br>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="main-help">
<div class="container">
<div class="need-help">
<p>WE’RE FAST, AFFORDABLE & STANDING BY READY TO HELP 24/7. CALL NOW. <span><i class="fa fa-phone"></i><a href="tel:844-407-5312">(844) 407-5312</span></a>
</p>
</div>
</div>
</div>
<div class="footer-content">
<div class="container">
<ul>
<li><a href="./index.html">Home</a></li>
<li><a href="./disclaimer.html">Disclaimer</a></li>
<li><a href="./privacy.html">Privacy Policy</a></li>
<li><a href="./terms.html">Terms of Service</a></li>
</ul>
<p>© 2020 Plumbing Services - All Rights Reserved</p>
<p>This site is a free service to assist homeowners in connecting with local service contractors. All contractors are independent and this site does not warrant or guarantee any work performed. It is the responsibility of the homeowner to
verify that the hired contractor furnishes the necessary license and insurance required for the work being performed. All persons depicted in a photo or video are actors or models and not contractors listed on this site.</p>
</div>
</div>
</footer>
</main>
<!-- Start -->
<script type="text/javascript">
var sc_project=12340729;
var sc_invisible=1;
var sc_security="be78cc4c";
</script>
<script type="text/javascript"
src="https://www.statcounter.com/counter/counter.js"
async></script>
<noscript><div class="statcounter"><a title="Web Analytics
Made Easy - StatCounter" href="https://statcounter.com/"
target="_blank"><img class="statcounter"
src="https://c.statcounter.com/12340729/0/be78cc4c/1/"
alt="Web Analytics Made Easy -
StatCounter"></a></div></noscript>
<!-- End -->
<div class="tabtocall">
<a href="tel:844-407-5312"><img src="images/baseline_call_white_18dp.png" alt=""> Tap To Call</a>
</div>
<div class="modal fade" id="ouibounce-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" class="close-btn" data-dismiss="modal">X</button>
<div class="modal-body">
<div class="popupWait">
<span class="waitText">Wait!</span>
<p class="para1">Urgent Plumbing Needs? Calls Are Answered 24/7</p>
<p class="para2">Call now to get connected to a plumber near you.</p>
<a href="tel:844-407-5312"><strong><i class="fa fa-phone"></i>(844) 407-5312</strong></a>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/exit-popup.js"></script>
<body>
</body>
</html>
|
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:
# Maintainer: <NAME> <flocke [swirly thing] shadowice [dot] org>
pkgname=perl-poppler-git
pkgver=20110127
pkgrel=1
pkgdesc="perl binding of poppler library"
depends=('perl>=5.10.0' 'glibc' 'poppler' 'cairo-perl')
makedepends=('perl-extutils-pkgconfig' 'git' 'patch')
provides=('perl-poppler')
conflicts=('perl-poppler')
license=('GPL' 'PerlArtistic')
url="http://search.cpan.org/dist/Poppler/"
source=()
md5sums=()
options=('force' '!emptydirs')
arch=(i686 x86_64)
_gitroot=https://github.com/c9s/perl-poppler.git
_gitname=perl-poppler
build()
{
cd "$srcdir"
msg "Connecting to GIT server...."
if [ -d $_gitname ] ; then
cd $_gitname && git pull origin
msg "The local files are updated."
else
git clone $_gitroot $_gitname
fi
msg "GIT checkout done or server timeout"
msg "Starting make..."
rm -rf "$srcdir/$_gitname-build"
git clone "$srcdir/$_gitname" "$srcdir/$_gitname-build"
cd "$srcdir/$_gitname-build"
perl Makefile.PL INSTALLDIRS=vendor || return 1
make || return 1
make DESTDIR=${pkgdir} install || return 1
# Remove .packlist and perllocal.pod files.
find ${pkgdir} -name '.packlist' -delete
find ${pkgdir} -name 'perllocal.pod' -delete
}
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
| 3 |
# Maintainer: <NAME> <flocke [swirly thing] shadowice [dot] org>
pkgname=perl-poppler-git
pkgver=20110127
pkgrel=1
pkgdesc="perl binding of poppler library"
depends=('perl>=5.10.0' 'glibc' 'poppler' 'cairo-perl')
makedepends=('perl-extutils-pkgconfig' 'git' 'patch')
provides=('perl-poppler')
conflicts=('perl-poppler')
license=('GPL' 'PerlArtistic')
url="http://search.cpan.org/dist/Poppler/"
source=()
md5sums=()
options=('force' '!emptydirs')
arch=(i686 x86_64)
_gitroot=https://github.com/c9s/perl-poppler.git
_gitname=perl-poppler
build()
{
cd "$srcdir"
msg "Connecting to GIT server...."
if [ -d $_gitname ] ; then
cd $_gitname && git pull origin
msg "The local files are updated."
else
git clone $_gitroot $_gitname
fi
msg "GIT checkout done or server timeout"
msg "Starting make..."
rm -rf "$srcdir/$_gitname-build"
git clone "$srcdir/$_gitname" "$srcdir/$_gitname-build"
cd "$srcdir/$_gitname-build"
perl Makefile.PL INSTALLDIRS=vendor || return 1
make || return 1
make DESTDIR=${pkgdir} install || return 1
# Remove .packlist and perllocal.pod files.
find ${pkgdir} -name '.packlist' -delete
find ${pkgdir} -name 'perllocal.pod' -delete
}
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System.Windows.Threading;
using Microsoft.Win32;
using System.Windows.Interop;
using System.Windows.Forms;
using System.IO;
namespace Preview
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BackPriviewBtn_Click(object sender, RoutedEventArgs e)
{
// View.Position -=new TimeSpan(00,00,05);
}
private void BackPriviewBtn_MouseDown(object sender, MouseButtonEventArgs e)
{
// View.Position -= new TimeSpan(00, 00, 02);
}
private void PlayPriviewBtn_Click(object sender, RoutedEventArgs e)
{
// View.Play();
Thread t = new Thread(delegate ()
{
RecognizeSpeechAsync().Wait();
});
t.Start();
Thread enter = new Thread(delegate ()
{
// Thread.Sleep(1000);
SendKeys.Send("<ENTER>");
// SendKeys.Send("{ENTER}"); // отправка нажатия
});
axTimeLine.Play();
}
private void PausePriviewBtn_Click(object sender, RoutedEventArgs e)
{
axTimeLine.Pause();
}
private void NextPriviewBtn_Click(object sender, RoutedEventArgs e)
{
}
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>"
|
csharp
| 1 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System.Windows.Threading;
using Microsoft.Win32;
using System.Windows.Interop;
using System.Windows.Forms;
using System.IO;
namespace Preview
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BackPriviewBtn_Click(object sender, RoutedEventArgs e)
{
// View.Position -=new TimeSpan(00,00,05);
}
private void BackPriviewBtn_MouseDown(object sender, MouseButtonEventArgs e)
{
// View.Position -= new TimeSpan(00, 00, 02);
}
private void PlayPriviewBtn_Click(object sender, RoutedEventArgs e)
{
// View.Play();
Thread t = new Thread(delegate ()
{
RecognizeSpeechAsync().Wait();
});
t.Start();
Thread enter = new Thread(delegate ()
{
// Thread.Sleep(1000);
SendKeys.Send("<ENTER>");
// SendKeys.Send("{ENTER}"); // отправка нажатия
});
axTimeLine.Play();
}
private void PausePriviewBtn_Click(object sender, RoutedEventArgs e)
{
axTimeLine.Pause();
}
private void NextPriviewBtn_Click(object sender, RoutedEventArgs e)
{
}
private void MutePriviewBtn_Click(object sender, RoutedEventArgs e)
{
/*
double volum = View.Volume;
bool on_off = true;
if (on_off == false)
{
View.Volume = volum;
on_off = true;
}
else
{
View.Volume = 0;
on_off = false;
}
*/
}
public async Task RecognizeSpeechAsync()
{
// Creates an instance of a speech config with specified subscription key and service region.
// Replace with your own subscription key and service region (e.g., "westus").
var config = SpeechConfig.FromSubscription("c14e2c4bf1ce4c5cb3baae64ffb4556d", "westus");
var stopRecognition = new TaskCompletionSource<int>();
// Creates a speech recognizer using file as audio input.
// Replace with your own audio file name.
using (var audioInput = AudioConfig.FromWavFileInput(@"E:\Marvel Studios Avengers Endgame - Official Trailer.wav"))
{
using (var recognizer = new SpeechRecognizer(config, audioInput))
{
// Subscribes to events.
recognizer.Recognizing += (s, e) =>
{
RecognitionText.Dispatcher.Invoke((Action)(() =>
{
RecognitionText.Text =e.Result.Text;
// EditSub.Text += e.Result.Text;
}));
// RecognitionText.Text += e.Result.Text;
};
recognizer.Recognized += (s, e) =>
{
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
RecognitionText.Dispatcher.Invoke((Action)(() =>
{
RecognitionText.Text = e.Result.Text;
//EditSub.Text += e.Result.Text;
}));
}
else if (e.Result.Reason == ResultReason.NoMatch)
{
RecognitionText.Dispatcher.Invoke((Action)(() =>
{
RecognitionText.Text += " NOMATCH: Speech could not be recognized.";
}));
}
};
recognizer.Canceled += (s, e) =>
{
RecognitionText.Dispatcher.Invoke((Action)(() =>
{
RecognitionText.Text = e.Result.Text;
// EditSub.Text += e.Result.Text;
}));
if (e.Reason == CancellationReason.Error)
{
RecognitionText.Dispatcher.Invoke((Action)(() =>
{
RecognitionText.Text += e.ErrorCode.ToString();
RecognitionText.Text += e.ErrorDetails;
RecognitionText.Text += "CANCELED: Did you update the subscription info?";
}));
}
stopRecognition.TrySetResult(0);
};
recognizer.SessionStarted += (s, e) =>
{
//Sub.Text = "\n Session started event.";
};
recognizer.SessionStopped += (s, e) =>
{
//Sub.Text ="\n Session stopped event.";
//Sub.Text = "\n Stop recognition.";
//Sub.Text = "\n Stop recognition.";
stopRecognition.TrySetResult(0);
};
// Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
// Waits for completion.
// Use Task.WaitAny to keep the task rooted.
Task.WaitAny(new[] { stopRecognition.Task });
// Stops recognition.
await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
Thread.Sleep(70);
}
}
// </recognitionContinuousWithFile>
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
IntPtr helper = new WindowInteropHelper(this).Handle;
axTimeLine.SetPreviewWnd((int)PictureBox.Handle);
}
private void StopPriViewBtn_Click(object sender, RoutedEventArgs e)
{
axTimeLine.Stop();
}
private void Import_Click(object sender, RoutedEventArgs e)
{
float iduration;
int iwidth;
int iheight;
float framerate;
int videobitrate;
int iaudiobitrate;
int iaudiochannel;
int audiosamplerate;
int ivideostreamcount;
int iaudiostreamcouunt;
string strmediacontainer;
string strvideostreamformat;
string straudiostreamformat;
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Filter = "All Files (*.*)|*.*|mpg (*.mpg*.vob) | *.mpg;*.vob|avi (*.avi) | *.avi|Divx (*.divx) | *.divx|wmv (*.wmv)| *.wmv|QuickTime (*.mov)| *.mov|MP4 (*.mp4) | *.mp4|AVCHD (*.m2ts*.ts*.mts*m2t)|*.m2ts;*.ts;*.mts;*.m2t|wav (*.wav)|*.wav|MP3 (*.mp3)|*.mp3|WMA (*.wma)|*.wma||";
if (openFileDialog.ShowDialog() == true)
{
string strFile = openFileDialog.FileName;
axTimeLine.GetMediaInfo(strFile, out iduration, out iwidth, out iheight, out framerate, out videobitrate, out iaudiobitrate, out iaudiochannel, out audiosamplerate, out ivideostreamcount,out iaudiostreamcouunt, out strmediacontainer, out strvideostreamformat, out straudiostreamformat);
axTimeLine.SetVideoTrackResolution(iwidth, iheight);
axTimeLine.AddVideoClip(1, strFile, 0, axTimeLine.GetMediaDuration(strFile), 0);
axTimeLine.AddAudioClip(5, strFile, 0, axTimeLine.GetMediaDuration(strFile), 0,(float)1.0);
}
}
private void Export_Click(object sender, RoutedEventArgs e)
{
ExportOptions export = new ExportOptions(axTimeLine);
export.Show();
}
}
}
|
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:
# stock(python)
--------------------------------------------------------------------------
네이버 주식 (https://finance.naver.com/) - Crawling example
--------------------------------------------------------------------------
- 1. install python library
$ pip install requests beautifulsoup4 apscheduler python-telegram-bot
- 2. seqlite3 install && sqlite location PATH add
- 3. create db schema (stock_db_init.py)
sqlite3 stock.db
* version 1 ~ 3
create table stock_vX_meta (current_amt text);
insert into stock_vX_meta (current_amt) values ('현재자금 ex) 500000');
create table stock_vX (id integer primary key autoincrement, code text, item text, status text
, purchase_current_amt text , sell_current_amt text, purchase_count text
, purchase_amt text , sell_amt text, search_rate text, yesterday_rate text, up_down_rate text
, ps_cnt text, c_amt text, h_amt text, l_amt, crt_dttm text, chg_dttm text);
* version 4 ~ 9
create table stock_vX_x_meta (current_amt text);
insert into stock_vX_x_meta (current_amt) values ('현재자금 ex) 500000');
create table stock_vX_x (id integer primary key autoincrement, code text, item text, status text
, purchase_current_amt text , sell_current_amt text, purchase_count text
, purchase_amt text , sell_amt text, crt_dttm text, chg_dttm text);
- 4. telegram setting
BotFather -> /newbot -> devsunetstock -> devsunsetstock_bot - > get api key
--------------------------------------------------------------------------
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 |
# stock(python)
--------------------------------------------------------------------------
네이버 주식 (https://finance.naver.com/) - Crawling example
--------------------------------------------------------------------------
- 1. install python library
$ pip install requests beautifulsoup4 apscheduler python-telegram-bot
- 2. seqlite3 install && sqlite location PATH add
- 3. create db schema (stock_db_init.py)
sqlite3 stock.db
* version 1 ~ 3
create table stock_vX_meta (current_amt text);
insert into stock_vX_meta (current_amt) values ('현재자금 ex) 500000');
create table stock_vX (id integer primary key autoincrement, code text, item text, status text
, purchase_current_amt text , sell_current_amt text, purchase_count text
, purchase_amt text , sell_amt text, search_rate text, yesterday_rate text, up_down_rate text
, ps_cnt text, c_amt text, h_amt text, l_amt, crt_dttm text, chg_dttm text);
* version 4 ~ 9
create table stock_vX_x_meta (current_amt text);
insert into stock_vX_x_meta (current_amt) values ('현재자금 ex) 500000');
create table stock_vX_x (id integer primary key autoincrement, code text, item text, status text
, purchase_current_amt text , sell_current_amt text, purchase_count text
, purchase_amt text , sell_amt text, crt_dttm text, chg_dttm text);
- 4. telegram setting
BotFather -> /newbot -> devsunetstock -> devsunsetstock_bot - > get api key
--------------------------------------------------------------------------
|
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 DATABASE_H
#define DATABASE_H
#include <QString>
#include <vector>
#include <map>
#include <QDate>
#include "DataBase_global.h"
struct User{
int id = -1;
QString name = "";
};
class DATABASE_EXPORT DataBase
{
public:
static DataBase *get();
std::vector<User> getUsers();
std::map<QDate, std::vector<int>> getUsersSomething(int id) const;
void addSomething(int id, const QDateTime& date, std::vector<int> data);
protected:
DataBase();
static DataBase *m_dataBase;
//TEMP. Before SQL database
std::vector<User> m_users;
std::map<QDate, std::vector<int>> m_calendarLika; //День + вредности
std::map<QDate, std::vector<int>> m_calendarAndrey; //День + вредности
};
#endif // DATABASE_H
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 DATABASE_H
#define DATABASE_H
#include <QString>
#include <vector>
#include <map>
#include <QDate>
#include "DataBase_global.h"
struct User{
int id = -1;
QString name = "";
};
class DATABASE_EXPORT DataBase
{
public:
static DataBase *get();
std::vector<User> getUsers();
std::map<QDate, std::vector<int>> getUsersSomething(int id) const;
void addSomething(int id, const QDateTime& date, std::vector<int> data);
protected:
DataBase();
static DataBase *m_dataBase;
//TEMP. Before SQL database
std::vector<User> m_users;
std::map<QDate, std::vector<int>> m_calendarLika; //День + вредности
std::map<QDate, std::vector<int>> m_calendarAndrey; //День + вредности
};
#endif // DATABASE_H
|
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:
# Mortar
That crap between the bricks
## I depend on Mortar & cant auto-download Mortar without Mortar...
Because plugins depend on MortarPlugin you may have some class loading issues when enabling. To work around this, simply add this anywhere in your main plugin class.
What this does
* Checks if mortar is installed already
* If not, downloads Mortar and force-loads it
Mortar will be enabled before your plugin is enabled.
```java
static {
try {
URL url = new URL("https://raw.githubusercontent.com/VolmitSoftware/Mortar/master/release/Mortar.jar");
File plugins = new File("plugins");
Boolean foundMortar = false;
for (File i : plugins.listFiles()) {
if (i.isFile() && i.getName().endsWith(".jar")) {
ZipFile file = new ZipFile(i);
try {
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if ("plugin.yml".equals(entry.getName())) {
InputStream in = file.getInputStream(entry);
PluginDescriptionFile pdf = new PluginDescriptionFile(in);
if (pdf.getMain().equals("mortar.bukkit.plugin.MortarAPIPlugin")) {
foundMortar = true;
break;
}
}
}
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
file.close();
}
}
}
if (!foundMortar) {
System.out.println("Cannot find mortar. Attempting to download...");
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setC
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 |
# Mortar
That crap between the bricks
## I depend on Mortar & cant auto-download Mortar without Mortar...
Because plugins depend on MortarPlugin you may have some class loading issues when enabling. To work around this, simply add this anywhere in your main plugin class.
What this does
* Checks if mortar is installed already
* If not, downloads Mortar and force-loads it
Mortar will be enabled before your plugin is enabled.
```java
static {
try {
URL url = new URL("https://raw.githubusercontent.com/VolmitSoftware/Mortar/master/release/Mortar.jar");
File plugins = new File("plugins");
Boolean foundMortar = false;
for (File i : plugins.listFiles()) {
if (i.isFile() && i.getName().endsWith(".jar")) {
ZipFile file = new ZipFile(i);
try {
Enumeration<? extends ZipEntry> entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if ("plugin.yml".equals(entry.getName())) {
InputStream in = file.getInputStream(entry);
PluginDescriptionFile pdf = new PluginDescriptionFile(in);
if (pdf.getMain().equals("mortar.bukkit.plugin.MortarAPIPlugin")) {
foundMortar = true;
break;
}
}
}
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
file.close();
}
}
}
if (!foundMortar) {
System.out.println("Cannot find mortar. Attempting to download...");
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
InputStream in = con.getInputStream();
File mortar = new File("plugins/Mortar.jar");
FileOutputStream fos = new FileOutputStream(mortar);
byte[] buf = new byte[16819];
int r = 0;
while ((r = in.read(buf)) != -1) {
fos.write(buf, 0, r);
}
fos.close();
in.close();
con.disconnect();
System.out.println("Mortar has been downloaded. Installing...");
Bukkit.getPluginManager().loadPlugin(mortar);
} catch (Throwable e) {
System.out.println("Failed to download mortar! Please download it from " + url.toString());
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
```
|
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
if [ "x$1" = "x-usage" ]; then
echo "Push memo to remote."
exit 0
fi
MEMODIR=`cat ~/.config/memo/config.toml | grep memodir | awk -F\" '{print $2}'`
echo "Push the following content to github."
echo " - ${MEMODIR}"
echo ""
echo "= = = current status = = ="
(cd ${MEMODIR} && git status)
echo ""
read -p " OK? (y/N): " yn
if [ "xy" != "x${yn}" ]; then
exit 1
fi
echo ""
echo "= = = exec log = = ="
(cd ${MEMODIR} && git add . && git commit -am'update documents' && git push)
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/sh
if [ "x$1" = "x-usage" ]; then
echo "Push memo to remote."
exit 0
fi
MEMODIR=`cat ~/.config/memo/config.toml | grep memodir | awk -F\" '{print $2}'`
echo "Push the following content to github."
echo " - ${MEMODIR}"
echo ""
echo "= = = current status = = ="
(cd ${MEMODIR} && git status)
echo ""
read -p " OK? (y/N): " yn
if [ "xy" != "x${yn}" ]; then
exit 1
fi
echo ""
echo "= = = exec log = = ="
(cd ${MEMODIR} && git add . && git commit -am'update documents' && git push)
|
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:
#[allow(dead_code)]
#[allow(unused_imports)]
#[allow(unused_must_use)]
#[allow(unused_variables)]
#[allow(unused_assignments)]
use rand::Rng;
use std::io::stdin;
fn strings()
{
// &str = string slice
let s: &'static str = "hello there!";
// cannot do
// s = "abc";
// println!("{}", s[0]};
for c in s.chars().rev()
{
println!("{}", c);
}
if let Some(char) = s.chars().nth(0)
{
println!("first char: {}", char);
}
// Heap - String
let mut letters = String::new();
let mut a = 'a' as u8;
while a <= ('z' as u8)
{
letters.push(a as char);
letters.push_str(" ");
a = a + 1;
}
println!("letters = {}", letters);
// &str <> String
let u: &str = &letters;
println!("u = {}", u);
// concatenation
// String + str
let v = String::from("abc");
let t = "def".to_string();
let z = v + &t + &u;
println!("z = {}", z);
let mut abc = "hello world".to_string();
abc.remove(0);
abc.push_str("!!!");
println!("{}", abc.replace("ello", "goodbye"));
}
fn string_format()
{
let name = "John";
let greeting = format!("Hi, I am {}, nice to meet you", name);
println!("{}", greeting);
let run = "run";
let forest = "forest";
let rfr = format!("{0}, {1}, {0}", run, forest);
println!("{}", rfr);
let info = format!("the name's {last}. {first} {last}",
first = "James", last = "Bond");
println!("{}", info);
let mixed = format!("{1} {} {0} {} {} {data}",
"alpha", "beta",
data = "delta");
println!("{}", mixed);
}
fn number_guessing_game()
{
let number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Enter you guess: ");
let mut buffer = String::new();
match stdin().read_line(&mut buffer) {
Ok(_) => {
let parsed = buffer.trim_end().parse:
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 |
#[allow(dead_code)]
#[allow(unused_imports)]
#[allow(unused_must_use)]
#[allow(unused_variables)]
#[allow(unused_assignments)]
use rand::Rng;
use std::io::stdin;
fn strings()
{
// &str = string slice
let s: &'static str = "hello there!";
// cannot do
// s = "abc";
// println!("{}", s[0]};
for c in s.chars().rev()
{
println!("{}", c);
}
if let Some(char) = s.chars().nth(0)
{
println!("first char: {}", char);
}
// Heap - String
let mut letters = String::new();
let mut a = 'a' as u8;
while a <= ('z' as u8)
{
letters.push(a as char);
letters.push_str(" ");
a = a + 1;
}
println!("letters = {}", letters);
// &str <> String
let u: &str = &letters;
println!("u = {}", u);
// concatenation
// String + str
let v = String::from("abc");
let t = "def".to_string();
let z = v + &t + &u;
println!("z = {}", z);
let mut abc = "hello world".to_string();
abc.remove(0);
abc.push_str("!!!");
println!("{}", abc.replace("ello", "goodbye"));
}
fn string_format()
{
let name = "John";
let greeting = format!("Hi, I am {}, nice to meet you", name);
println!("{}", greeting);
let run = "run";
let forest = "forest";
let rfr = format!("{0}, {1}, {0}", run, forest);
println!("{}", rfr);
let info = format!("the name's {last}. {first} {last}",
first = "James", last = "Bond");
println!("{}", info);
let mixed = format!("{1} {} {0} {} {} {data}",
"alpha", "beta",
data = "delta");
println!("{}", mixed);
}
fn number_guessing_game()
{
let number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Enter you guess: ");
let mut buffer = String::new();
match stdin().read_line(&mut buffer) {
Ok(_) => {
let parsed = buffer.trim_end().parse::<i64>();
match parsed {
Ok(guess) => {
if guess < 1 || guess > 100 {
println!("Your guess is out of range");
}
else {
if guess < number {
println!("Your guess is too low");
}
else {
if guess > number {
println!("Your het is too high");
}
else {
println!("Correct!!!!");
break;
}
}
}
},
Err(e) =>{
println!("Could not read you input. {}. Try again", e);
}
}
},
Err(_) => continue
}
}
}
fn main() {
strings();
string_format();
number_guessing_game();
}
|
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:
<HTML>
<head><script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-43183130-1', 'temple.edu'); ga('send', 'pageview'); </script>
<title><NAME>: Detroit Lives - Print</TITLE>
<link rel="stylesheet" href="general.css" type="text/css"><SCRIPT LANGUAGE = JAVASCRIPT></SCRIPT></HEAD>
<BODY LINK="#3152A5" VLINK="#3152A5" ALINK=Gray BGCOLOR=White>
<CENTER><P CLASS=intro><img src="/tempress/img/350line.gif" height="1" width="350"><br><img src="/tempress/img/spacer.gif" border="0" width="2" height="25">A story of spirit, growth, and survival in a city that reflects America's urban problems<br><img src="/tempress/img/spacer.gif" border="0" width="2" height="8"><br><img src="/tempress/img/350line.gif" height="1" width="350"></P></CENTER><br>
<!--none//--><Table width="100%" border=0 cellspacing=5><tr><td width="175" align="center"><img src="1016_reg.gif" height=200 border=1 VSPACE=4></td><td>
<h1 class="booktitle">Detroit Lives</h1>
<h3 class="author">edited by <NAME>, foreword by <NAME></h3>
<P class="info">paper EAN: 978-1-56639-226-6 (ISBN: 1-56639-226-8) <br>$36.95, Oct 94, <FONT COLOR=#990033>Available</FONT>
<br>cloth EAN: 978-1-56639-225-9 (ISBN: 1-56639-225-X) <br>$78.50, Oct 94, <FONT COLOR=#990033>Out of Stock Unavailable</FONT>
<br> 368 pp
6x9
</P></td></tr></table><BR><BLOCKQUOTE><P><I>"Only the numbest reader of these pages will fail to see the relationship of the urban realities herein explicated so poignantly to those that flamed so fiercely in Los Angeles in 1992. Given that context, no one should be shocked at the radical elements in the thought of these activists from so many diverse background, perspectives, and generations. To deal radically means to go to
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<HTML>
<head><script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-43183130-1', 'temple.edu'); ga('send', 'pageview'); </script>
<title><NAME>: Detroit Lives - Print</TITLE>
<link rel="stylesheet" href="general.css" type="text/css"><SCRIPT LANGUAGE = JAVASCRIPT></SCRIPT></HEAD>
<BODY LINK="#3152A5" VLINK="#3152A5" ALINK=Gray BGCOLOR=White>
<CENTER><P CLASS=intro><img src="/tempress/img/350line.gif" height="1" width="350"><br><img src="/tempress/img/spacer.gif" border="0" width="2" height="25">A story of spirit, growth, and survival in a city that reflects America's urban problems<br><img src="/tempress/img/spacer.gif" border="0" width="2" height="8"><br><img src="/tempress/img/350line.gif" height="1" width="350"></P></CENTER><br>
<!--none//--><Table width="100%" border=0 cellspacing=5><tr><td width="175" align="center"><img src="1016_reg.gif" height=200 border=1 VSPACE=4></td><td>
<h1 class="booktitle">Detroit Lives</h1>
<h3 class="author">edited by <NAME>, foreword by <NAME></h3>
<P class="info">paper EAN: 978-1-56639-226-6 (ISBN: 1-56639-226-8) <br>$36.95, Oct 94, <FONT COLOR=#990033>Available</FONT>
<br>cloth EAN: 978-1-56639-225-9 (ISBN: 1-56639-225-X) <br>$78.50, Oct 94, <FONT COLOR=#990033>Out of Stock Unavailable</FONT>
<br> 368 pp
6x9
</P></td></tr></table><BR><BLOCKQUOTE><P><I>"Only the numbest reader of these pages will fail to see the relationship of the urban realities herein explicated so poignantly to those that flamed so fiercely in Los Angeles in 1992. Given that context, no one should be shocked at the radical elements in the thought of these activists from so many diverse background, perspectives, and generations. To deal radically means to go to the root of things, the origins, the fundamentals. These Detroit voices insist that the problems of urban Americans have become so grave that nothing less will suffice."</I>
<br>—<b><NAME></b><I></I></P></BLOCKQUOTE>
<P><p><I>Detroit Lives</I> tells the story of a city fighting for survival. <NAME>'s interviews with numerous Detroit activists and observers depict people from all walks of life who share a common commitment to the rejuvenation of their home. Despite a mass exodus from the city of over 800,000 citizens and more than 70 percent of business and industry over the last 40 years, Detroit's activists continue to organize, to demonstrate, to speak out, and to lend one another support.
<p>The compilation of these interviews provides an exchange of ideas between progressives who were and are deeply involved in the multitude of struggles for equality and liberation, from the 1930s through the 1990s. Their stories highlight the contributions and resourcefulness of working class and minorities, the struggles of women, the role of the clergy, the African American experience, and the battle to maintain quality education and social services. Represented is the collective body of Detroit progressives—including city and suburban dwellers, writers, lawyers, city officials, professors, union members, clergy, housing and welfare reformers, racial activists, and community organizers.</p>
<BR><H2 class="inpageheading">Contents</h2><p>
<p>Foreword – Dan Georgakas
<br>Preface
<br>Introduction
<br>Prologue
<br>1. Organizing for Survival at the Grassroots
<br>2. The African-American Experience
<br>3. The Struggles of Women
<br>4. City Life, Scenes, Feelings
<br>5. The Trauma of the Politics of Race and Class
<br>6. There Is Power: The Dilemma of Organized Labor in Motown
<br>7. Theology for the People
<br>8. The Changing Visions of Detroit's White Male Left
<br>9. Analyze and Regroup: The Left Against All Odds
<br>Index
</P><BR> <BR><H2 class="inpageheading">About the Author(s)</H2><p>
<P><b><NAME></b> is Coordinator of the Pittsburgh Oral History Project and Adjunct Professor of Sociology at Clarion University in Pennsylvania.</P>
</p>
<BR><H2 class="inpageheading">Subject Categories</H2>
<p><A HREF="/tempress/urban.html" TARGET="_top">Urban Studies</a>
<BR>
</p>
<BR><h2 class="inpageheading">In the series</H2>
<P><I><a href="http://www.temple.edu/tempress/conflicts.html" onMouseOver="window.status='Click for other books in this series!'; return true;" onMouseOut="window.status=''; return true;" target="_top">Conflicts in Urban and Regional Development</a></i>, edited by <NAME> and <NAME>.
</p><p><i>Conflicts in Urban and Regional Development</i>, edited by <NAME> and <NAME>, includes books on urban policy and issues of city and regional planning, accounts of the political economy of individual cities, and books that compare policies across cities and countries.</p>
<P> </P><font face="Arial" size="1"><a href="copyright.html" OnMouseOver="window.status='Web Copyright Policy';return true;" OnMouseOut="window.status=''" TITLE="Web Copyright Policy">©</a> 2015 <a href="http://www.temple.edu" target="new" OnMouseOver="window.status='Link to Temple University home page';return true;" OnMouseOut="window.status=''" TITLE="Link to Temple University home page">Temple University</a>. All Rights Reserved. This page: <a href="http://www.temple.edu/tempress/titles/1016_reg.html"OnMouseOver="window.status='Link to the book page';return true;" OnMouseOut="window.status=''" TITLE="Link to the book page">http://www.temple.edu/tempress/titles/1016_reg.html.</a></font></BODY></HTML>
|
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
[ 3 -eq 2 ]
RET_VAL=$?
if [ $RET_VAL != 0 ]; then
#can not use [ $ARG_NUM ]
echo "RET_VAL=$RET_VAL"
else
echo "0, TRUE, success"
fi
ARG_NUM=$#
if [ $ARG_NUM = 0 ]; then
#can not use [ ! $ARG_NUM ]
echo "no arg input"
elif [ $ARG_NUM -gt 3 ]; then
#can not use [ $ARG_NUM > 3 ]
echo "too many args input"
else
echo "$ARG_NUM arg(s) input"
fi
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
| 3 |
#! /bin/sh
[ 3 -eq 2 ]
RET_VAL=$?
if [ $RET_VAL != 0 ]; then
#can not use [ $ARG_NUM ]
echo "RET_VAL=$RET_VAL"
else
echo "0, TRUE, success"
fi
ARG_NUM=$#
if [ $ARG_NUM = 0 ]; then
#can not use [ ! $ARG_NUM ]
echo "no arg input"
elif [ $ARG_NUM -gt 3 ]; then
#can not use [ $ARG_NUM > 3 ]
echo "too many args input"
else
echo "$ARG_NUM arg(s) input"
fi
|
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';
// directive for handling editing artworks
angular.module('artApp')
.directive('artworkEdit', function () {
return {
templateUrl: 'views/artworks/_editCreate.html',
restrict: 'A',
controller: 'ArtworkEditCtrl',
link: function postLink(scope, element, attrs) {
scope.artworkAtLink = angular.copy(scope.artwork);
// canceling edit
element.on('click', '.stopEdit', function(){
scope.artwork = scope.artworkAtLink;
scope.$apply(function(){
scope.artwork.inEdit = false;
});
});
// adding material
element.on('keyup', '#addMaterial', function(e){
if(e.keyCode === 13){
scope.addMaterialAndAttach();
}
});
}
};
});
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 |
'use strict';
// directive for handling editing artworks
angular.module('artApp')
.directive('artworkEdit', function () {
return {
templateUrl: 'views/artworks/_editCreate.html',
restrict: 'A',
controller: 'ArtworkEditCtrl',
link: function postLink(scope, element, attrs) {
scope.artworkAtLink = angular.copy(scope.artwork);
// canceling edit
element.on('click', '.stopEdit', function(){
scope.artwork = scope.artworkAtLink;
scope.$apply(function(){
scope.artwork.inEdit = false;
});
});
// adding material
element.on('keyup', '#addMaterial', function(e){
if(e.keyCode === 13){
scope.addMaterialAndAttach();
}
});
}
};
});
|
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>
<title>Flat Admin V.2 - Free Bootstrap Admin Templates</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Fonts -->
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:300,400' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,900' rel='stylesheet' type='text/css'>
<!-- CSS Libs -->
<link rel="stylesheet" type="text/css" href="../lib/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/animate.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/bootstrap-switch.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/checkbox3.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/dataTables.bootstrap.css">
<link rel="stylesheet" type="text/css" href="../lib/css/select2.min.css">
<!-- CSS App -->
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/themes/flat-blue.css">
</head>
<body class="flat-blue">
<div class="app-container">
<div class="row content-container">
<nav class="navbar navbar-default navbar-fixed-top navbar-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-expand-toggle">
<i class="fa fa-bars icon"></i>
</button>
<ol class="breadcrumb navbar-breadcrumb">
<li class="active">Licence</li>
</ol>
<button type="button" class="navbar-right-expand-toggle pull-right visible-xs">
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!DOCTYPE html>
<html>
<head>
<title>Flat Admin V.2 - Free Bootstrap Admin Templates</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Fonts -->
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:300,400' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,900' rel='stylesheet' type='text/css'>
<!-- CSS Libs -->
<link rel="stylesheet" type="text/css" href="../lib/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/animate.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/bootstrap-switch.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/checkbox3.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="../lib/css/dataTables.bootstrap.css">
<link rel="stylesheet" type="text/css" href="../lib/css/select2.min.css">
<!-- CSS App -->
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/themes/flat-blue.css">
</head>
<body class="flat-blue">
<div class="app-container">
<div class="row content-container">
<nav class="navbar navbar-default navbar-fixed-top navbar-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-expand-toggle">
<i class="fa fa-bars icon"></i>
</button>
<ol class="breadcrumb navbar-breadcrumb">
<li class="active">Licence</li>
</ol>
<button type="button" class="navbar-right-expand-toggle pull-right visible-xs">
<i class="fa fa-th icon"></i>
</button>
</div>
</div>
</nav>
<div class="side-menu sidebar-inverse">
<nav class="navbar navbar-default" role="navigation">
<div class="side-menu-container">
<ul class="nav navbar-nav">
<li>
<a href="index.html">
<span class="icon fa fa-tachometer"></span><span class="title">back</span>
</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
</div>
<!-- Main Content -->
<div class="container-fluid">
<div class="side-body">
<div class="page-title">
<span class="title">License</span>
</div>
<div class="row">
<div class="col-xs-12">
<div class="card">
<div class="card-body">
The MIT License (MIT)<br><br>
Copyright (c) [2015] [Flat Admin Bootstrap Templates]<br><br>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:<br><br>
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.<br><br>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="app-footer">
<div class="wrapper">
<span class="pull-right">2.1 <a href="#"><i class="fa fa-long-arrow-up"></i></a></span> © 2015 Copyright.
</div>
</footer>
<div>
<!-- Javascript Libs -->
<script type="text/javascript" src="../lib/js/jquery.min.js"></script>
<script type="text/javascript" src="../lib/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../lib/js/Chart.min.js"></script>
<script type="text/javascript" src="../lib/js/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="../lib/js/jquery.matchHeight-min.js"></script>
<script type="text/javascript" src="../lib/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../lib/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="../lib/js/select2.full.min.js"></script>
<script type="text/javascript" src="../lib/js/ace/ace.js"></script>
<script type="text/javascript" src="../lib/js/ace/mode-html.js"></script>
<script type="text/javascript" src="../lib/js/ace/theme-github.js"></script>
<!-- Javascript -->
<script type="text/javascript" src="../js/app.js"></script>
<script type="text/javascript" src="../js/index.js"></script>
</body>
</html>
|
Below is an extract from a C# program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
Add 1 point if the program contains valid C# code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
Add another point if the program addresses practical C# concepts, even if it lacks comments.
Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., LINQ, reflection). The code should be well-structured and contain some comments.
Give a fourth point if the program is self-contained and highly relevant to teaching C#. It should be similar to a school exercise, a tutorial, or a C# course section.
Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching C#. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuadraCore.Models
{
public class Element
{
public Element()
{
ID = new ElementId(String.Empty, 0, 0);
Parameters = new Dictionary<string, object>();
}
#region Properties
public string Name { get; set; }
public ElementId ID { get; set; }
public int Orientation { get; set; }
public Dictionary<string, object> Parameters { get; set; }
public string Code { get { return ID.code; } }
public int X { get { return ID.x; } }
public int Y { get { return ID.y; } }
public int X2 { get { return ID.x2; } }
public int Y2 { get { return ID.y2; } }
#endregion
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
csharp
| 2 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuadraCore.Models
{
public class Element
{
public Element()
{
ID = new ElementId(String.Empty, 0, 0);
Parameters = new Dictionary<string, object>();
}
#region Properties
public string Name { get; set; }
public ElementId ID { get; set; }
public int Orientation { get; set; }
public Dictionary<string, object> Parameters { get; set; }
public string Code { get { return ID.code; } }
public int X { get { return ID.x; } }
public int Y { get { return ID.y; } }
public int X2 { get { return ID.x2; } }
public int Y2 { get { return ID.y2; } }
#endregion
}
}
|
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 { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IAppConfig, AppConfig } from '../../app.config';
@Injectable({ providedIn: 'root' })
export class AppConfigService {
// AppConfig.settings
// protected appConfig: AppConfig;
constructor(private http: HttpClient, private appConfig: AppConfig) {
// this.appConfig = appConfig;
}
load() {
const jsonFile = `assets/config/config.json`;
console.log('[AppConfigService] [load]', {jsonFile})
return new Promise<void>((resolve, reject) => {
this.http.get(jsonFile).toPromise().then((response: HagridConfig) => {
let objFim = {};
console.log('Config Loaded', { response });
let pall2 = response.propertySources.map((e: PropertySources) => {
// console.log('PropertySources', { e });
// console.log('PropertySources', e.source);
let pall1 = Object.keys(e.source).map((key) => {
let value = e.source[key];
console.log(`key: ${key}, value: ${value}`);
return Promise.resolve(index(objFim, key, value));
});
console.log('pall1', pall1);
return Promise.all(pall1);
});
console.log('pall2', pall2);
Promise.all(pall2).then((r) => {
console.log('obj', { objFim });
this.appConfig.settings = <IAppConfig>objFim;
console.log('this.appConfig.settings', this.appConfig.settings);
resolve();
});
// resolve();
}).catch((response: any) => {
console.error('[AppConfigService] [error]', {response})
reject(`Could not load the config file`);
});
});
}
}
function index(obj
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 { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IAppConfig, AppConfig } from '../../app.config';
@Injectable({ providedIn: 'root' })
export class AppConfigService {
// AppConfig.settings
// protected appConfig: AppConfig;
constructor(private http: HttpClient, private appConfig: AppConfig) {
// this.appConfig = appConfig;
}
load() {
const jsonFile = `assets/config/config.json`;
console.log('[AppConfigService] [load]', {jsonFile})
return new Promise<void>((resolve, reject) => {
this.http.get(jsonFile).toPromise().then((response: HagridConfig) => {
let objFim = {};
console.log('Config Loaded', { response });
let pall2 = response.propertySources.map((e: PropertySources) => {
// console.log('PropertySources', { e });
// console.log('PropertySources', e.source);
let pall1 = Object.keys(e.source).map((key) => {
let value = e.source[key];
console.log(`key: ${key}, value: ${value}`);
return Promise.resolve(index(objFim, key, value));
});
console.log('pall1', pall1);
return Promise.all(pall1);
});
console.log('pall2', pall2);
Promise.all(pall2).then((r) => {
console.log('obj', { objFim });
this.appConfig.settings = <IAppConfig>objFim;
console.log('this.appConfig.settings', this.appConfig.settings);
resolve();
});
// resolve();
}).catch((response: any) => {
console.error('[AppConfigService] [error]', {response})
reject(`Could not load the config file`);
});
});
}
}
function index(obj, is, value) {
// console.log('obj', { obj }, 'is', { is }, 'value', { value });
if (typeof is == 'string')
return index(obj, is.split('.'), value);
else if (is.length == 1 && value !== undefined)
return obj[is[0]] = value;
else if (is.length == 0)
return obj;
else {
if(!obj[is[0]]){
obj[is[0]] = {};
}
return index(obj[is[0]], is.slice(1), value);
}
}
export interface HagridConfig {
name: string,
profiles: Array<string>,
propertySources: Array<PropertySources>
}
export interface PropertySources {
name: string,
source: Object
}
|
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 (
"flag"
"fmt"
"github.com/nlopes/slack"
)
var token = flag.String("token", "", "bot token generated by slack")
var debug = flag.Bool("debug", false, "set to show debugging messages")
func main() {
flag.Parse()
if *token == "" {
fmt.Println("Please set -token flag")
flag.PrintDefaults()
return
}
api := slack.New(*token)
api.SetDebug(*debug)
rtm := api.NewRTM()
go rtm.ManageConnection()
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
if len(ev.Text) > 0 && playgroundUrl.MatchString(ev.Text) {
addrs := playgroundUrl.FindAllString(ev.Text, -1)
for _, addr := range addrs {
data, err := playground(addr)
if err != nil {
fmt.Println("Playground error:", err)
continue
}
rtm.SendMessage(rtm.NewOutgoingMessage(data, ev.Channel))
}
}
case *slack.InvalidAuthEvent:
fmt.Printf("Invalid credentials")
break Loop
default:
// Ignore other events..
}
}
}
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
go
| 4 |
package main
import (
"flag"
"fmt"
"github.com/nlopes/slack"
)
var token = flag.String("token", "", "bot token generated by slack")
var debug = flag.Bool("debug", false, "set to show debugging messages")
func main() {
flag.Parse()
if *token == "" {
fmt.Println("Please set -token flag")
flag.PrintDefaults()
return
}
api := slack.New(*token)
api.SetDebug(*debug)
rtm := api.NewRTM()
go rtm.ManageConnection()
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
if len(ev.Text) > 0 && playgroundUrl.MatchString(ev.Text) {
addrs := playgroundUrl.FindAllString(ev.Text, -1)
for _, addr := range addrs {
data, err := playground(addr)
if err != nil {
fmt.Println("Playground error:", err)
continue
}
rtm.SendMessage(rtm.NewOutgoingMessage(data, ev.Channel))
}
}
case *slack.InvalidAuthEvent:
fmt.Printf("Invalid credentials")
break Loop
default:
// Ignore other events..
}
}
}
}
|
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 FIL_H
#define FIL_H
#include "ds.h"
#include "gen.h"
#include <fstream>
#include <iostream>
void input(Hash *details);
void storeInFile(User user);
#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>"
|
cpp
| 1 |
#ifndef FIL_H
#define FIL_H
#include "ds.h"
#include "gen.h"
#include <fstream>
#include <iostream>
void input(Hash *details);
void storeInFile(User user);
#endif
|
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
java -Xmx1024M -Xms1024M -jar server-1.16.1.jar nogui
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 2 |
#!/bin/sh
java -Xmx1024M -Xms1024M -jar server-1.16.1.jar nogui
|
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 audit
import (
"fmt"
"log"
"os"
"github.com/kaz/flos/libra"
"github.com/kaz/flos/libra/bookshelf"
"github.com/kaz/flos/state"
)
var (
logger = log.New(os.Stdout, "[audit] ", log.Ltime)
)
func StartWorker() {
go cacheFlusher()
auditor, err := NewAuditor(false)
if err != nil {
logger.Printf("failed to init auditor: %v\n", err)
return
}
for _, path := range state.Get().Audit.File {
if err := auditor.WatchFile(path); err != nil {
logger.Printf("failed to watch: %v\n", err)
continue
}
logger.Printf("Watching file=%v\n", path)
}
for _, path := range state.Get().Audit.Mount {
if err := auditor.WatchMount(path); err != nil {
logger.Printf("failed to watch: %v\n", err)
return
}
logger.Printf("Watching mount=%v\n", path)
}
for ev := range auditor.Event {
go eventProcess(ev)
}
}
func eventProcess(ev *Event) {
if bookshelf.IsBookshelf(ev.FileName) {
return
}
libra.Put("audit", fmt.Sprintln(ev.Acts, ev.FileName, "by", ev.ProcessInfo))
}
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 audit
import (
"fmt"
"log"
"os"
"github.com/kaz/flos/libra"
"github.com/kaz/flos/libra/bookshelf"
"github.com/kaz/flos/state"
)
var (
logger = log.New(os.Stdout, "[audit] ", log.Ltime)
)
func StartWorker() {
go cacheFlusher()
auditor, err := NewAuditor(false)
if err != nil {
logger.Printf("failed to init auditor: %v\n", err)
return
}
for _, path := range state.Get().Audit.File {
if err := auditor.WatchFile(path); err != nil {
logger.Printf("failed to watch: %v\n", err)
continue
}
logger.Printf("Watching file=%v\n", path)
}
for _, path := range state.Get().Audit.Mount {
if err := auditor.WatchMount(path); err != nil {
logger.Printf("failed to watch: %v\n", err)
return
}
logger.Printf("Watching mount=%v\n", path)
}
for ev := range auditor.Event {
go eventProcess(ev)
}
}
func eventProcess(ev *Event) {
if bookshelf.IsBookshelf(ev.FileName) {
return
}
libra.Put("audit", fmt.Sprintln(ev.Acts, ev.FileName, "by", ev.ProcessInfo))
}
|
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 { Component, OnInit } from '@angular/core';
import { CompStatModel } from 'src/Models/CompStatModel';
import { ActivatedRoute, Params } from '@angular/router';
import { RestService } from 'src/Services/rest.service';
import {Router} from "@angular/router";
import { faSync } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-competition-result',
templateUrl: './competition-result.component.html',
styleUrls: ['./competition-result.component.css']
})
export class CompetitionResultComponent implements OnInit {
compStatModels : CompStatModel[];
compId: number;
constructor(private myRoute: ActivatedRoute, private api: RestService, private router: Router) { }
faSync = faSync;
ngOnInit(): void{
this.compId = Number(this.myRoute.snapshot.params.compId);
this.getResults()
}
getResults(): void{
this.api.getCompetitionResults(this.compId).then(res => {this.compStatModels = res});
}
TakeTest(): void{
this.router.navigate(['./CompetitionTest/',this.compId]).then();
}
}
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 { Component, OnInit } from '@angular/core';
import { CompStatModel } from 'src/Models/CompStatModel';
import { ActivatedRoute, Params } from '@angular/router';
import { RestService } from 'src/Services/rest.service';
import {Router} from "@angular/router";
import { faSync } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-competition-result',
templateUrl: './competition-result.component.html',
styleUrls: ['./competition-result.component.css']
})
export class CompetitionResultComponent implements OnInit {
compStatModels : CompStatModel[];
compId: number;
constructor(private myRoute: ActivatedRoute, private api: RestService, private router: Router) { }
faSync = faSync;
ngOnInit(): void{
this.compId = Number(this.myRoute.snapshot.params.compId);
this.getResults()
}
getResults(): void{
this.api.getCompetitionResults(this.compId).then(res => {this.compStatModels = res});
}
TakeTest(): void{
this.router.navigate(['./CompetitionTest/',this.compId]).then();
}
}
|
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:
//
// TSVersionCheck.swift
// ThinkSNSPlus
//
// Created by IMAC on 2018/11/9.
// Copyright © 2018年 ZhiYiCX. All rights reserved.
//
import UIKit
//import MarkdownView
class TSVersionCheck: UIViewController {
/// 整体白色背景视图的高度
var whiteHeight: CGFloat = 349.0
/// 整体白色背景的宽度
var whiteWidth: CGFloat = 500 / 2.0
/// 整体白色背景的内部视图与白色背景左右间距
var inMargin: CGFloat = 30
/// 有透明度的背景视图
var bgView = UIView()
/// 整体白色背景视图
var whiteView = UIView()
var detailView = MarkdownView()
/// 顶部图片
var topImage = UIImageView()
/// 顶部图片以下的白色
var bottomView = UIView()
/// 发送给谁 主题文字
var titleLabel = UILabel()
/// 发送按钮
var sureButton = UIButton(type: .custom)
/// 关闭按钮
var closeButton = UIButton(type: .custom)/// 当前的model
var sendModel: AppVersionCheckModel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0, alpha: 0.2)
setUI()
}
func setUI() {
whiteView.frame = CGRect(x: 0, y: 0, width: whiteWidth, height: whiteHeight)
whiteView.backgroundColor = UIColor.clear
whiteView.layer.cornerRadius = 10
whiteView.clipsToBounds = true
whiteView.centerY = ScreenHeight / 2.0
whiteView.centerX = ScreenWidth / 2.0
self.view.addSubview(whiteView)
bottomView.frame = CGRect(x: 0, y: 40, width: whiteWidth, height: whiteHeight - 40)
bottomView.backgroundColor = UIColor.white
whiteView.addSubview(bottomView)
topImage.frame = CGRect(x: 0, y: 0, width: whiteWidth, height: 241 / 2.0)
topImage.clipsToBounds = true
topImage.contentMode = .scaleAspectFill
topImage.image = #imageLiteral(resourceName: "pic_update")
whiteView.addSubview(topImage)
/// 这里高度原本是16 但是避免文字显示不完整,扩大了 4 ,Y坐标就向上偏移 2
titleLabel.frame = CGRect(x: 0, y: topImage.bottom + 22, width: whiteWidth, height: 20)
titleLabel.textColor = UIColor(he
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 |
//
// TSVersionCheck.swift
// ThinkSNSPlus
//
// Created by IMAC on 2018/11/9.
// Copyright © 2018年 ZhiYiCX. All rights reserved.
//
import UIKit
//import MarkdownView
class TSVersionCheck: UIViewController {
/// 整体白色背景视图的高度
var whiteHeight: CGFloat = 349.0
/// 整体白色背景的宽度
var whiteWidth: CGFloat = 500 / 2.0
/// 整体白色背景的内部视图与白色背景左右间距
var inMargin: CGFloat = 30
/// 有透明度的背景视图
var bgView = UIView()
/// 整体白色背景视图
var whiteView = UIView()
var detailView = MarkdownView()
/// 顶部图片
var topImage = UIImageView()
/// 顶部图片以下的白色
var bottomView = UIView()
/// 发送给谁 主题文字
var titleLabel = UILabel()
/// 发送按钮
var sureButton = UIButton(type: .custom)
/// 关闭按钮
var closeButton = UIButton(type: .custom)/// 当前的model
var sendModel: AppVersionCheckModel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0, alpha: 0.2)
setUI()
}
func setUI() {
whiteView.frame = CGRect(x: 0, y: 0, width: whiteWidth, height: whiteHeight)
whiteView.backgroundColor = UIColor.clear
whiteView.layer.cornerRadius = 10
whiteView.clipsToBounds = true
whiteView.centerY = ScreenHeight / 2.0
whiteView.centerX = ScreenWidth / 2.0
self.view.addSubview(whiteView)
bottomView.frame = CGRect(x: 0, y: 40, width: whiteWidth, height: whiteHeight - 40)
bottomView.backgroundColor = UIColor.white
whiteView.addSubview(bottomView)
topImage.frame = CGRect(x: 0, y: 0, width: whiteWidth, height: 241 / 2.0)
topImage.clipsToBounds = true
topImage.contentMode = .scaleAspectFill
topImage.image = #imageLiteral(resourceName: "pic_update")
whiteView.addSubview(topImage)
/// 这里高度原本是16 但是避免文字显示不完整,扩大了 4 ,Y坐标就向上偏移 2
titleLabel.frame = CGRect(x: 0, y: topImage.bottom + 22, width: whiteWidth, height: 20)
titleLabel.textColor = UIColor(hex: 0x333333)
titleLabel.font = UIFont(name: "PingFangSC-Medium", size: 16)
titleLabel.text = "发现新版本!"
titleLabel.textAlignment = .center
whiteView.addSubview(titleLabel)
detailView.frame = CGRect(x: inMargin, y: titleLabel.bottom + 24, width: whiteWidth - inMargin * 2, height: 80)
detailView.isScrollEnabled = true
whiteView.addSubview(detailView)
sureButton.frame = CGRect(x: inMargin, y: detailView.bottom + 27, width: whiteWidth - inMargin * 2, height: 35)
sureButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
sureButton.backgroundColor = TSColor.main.theme
sureButton.setTitleColor(UIColor.white, for: .normal)
sureButton.setTitle("立即更新", for: .normal)
sureButton.clipsToBounds = true
sureButton.layer.cornerRadius = 4
sureButton.addTarget(self, action: #selector(sendBtnClick), for: UIControlEvents.touchUpInside)
whiteView.addSubview(sureButton)
closeButton.frame = CGRect(x: 0, y: whiteView.bottom + 37, width: 24, height: 24)
closeButton.clipsToBounds = true
closeButton.layer.cornerRadius = 12
closeButton.setImage(#imageLiteral(resourceName: "ico_update_close"), for: .normal)
closeButton.addTarget(self, action: #selector(closeBtnClick), for: UIControlEvents.touchUpInside)
closeButton.centerX = whiteView.centerX
self.view.addSubview(closeButton)
}
func sendBtnClick() {
UIApplication.shared.openURL(URL(string: self.sendModel.link)!)
hidSelf()
/// 关闭App
assert(false, "upload version")
}
func hidSelf() {
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
/// 关闭即为忽略当前版本
func closeBtnClick() {
TSCurrentUserInfo.share.lastIgnoreAppVesin = sendModel
hidSelf()
}
public func show(vc: TSVersionCheck, presentVC: UIViewController) {
if presentVC != nil {
presentVC.addChildViewController(vc)
presentVC.didMove(toParentViewController: presentVC)
presentVC.view.addSubview(vc.view)
}
}
func setVersionInfo(model: AppVersionCheckModel) {
self.sendModel = model
if model.is_forced {
closeButton.isHidden = true
} else {
closeButton.isHidden = false
}
let content = model.description.ts_customMarkdownToStandard()
self.detailView.load(markdown: content, enableImage: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
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 styled from 'styled-components';
import { Form as FormA} from '@unform/web';
export const Container = styled.div`
border-bottom: 2px solid #e3e8f4;
`;
export const Form = styled(FormA)`
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
> div {
margin-left: 4px;
}
> button {
width: 100px;
margin-top: 15px;
margin-left: 10px;
}
`;
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 styled from 'styled-components';
import { Form as FormA} from '@unform/web';
export const Container = styled.div`
border-bottom: 2px solid #e3e8f4;
`;
export const Form = styled(FormA)`
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
> div {
margin-left: 4px;
}
> button {
width: 100px;
margin-top: 15px;
margin-left: 10px;
}
`;
|
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.nanamare.mac.grab.data.source.remote
import com.nanamare.mac.grab.data.source.GeocodeDataSource
import com.nanamare.mac.grab.ext.networkDispatchToMainThread
import com.nanamare.mac.grab.network.api.GeocodeAPI
import com.nanamare.mac.grab.network.response.GeocodeResponse
import com.nanamare.mac.grab.network.response.PlaceResponse
import com.nanamare.mac.grab.network.response.ReverseGeocodeResponse
import io.reactivex.Single
class RemoteGeocodeDataSourceImpl(private val geocodeAPI: GeocodeAPI) : GeocodeDataSource {
override fun getLocationUseAddress(address: String): Single<GeocodeResponse> =
geocodeAPI.getLocationUseAddress(address).networkDispatchToMainThread()
override fun getPlace(address: String): Single<PlaceResponse> =
geocodeAPI.getPlace(address).networkDispatchToMainThread()
override fun getLocationUseLatLng(latLng: String): Single<ReverseGeocodeResponse> =
geocodeAPI.getLocationUseLatLng(latLng).networkDispatchToMainThread()
}
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.nanamare.mac.grab.data.source.remote
import com.nanamare.mac.grab.data.source.GeocodeDataSource
import com.nanamare.mac.grab.ext.networkDispatchToMainThread
import com.nanamare.mac.grab.network.api.GeocodeAPI
import com.nanamare.mac.grab.network.response.GeocodeResponse
import com.nanamare.mac.grab.network.response.PlaceResponse
import com.nanamare.mac.grab.network.response.ReverseGeocodeResponse
import io.reactivex.Single
class RemoteGeocodeDataSourceImpl(private val geocodeAPI: GeocodeAPI) : GeocodeDataSource {
override fun getLocationUseAddress(address: String): Single<GeocodeResponse> =
geocodeAPI.getLocationUseAddress(address).networkDispatchToMainThread()
override fun getPlace(address: String): Single<PlaceResponse> =
geocodeAPI.getPlace(address).networkDispatchToMainThread()
override fun getLocationUseLatLng(latLng: String): Single<ReverseGeocodeResponse> =
geocodeAPI.getLocationUseLatLng(latLng).networkDispatchToMainThread()
}
|
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(__DIR__.'/../../gsbSoloE6/model/model.php');
function index()
{
require(__DIR__.'/../../gsbSoloE6/login.php');
}
function familles()
{
$lesfam = getFamilles();
require(__DIR__.'/../../gsbSoloE6/view/familles.php');
}
function medicaments()
{
$lesMedicaments = getMedicaments();
require(__DIR__.'/../../gsbSoloE6/view/medicaments.php');
}
function medicament()
{
$lesMedicaments = getMedicaments();
require(__DIR__.'/../../gsbSoloE6/view/forms/modifMedic.php');
}
function medicamentsFromF($idFamille)
{
$lesMedicaments = getMedicamentsFromFamille($idFamille);
require(__DIR__.'/../../gsbSoloE6/view/medicaments.php');
}
function addFamille($id, $libelle)
{
$newFamille = postFamille($id, $libelle);
if($newFamille === false){
die('Impossible d\'ajouter la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function addMedicament($id, $nomCommercial, $idFamille, $composition, $effets, $contreIndications)
{
$newFamille = postMedicament($id, $nomCommercial, $idFamille, $composition, $effets, $contreIndications);
if($newFamille === false){
die('Impossible d\'ajouter le médicament');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurMedicaments.php"); </script><?php
}
}
function updateFamille($newId, $libelle, $oldId)
{
$changeFamille = modifyFamille($newId, $libelle, $oldId);
if($changeFamille == false){
die('Impossible de modifier la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function updateFamille2($newId, $oldId)
{
$changeFamille = modifyFamille2($newId, $oldId);
if($changeFamille == false){
die('Impossible de modifier la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function u
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(__DIR__.'/../../gsbSoloE6/model/model.php');
function index()
{
require(__DIR__.'/../../gsbSoloE6/login.php');
}
function familles()
{
$lesfam = getFamilles();
require(__DIR__.'/../../gsbSoloE6/view/familles.php');
}
function medicaments()
{
$lesMedicaments = getMedicaments();
require(__DIR__.'/../../gsbSoloE6/view/medicaments.php');
}
function medicament()
{
$lesMedicaments = getMedicaments();
require(__DIR__.'/../../gsbSoloE6/view/forms/modifMedic.php');
}
function medicamentsFromF($idFamille)
{
$lesMedicaments = getMedicamentsFromFamille($idFamille);
require(__DIR__.'/../../gsbSoloE6/view/medicaments.php');
}
function addFamille($id, $libelle)
{
$newFamille = postFamille($id, $libelle);
if($newFamille === false){
die('Impossible d\'ajouter la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function addMedicament($id, $nomCommercial, $idFamille, $composition, $effets, $contreIndications)
{
$newFamille = postMedicament($id, $nomCommercial, $idFamille, $composition, $effets, $contreIndications);
if($newFamille === false){
die('Impossible d\'ajouter le médicament');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurMedicaments.php"); </script><?php
}
}
function updateFamille($newId, $libelle, $oldId)
{
$changeFamille = modifyFamille($newId, $libelle, $oldId);
if($changeFamille == false){
die('Impossible de modifier la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function updateFamille2($newId, $oldId)
{
$changeFamille = modifyFamille2($newId, $oldId);
if($changeFamille == false){
die('Impossible de modifier la famille');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
}
function updateMedicament($newId, $nomCommercial, $idFamille, $composition, $effets, $contreIndications, $oldId)
{
$changeMedicament = modifyMedicament($newId, $nomCommercial, $idFamille, $composition, $effets, $contreIndications, $oldId);
if($changeMedicament == false){
die('Impossible de modifier le médicament');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurMedicaments.php"); </script><?php
}
}
function deleteFamille($id)
{
$delFamille = removeFamille($id);
?><script> location.replace("/gsbSoloE6/routeur/routeurFamilles.php"); </script><?php
}
function deleteMedicament($id)
{
$delMedicament = removeMedicament($id);
if($delMedicament == false){
die('Impossible de supprimer le médicament');
}
else{
?><script> location.replace("/gsbSoloE6/routeur/routeurMedicaments.php"); </script><?php
}
}
function searchMedicament($id)
{
$lesMedicaments = findMedicament($id);
require(__DIR__.'/../../gsbSoloE6/view/medicaments.php');
}
|
Below is an extract from a Swift program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Swift code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Swift concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., protocols, extensions). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Swift. It should be similar to a school exercise, a tutorial, or a Swift course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Swift. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
// swiftlint:disable all
//
// RankingViewModel.swift
// DriveKitDriverAchievementUI
//
// Created by <NAME> on 06/07/2020.
// Copyright © 2020 DriveQuant. All rights reserved.
//
import Foundation
import DriveKitCommonUI
import DriveKitCoreModule
import DriveKitDBAchievementAccessModule
import DriveKitDriverAchievementModule
import UIKit
class RankingViewModel {
var selectedRankingType: RankingType? {
didSet {
update(allowEmptyPseudo: false)
}
}
var selectedRankingSelector: RankingSelector? {
didSet {
update(allowEmptyPseudo: false)
}
}
weak var delegate: RankingViewModelDelegate?
private(set) var status: RankingStatus = .needsUpdate
private(set) var ranks = [DKDriverRankingItem]()
private(set) var driverRank: CurrentDriverRank?
private(set) var rankingTypes = [RankingType]()
private(set) var rankingSelectors = [RankingSelector]()
private(set) var nbDrivers = 0
private let groupName: String?
private let dkRankingTypes: [DKRankingType]
private let dkRankingSelectorType: DKRankingSelectorType
private let rankingDepth: Int
private var useCache = [String: Bool]()
private var initialized = false
private var progressionImageName: String?
private var askForPseudoIfEmpty = true
init(groupName: String?) {
self.groupName = groupName
self.dkRankingTypes = RankingViewModel.sanitizeRankingTypes(DriveKitDriverAchievementUI.shared.rankingTypes)
for (index, rankingType) in self.dkRankingTypes.enumerated() {
switch rankingType {
case .distraction:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.distraction.text(), image: DKImages.distractionFlat.image))
case .ecoDriving:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.ecodriving.text(), image: DKImages.ecoDrivingFlat.image))
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
swift
| 1 |
// swiftlint:disable all
//
// RankingViewModel.swift
// DriveKitDriverAchievementUI
//
// Created by <NAME> on 06/07/2020.
// Copyright © 2020 DriveQuant. All rights reserved.
//
import Foundation
import DriveKitCommonUI
import DriveKitCoreModule
import DriveKitDBAchievementAccessModule
import DriveKitDriverAchievementModule
import UIKit
class RankingViewModel {
var selectedRankingType: RankingType? {
didSet {
update(allowEmptyPseudo: false)
}
}
var selectedRankingSelector: RankingSelector? {
didSet {
update(allowEmptyPseudo: false)
}
}
weak var delegate: RankingViewModelDelegate?
private(set) var status: RankingStatus = .needsUpdate
private(set) var ranks = [DKDriverRankingItem]()
private(set) var driverRank: CurrentDriverRank?
private(set) var rankingTypes = [RankingType]()
private(set) var rankingSelectors = [RankingSelector]()
private(set) var nbDrivers = 0
private let groupName: String?
private let dkRankingTypes: [DKRankingType]
private let dkRankingSelectorType: DKRankingSelectorType
private let rankingDepth: Int
private var useCache = [String: Bool]()
private var initialized = false
private var progressionImageName: String?
private var askForPseudoIfEmpty = true
init(groupName: String?) {
self.groupName = groupName
self.dkRankingTypes = RankingViewModel.sanitizeRankingTypes(DriveKitDriverAchievementUI.shared.rankingTypes)
for (index, rankingType) in self.dkRankingTypes.enumerated() {
switch rankingType {
case .distraction:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.distraction.text(), image: DKImages.distractionFlat.image))
case .ecoDriving:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.ecodriving.text(), image: DKImages.ecoDrivingFlat.image))
case .safety:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.safety.text(), image: DKImages.safetyFlat.image))
case .speeding:
self.rankingTypes.append(RankingType(index: index, name: DKCommonLocalizable.speeding.text(), image: DKImages.speedingFlat.image))
@unknown default:
break
}
}
self.selectedRankingType = self.rankingTypes.first
self.dkRankingSelectorType = RankingViewModel.sanitizeRankingSelectorType(DriveKitDriverAchievementUI.shared.rankingSelector)
switch self.dkRankingSelectorType {
case .none:
break
case let .period(rankingPeriods):
for (index, rankingPeriod) in rankingPeriods.enumerated() {
let titleKey: String
switch rankingPeriod {
case .weekly:
titleKey = "dk_achievements_ranking_week"
case .legacy:
titleKey = "dk_achievements_ranking_legacy"
case .monthly:
titleKey = "dk_achievements_ranking_month"
case .allTime:
titleKey = "dk_achievements_ranking_permanent"
@unknown default:
titleKey = ""
}
self.rankingSelectors.append(RankingSelector(index: index, title: titleKey.dkAchievementLocalized()))
}
}
self.selectedRankingSelector = self.rankingSelectors.first
let rankingDepth = DriveKitDriverAchievementUI.shared.rankingDepth
self.rankingDepth = rankingDepth > 0 ? rankingDepth : 5
self.initialized = true
}
func update(allowEmptyPseudo: Bool) {
if self.initialized {
self.status = .updating
if allowEmptyPseudo || !self.askForPseudoIfEmpty {
self.updateRanking()
} else {
DriveKit.shared.getUserInfo(synchronizationType: .cache) { [weak self] _, userInfo in
if let self = self {
DispatchQueue.main.async { [weak self] in
if let self = self {
if self.askForPseudoIfEmpty && (userInfo?.pseudo?.isCompletelyEmpty() ?? true) {
self.delegate?.updateUserPseudo()
self.askForPseudoIfEmpty = false
} else {
self.updateRanking()
}
}
}
}
}
}
}
}
func clearCache() {
self.useCache.removeAll()
}
private func updateRanking() {
let dkRankingType: DKRankingType
let rankingTypeIndex = self.selectedRankingType?.index ?? 0
if rankingTypeIndex < self.dkRankingTypes.count {
dkRankingType = self.dkRankingTypes[rankingTypeIndex]
} else {
dkRankingType = self.dkRankingTypes.first ?? .safety
}
let dkRankingPeriod: DKRankingPeriod = getRankingPeriod()
self.delegate?.rankingDidUpdate()
let useCacheKey = "\(dkRankingType.rawValue)-\(dkRankingPeriod.rawValue)"
let synchronizationType: SynchronizationType = self.useCache[useCacheKey] == true ? .cache : .defaultSync
DriveKitDriverAchievement.shared.getRanking(rankingType: dkRankingType, rankingPeriod: dkRankingPeriod, rankingDepth: self.rankingDepth, groupName: self.groupName, type: synchronizationType) { [weak self] (rankingSyncStatus, ranking) in
DispatchQueue.main.async {
if let self = self {
self.driverRank = nil
if let ranking = ranking {
var ranks = [DKDriverRankingItem]()
let nbDrivers = ranking.nbDriverRanked
self.nbDrivers = nbDrivers
var previousRank: Int?
for dkRank in ranking.driversRanked.sorted(by: { (dkDriverRank1, dkDriverRank2) -> Bool in
if dkDriverRank2.rank == 0 {
return true
} else if dkDriverRank1.rank == 0 {
return false
} else {
return dkDriverRank1.rank <= dkDriverRank2.rank
}
}) {
if let previousRank = previousRank, previousRank + 1 != dkRank.rank {
ranks.append(JumpDriverRank())
}
let name: String
if let nickname = dkRank.nickname, !nickname.isEmpty {
name = nickname
} else {
name = DKCommonLocalizable.anonymous.text()
}
if dkRank.rank == ranking.userPosition {
let progressionImageName: String?
if let userPreviousPosition = ranking.userPreviousPosition, ranking.userPosition > 0 {
let deltaRank = userPreviousPosition - ranking.userPosition
if deltaRank == 0 {
progressionImageName = nil
} else if deltaRank > 0 {
progressionImageName = "dk_common_ranking_arrow_up"
} else {
progressionImageName = "dk_common_ranking_arrow_down"
}
} else {
progressionImageName = nil
}
self.progressionImageName = progressionImageName
let currentDriverRank = CurrentDriverRank(
nbDrivers: nbDrivers,
position: dkRank.rank,
positionString: String(dkRank.rank),
positionImageName: self.getImageName(fromPosition: dkRank.rank),
rankString: " / \(nbDrivers)",
name: name,
distance: dkRank.distance,
distanceString: dkRank.distance.formatKilometerDistance(),
score: dkRank.score,
scoreString: self.formatScore(dkRank.score),
totalScoreString: " / 10"
)
ranks.append(currentDriverRank)
self.driverRank = currentDriverRank
} else {
let driverRank = DriverRank(
nbDrivers: nbDrivers,
position: dkRank.rank,
positionString: String(dkRank.rank),
positionImageName: self.getImageName(fromPosition: dkRank.rank),
rankString: " / \(nbDrivers)",
name: name,
distance: dkRank.distance,
distanceString: dkRank.distance.formatKilometerDistance(),
score: dkRank.score,
scoreString: self.formatScore(dkRank.score),
totalScoreString: " / 10"
)
ranks.append(driverRank)
}
previousRank = dkRank.rank
}
self.ranks = ranks
} else {
self.nbDrivers = 0
self.ranks = []
}
switch rankingSyncStatus {
case .noError:
self.status = .success
case .userNotRanked:
self.status = .noRankForUser
case .cacheDataOnly, .failedToSyncRanking, .syncAlreadyInProgress:
if ranking != nil {
self.status = .success
} else {
self.status = .networkError
}
@unknown default:
break
}
let dataError: Bool
switch rankingSyncStatus {
case .noError, .userNotRanked:
dataError = false
case .failedToSyncRanking, .syncAlreadyInProgress, .cacheDataOnly:
dataError = true
@unknown default:
dataError = true
}
self.useCache[useCacheKey] = !dataError
self.delegate?.rankingDidUpdate()
}
}
}
}
private func getRankingPeriod() -> DKRankingPeriod {
let dkRankingPeriod: DKRankingPeriod
switch self.dkRankingSelectorType {
case .none:
dkRankingPeriod = .weekly
case let .period(rankingPeriods):
let periodIndex = self.selectedRankingSelector?.index ?? 0
if periodIndex < rankingPeriods.count {
dkRankingPeriod = rankingPeriods[periodIndex]
} else {
dkRankingPeriod = rankingPeriods.first ?? .weekly
}
}
return dkRankingPeriod
}
private func getImageName(fromPosition position: Int) -> String? {
if position >= 1 && position <= 3 {
return "dk_common_rank_\(position)"
} else {
return nil
}
}
private func formatScore(_ score: Double) -> String {
if score >= 10 {
return "10"
} else {
return score.formatDouble(fractionDigits: 2)
}
}
private static func sanitizeRankingTypes(_ rankingTypes: [DKRankingType]) -> [DKRankingType] {
if rankingTypes.isEmpty {
return [.safety]
} else {
var filteredRankingTypes = [DKRankingType]()
var rankingTypesSet: Set<DKRankingType> = []
for rankingType in rankingTypes {
if !rankingTypesSet.contains(rankingType) && rankingType.hasAccess() {
filteredRankingTypes.append(rankingType)
rankingTypesSet.insert(rankingType)
}
}
return filteredRankingTypes
}
}
private static func sanitizeRankingSelectorType(_ selectorType: DKRankingSelectorType) -> DKRankingSelectorType {
switch selectorType {
case .none:
return selectorType
case let .period(rankingPeriods):
return .period(rankingPeriods: sanitizePeriods(rankingPeriods))
}
}
private static func sanitizePeriods(_ rankingPeriods: [DKRankingPeriod]) -> [DKRankingPeriod] {
if rankingPeriods.isEmpty {
return [.weekly]
} else {
var filteredRankingPeriods = [DKRankingPeriod]()
var rankingPeriodsSet: Set<DKRankingPeriod> = []
let managedRankingPeriods: Set<DKRankingPeriod> = Set(DKRankingPeriod.allCases)
for rankingPeriod in rankingPeriods {
if !rankingPeriodsSet.contains(rankingPeriod) && managedRankingPeriods.contains(rankingPeriod) {
filteredRankingPeriods.append(rankingPeriod)
rankingPeriodsSet.insert(rankingPeriod)
}
}
return filteredRankingPeriods
}
}
}
extension DKRankingType {
func hasAccess() -> Bool {
let driveKitAccess = DriveKitAccess.shared
switch self {
case .distraction:
return driveKitAccess.hasAccess(.phoneDistraction)
case .ecoDriving:
return driveKitAccess.hasAccess(.ecoDriving)
case .safety:
return driveKitAccess.hasAccess(.safety)
case .speeding:
return driveKitAccess.hasAccess(.speeding)
@unknown default:
return false
}
}
}
protocol RankingViewModelDelegate: AnyObject {
func rankingDidUpdate()
func updateUserPseudo()
}
extension RankingViewModel: DKDriverRanking {
func getHeaderDisplayType() -> DKRankingHeaderDisplayType {
if rankingSelectors.count > 1 {
return .compact
} else {
return .full
}
}
func getDriverRankingItems() -> [DKDriverRankingItem] {
return ranks
}
func getTitle() -> String {
guard rankingSelectors.count > 0 else {
return ""
}
return selectedRankingType?.name ?? DKCommonLocalizable.safety.text()
}
func getImage() -> UIImage? {
guard rankingSelectors.count > 0 else {
return nil
}
return selectedRankingType?.image ?? DKImages.safetyFlat.image
}
func getProgressionImage() -> UIImage? {
if let progressionImageName = self.progressionImageName {
return UIImage(named: progressionImageName, in: Bundle.driveKitCommonUIBundle, compatibleWith: nil)
} else {
return nil
}
}
func getDriverGlobalRankAttributedText() -> NSAttributedString {
if let driverRank = driverRank {
let driverRankString = driverRank.positionString.dkAttributedString().font(dkFont: .primary, style: .highlightBig).color(.secondaryColor).build()
let rankString = driverRank.rankString.dkAttributedString().font(dkFont: .primary, style: .highlightNormal).color(.mainFontColor).build()
return "%@%@".dkAttributedString().buildWithArgs(driverRankString, rankString)
} else {
let driverRankString = "-".dkAttributedString().font(dkFont: .primary, style: .highlightBig).color(.secondaryColor).build()
let rankString = " / \(nbDrivers)".dkAttributedString().font(dkFont: .primary, style: .highlightNormal).color(.mainFontColor).build()
return "%@%@".dkAttributedString().buildWithArgs(driverRankString, rankString)
}
}
func getScoreTitle() -> String {
return DKCommonLocalizable.rankingScore.text()
}
func hasInfoButton() -> Bool {
return true
}
func infoPopupTitle() -> String? {
return ""
}
func infoPopupMessage() -> String? {
let dkRankingPeriod: DKRankingPeriod = getRankingPeriod()
switch dkRankingPeriod {
case .weekly:
return "dk_achievements_ranking_week_info".dkAchievementLocalized()
case .monthly:
return "dk_achievements_ranking_month_info".dkAchievementLocalized()
case .allTime:
return "dk_achievements_ranking_permanent_info".dkAchievementLocalized()
case .legacy:
return "dk_achievements_ranking_legacy_info".dkAchievementLocalized()
@unknown default:
return nil
}
}
}
|
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.divingapp.Presenter.classes
import android.widget.EditText
import com.example.divingapp.Model.User
import com.example.divingapp.Presenter.Iinterfaces.ILoginPresenter
import com.example.divingapp.View.ILoginView
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
class LoginPresenter(override val loginView: ILoginView) :
ILoginPresenter {
override fun onLogin(email: EditText, password: EditText, firebaseAuth: FirebaseAuth) {
val user = User(email = email.text.toString().trim(), password = password.text.toString().trim())
val loginResult = user.isLoginDataValid()
loginView.makeProgressBarVisible()
if(loginResult) {
firebaseAuth.signInWithEmailAndPassword((user.email) as String, (user.password) as String).addOnCompleteListener(
OnCompleteListener<AuthResult> { task ->
if (task.isSuccessful) {
loginView.makeProgressBarInvisible()
loginView.onLoginResult("Logowanie powiodło się.")
loginView.onSuccessfulLogin(task)
} else {
loginView.makeProgressBarInvisible()
loginView.onLoginResult(task.exception!!.message.toString())
}
})
}
else {
loginView.makeProgressBarInvisible()
if (!user.isEmailValid())
email.error = "E-mail jest niepoprawny."
if (!user.isPasswordValid())
password.error = "To pole nie może być puste."
}
}
}
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.divingapp.Presenter.classes
import android.widget.EditText
import com.example.divingapp.Model.User
import com.example.divingapp.Presenter.Iinterfaces.ILoginPresenter
import com.example.divingapp.View.ILoginView
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
class LoginPresenter(override val loginView: ILoginView) :
ILoginPresenter {
override fun onLogin(email: EditText, password: EditText, firebaseAuth: FirebaseAuth) {
val user = User(email = email.text.toString().trim(), password = password.text.toString().trim())
val loginResult = user.isLoginDataValid()
loginView.makeProgressBarVisible()
if(loginResult) {
firebaseAuth.signInWithEmailAndPassword((user.email) as String, (user.password) as String).addOnCompleteListener(
OnCompleteListener<AuthResult> { task ->
if (task.isSuccessful) {
loginView.makeProgressBarInvisible()
loginView.onLoginResult("Logowanie powiodło się.")
loginView.onSuccessfulLogin(task)
} else {
loginView.makeProgressBarInvisible()
loginView.onLoginResult(task.exception!!.message.toString())
}
})
}
else {
loginView.makeProgressBarInvisible()
if (!user.isEmailValid())
email.error = "E-mail jest niepoprawny."
if (!user.isPasswordValid())
password.error = "To pole nie może być puste."
}
}
}
|
Below is an extract from a Markdown document. Evaluate its educational value, considering both Markdown usage and the content itself. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document uses basic Markdown syntax correctly (e.g., headers, lists, or emphasis), regardless of content.
- Add another point if the document's content has some educational value, even if it's basic or limited in scope. The Markdown usage should be correct but might not be diverse.
- Award a third point if the document demonstrates a good range of Markdown features (e.g., links, images, code blocks) AND the content provides clear, accurate information on a topic. The structure should be logical and easy to follow.
- Give a fourth point if the document is well-suited for teaching both its subject matter and effective Markdown usage. It should use varied Markdown elements to enhance the presentation of educational content, similar to a well-crafted tutorial or lesson.
- Grant a fifth point if the document is exceptional both in its use of Markdown and the educational value of its content. It should demonstrate advanced Markdown features (e.g., tables, task lists, footnotes), have an engaging structure, and provide comprehensive, high-quality educational content on its topic. The document should serve as an excellent example of using Markdown for educational purposes.
The extract:
---
layout: archive
title: "CV"
permalink: /cv/
author_profile: true
redirect_from:
- /resume
---
{% include base_path %}
Education
======
* B.S. in Environmental Sciences, Nankai University, 2009
* M.S. in Environmental Sciences, Louisiana State University, 2011
* Ph.D in Environmental Sciences, Louisiana State University, 2015
Work experience
======
* 2009/6 - 2016/6: Research Assistant
* Louisiana State University
* Graduate Advisor: Professor <NAME>
* 2016/6 - 2017/4: Data Scientist
* DAL (Start-up Company)
* 2017/4 - 2019/8: Research Associate
* University of Southern California
* Director: <NAME>
* 2019/8 - present: Research Scientist
* University of Southern California
* Director: <NAME>
Key Publications
======
<ul>{% for post in site.publications %}
{% include archive-single-cv.html %}
{% endfor %}</ul>
Talks
======
<ul>{% for post in site.talks %}
{% include archive-single-talk-cv.html %}
{% endfor %}</ul>
Teaching
======
<ul>{% for post in site.teaching %}
{% include archive-single-cv.html %}
{% endfor %}</ul>
Service and leadership
======
* Currently signed in to 43 different slack teams
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 |
---
layout: archive
title: "CV"
permalink: /cv/
author_profile: true
redirect_from:
- /resume
---
{% include base_path %}
Education
======
* B.S. in Environmental Sciences, Nankai University, 2009
* M.S. in Environmental Sciences, Louisiana State University, 2011
* Ph.D in Environmental Sciences, Louisiana State University, 2015
Work experience
======
* 2009/6 - 2016/6: Research Assistant
* Louisiana State University
* Graduate Advisor: Professor <NAME>
* 2016/6 - 2017/4: Data Scientist
* DAL (Start-up Company)
* 2017/4 - 2019/8: Research Associate
* University of Southern California
* Director: <NAME>
* 2019/8 - present: Research Scientist
* University of Southern California
* Director: <NAME>
Key Publications
======
<ul>{% for post in site.publications %}
{% include archive-single-cv.html %}
{% endfor %}</ul>
Talks
======
<ul>{% for post in site.talks %}
{% include archive-single-talk-cv.html %}
{% endfor %}</ul>
Teaching
======
<ul>{% for post in site.teaching %}
{% include archive-single-cv.html %}
{% endfor %}</ul>
Service and leadership
======
* Currently signed in to 43 different slack teams
|
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.goodideas.projectcube.data.dto.auth
data class LoginReq(
val email: String = "",
val password: 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>"
|
kotlin
| 2 |
package com.goodideas.projectcube.data.dto.auth
data class LoginReq(
val email: String = "",
val password: String = ""
)
|
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 nmea0183_test
import (
goNMEA "github.com/adrianmo/go-nmea"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/munnik/nmea0183"
)
var _ = Describe("GLL", func() {
var (
parsed GLL
)
Describe("Getting data from a $__GLL sentence", func() {
BeforeEach(func() {
parsed = GLL{
Time: goNMEA.Time{},
Latitude: NewFloat64WithValue(Latitude),
Longitude: NewFloat64WithValue(Longitude),
Validity: goNMEA.ValidGLL,
}
})
Context("When having a parsed sentence", func() {
It("should give a valid position", func() {
lat, lon, _ := parsed.GetPosition2D()
Expect(lat).To(Equal(Latitude))
Expect(lon).To(Equal(Longitude))
})
})
Context("When having a parsed sentence with validity set to invalid", func() {
JustBeforeEach(func() {
parsed.Validity = goNMEA.InvalidGLL
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
Context("When having a parsed sentence with missing longitude", func() {
JustBeforeEach(func() {
parsed.Longitude = NewFloat64()
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
Context("When having a parsed sentence with missing latitude", func() {
JustBeforeEach(func() {
parsed.Latitude = NewFloat64()
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
})
})
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 nmea0183_test
import (
goNMEA "github.com/adrianmo/go-nmea"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/munnik/nmea0183"
)
var _ = Describe("GLL", func() {
var (
parsed GLL
)
Describe("Getting data from a $__GLL sentence", func() {
BeforeEach(func() {
parsed = GLL{
Time: goNMEA.Time{},
Latitude: NewFloat64WithValue(Latitude),
Longitude: NewFloat64WithValue(Longitude),
Validity: goNMEA.ValidGLL,
}
})
Context("When having a parsed sentence", func() {
It("should give a valid position", func() {
lat, lon, _ := parsed.GetPosition2D()
Expect(lat).To(Equal(Latitude))
Expect(lon).To(Equal(Longitude))
})
})
Context("When having a parsed sentence with validity set to invalid", func() {
JustBeforeEach(func() {
parsed.Validity = goNMEA.InvalidGLL
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
Context("When having a parsed sentence with missing longitude", func() {
JustBeforeEach(func() {
parsed.Longitude = NewFloat64()
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
Context("When having a parsed sentence with missing latitude", func() {
JustBeforeEach(func() {
parsed.Latitude = NewFloat64()
})
Specify("an error is returned", func() {
_, _, err := parsed.GetPosition2D()
Expect(err).To(HaveOccurred())
})
})
})
})
|
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:
/* Copyright (c) 2003, <NAME>
* Copyright (c) 2004-2006, <NAME>, <NAME>.
* Copyright (c) 2007-2013, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file torgzip.h
* \brief Headers for torgzip.h
**/
#ifndef TOR_TORGZIP_H
#define TOR_TORGZIP_H
/** Enumeration of what kind of compression to use. Only ZLIB_METHOD is
* guaranteed to be supported by the compress/uncompress functions here;
* GZIP_METHOD may be supported if we built against zlib version 1.2 or later
* and is_gzip_supported() returns true. */
typedef enum {
NO_METHOD=0, GZIP_METHOD=1, ZLIB_METHOD=2, UNKNOWN_METHOD=3
} compress_method_t;
int
tor_gzip_compress(char **out, size_t *out_len,
const char *in, size_t in_len,
compress_method_t method);
int
tor_gzip_uncompress(char **out, size_t *out_len,
const char *in, size_t in_len,
compress_method_t method,
int complete_only,
int protocol_warn_level);
int is_gzip_supported(void);
const char *
tor_zlib_get_version_str(void);
const char *
tor_zlib_get_header_version_str(void);
compress_method_t detect_compression_method(const char *in, size_t in_len);
/** Return values from tor_zlib_process; see that function's documentation for
* details. */
typedef enum {
TOR_ZLIB_OK, TOR_ZLIB_DONE, TOR_ZLIB_BUF_FULL, TOR_ZLIB_ERR
} tor_zlib_output_t;
/** Internal state for an incremental zlib compression/decompression. */
typedef struct tor_zlib_state_t tor_zlib_state_t;
tor_zlib_state_t *tor_zlib_new(int compress, compress_method_t method);
tor_zlib_output_t tor_zlib_process(tor_zlib_state_t *state,
char **out, size_t *out_len,
const char **in, size_t *in_len,
int finish);
void tor_zlib_free(tor_zlib_state_t *state);
#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 |
/* Copyright (c) 2003, <NAME>
* Copyright (c) 2004-2006, <NAME>, <NAME>.
* Copyright (c) 2007-2013, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file torgzip.h
* \brief Headers for torgzip.h
**/
#ifndef TOR_TORGZIP_H
#define TOR_TORGZIP_H
/** Enumeration of what kind of compression to use. Only ZLIB_METHOD is
* guaranteed to be supported by the compress/uncompress functions here;
* GZIP_METHOD may be supported if we built against zlib version 1.2 or later
* and is_gzip_supported() returns true. */
typedef enum {
NO_METHOD=0, GZIP_METHOD=1, ZLIB_METHOD=2, UNKNOWN_METHOD=3
} compress_method_t;
int
tor_gzip_compress(char **out, size_t *out_len,
const char *in, size_t in_len,
compress_method_t method);
int
tor_gzip_uncompress(char **out, size_t *out_len,
const char *in, size_t in_len,
compress_method_t method,
int complete_only,
int protocol_warn_level);
int is_gzip_supported(void);
const char *
tor_zlib_get_version_str(void);
const char *
tor_zlib_get_header_version_str(void);
compress_method_t detect_compression_method(const char *in, size_t in_len);
/** Return values from tor_zlib_process; see that function's documentation for
* details. */
typedef enum {
TOR_ZLIB_OK, TOR_ZLIB_DONE, TOR_ZLIB_BUF_FULL, TOR_ZLIB_ERR
} tor_zlib_output_t;
/** Internal state for an incremental zlib compression/decompression. */
typedef struct tor_zlib_state_t tor_zlib_state_t;
tor_zlib_state_t *tor_zlib_new(int compress, compress_method_t method);
tor_zlib_output_t tor_zlib_process(tor_zlib_state_t *state,
char **out, size_t *out_len,
const char **in, size_t *in_len,
int finish);
void tor_zlib_free(tor_zlib_state_t *state);
#endif
|
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
FFTW3_HOME="/u/local/apps/fftw3/current"
echo $FFTW_HOME
. /u/local/Modules/default/init/modules.sh
module load intel/13.cs
module load gcc/4.9.3
g++ -static -std=c++11 main_proj_2.cpp -o main_proj_2 -I$FFTW3_HOME/include -L$FFTW3_HOME/lib -lfftw3 -lm
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
shell
| 2 |
#!/bin/bash
FFTW3_HOME="/u/local/apps/fftw3/current"
echo $FFTW_HOME
. /u/local/Modules/default/init/modules.sh
module load intel/13.cs
module load gcc/4.9.3
g++ -static -std=c++11 main_proj_2.cpp -o main_proj_2 -I$FFTW3_HOME/include -L$FFTW3_HOME/lib -lfftw3 -lm
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.torana.biz;
import java.util.Map;
/**
* @author bhanuchander
* @version 2.0
* @since 26th Jun 2014
* */
public interface ServiceManager {
String SERVICE_MANAGER = "serviceManager";
public Map<String, Object> getServicesMap();
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package com.torana.biz;
import java.util.Map;
/**
* @author bhanuchander
* @version 2.0
* @since 26th Jun 2014
* */
public interface ServiceManager {
String SERVICE_MANAGER = "serviceManager";
public Map<String, Object> getServicesMap();
}
|
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 hsp_acct_study_id,
sp.specialty
FROM features.bayes_vw_index_admissions
JOIN hospital_account acc USING (hsp_acct_study_id)
LEFT JOIN providers prov
ON prov.prov_study_id = acc.attending_prov_study_id
LEFT JOIN provider_specialty sp
ON sp.prov_study_id = acc.attending_prov_study_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
| 2 |
SELECT hsp_acct_study_id,
sp.specialty
FROM features.bayes_vw_index_admissions
JOIN hospital_account acc USING (hsp_acct_study_id)
LEFT JOIN providers prov
ON prov.prov_study_id = acc.attending_prov_study_id
LEFT JOIN provider_specialty sp
ON sp.prov_study_id = acc.attending_prov_study_id
|
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:
module.exports = [
'Tanned',
'Yellow',
'Pale',
'Light',
'Brown',
'DarkBrown',
'Black'
]
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 |
module.exports = [
'Tanned',
'Yellow',
'Pale',
'Light',
'Brown',
'DarkBrown',
'Black'
]
|
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 modalBtn = document.querySelector('.modal-btn');
const modalBg = document.querySelector('.modal-bg');
const modalClose = document.querySelector('.modal-close');
const scrollIndicator = document.querySelector('#scrollIndicator');
// modalBtn.addEventListener('click', function () {
// modalBg.classList.add('bg-active');
// });
modalClose.addEventListener('click', function () {
modalBg.classList.remove('bg-active');
});
// scroll indicator bar
window.onscroll = function () {
// how far I scroll (by pixels);
let winScroll = document.body.scrollTop || document.documentElement.scrollTop;
console.log('winScroll = ' + winScroll);
console.log('winScroll rounded' + Math.round(winScroll));
// the full page scrollable height
let fullScreenHeight =
document.documentElement.scrollHeight -
document.documentElement.clientHeight;
console.log('full page height = ' + fullScreenHeight);
// the percentage we've scrolled
let scrolled = (winScroll * 100) / fullScreenHeight;
console.log('scrolled percentage = ' + scrolled);
// update the progress bar
scrollIndicator.style['width'] = scrolled + '%';
// show a modal after scrolling half the height of the page
if (winScroll > fullScreenHeight / 2) {
if (modalBg.getAttribute('displayed') === 'false') {
modalBg.setAttribute('displayed', 'true');
modalBg.classList.add('bg-active');
}
}
};
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 modalBtn = document.querySelector('.modal-btn');
const modalBg = document.querySelector('.modal-bg');
const modalClose = document.querySelector('.modal-close');
const scrollIndicator = document.querySelector('#scrollIndicator');
// modalBtn.addEventListener('click', function () {
// modalBg.classList.add('bg-active');
// });
modalClose.addEventListener('click', function () {
modalBg.classList.remove('bg-active');
});
// scroll indicator bar
window.onscroll = function () {
// how far I scroll (by pixels);
let winScroll = document.body.scrollTop || document.documentElement.scrollTop;
console.log('winScroll = ' + winScroll);
console.log('winScroll rounded' + Math.round(winScroll));
// the full page scrollable height
let fullScreenHeight =
document.documentElement.scrollHeight -
document.documentElement.clientHeight;
console.log('full page height = ' + fullScreenHeight);
// the percentage we've scrolled
let scrolled = (winScroll * 100) / fullScreenHeight;
console.log('scrolled percentage = ' + scrolled);
// update the progress bar
scrollIndicator.style['width'] = scrolled + '%';
// show a modal after scrolling half the height of the page
if (winScroll > fullScreenHeight / 2) {
if (modalBg.getAttribute('displayed') === 'false') {
modalBg.setAttribute('displayed', 'true');
modalBg.classList.add('bg-active');
}
}
};
|
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">
<meta name="viewport" content="width=device-width, maximum-scale=1.0">
<meta name="description" content="Ubrigens is a small site dedicated to all things Infosec.">
<title>Ubrigens | Demystifying iOS App Cracking</title>
<link rel="stylesheet" type="text/css" href="../assets/css/default.css" />
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
<!-- <script src="/assets/js/main.js"></script> -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-58005603-2', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<link rel="shortcut icon" type="image/png" href="../assets/images/favicon.png">
<link rel="shortcut icon" type="image/png" href="https://ubrigens.com/assets/images/favicon.png" !>
</head>
<body>
<div id="page" class="cf">
<div id="header" class="cf">
<a href="../" class="logo">Ü</a>
<ul class="nav cf">
<li><a href="../">Home</a></li>
<li><a href="../about.html">About</a></li>
</ul>
</div>
<div id="content"><div class="post">
<h2>
Demystifying iOS App Cracking
<span class="date">June 16, 2015</span>
</h2>
<p>This article is not a guide on how to crack iOS applications. It merely tries to explain the techniques used to circumvent the iOS DRM system. I do not in any way condone piracy.</p>
<hr />
<p>iOS apps come in packages with the filename extension <em>.ipa</em>. These packages are just renamed zip archives, and can easily be unpacked using appropriate tools. The resulting directory tr
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1.0">
<meta name="description" content="Ubrigens is a small site dedicated to all things Infosec.">
<title>Ubrigens | Demystifying iOS App Cracking</title>
<link rel="stylesheet" type="text/css" href="../assets/css/default.css" />
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
<!-- <script src="/assets/js/main.js"></script> -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-58005603-2', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<link rel="shortcut icon" type="image/png" href="../assets/images/favicon.png">
<link rel="shortcut icon" type="image/png" href="https://ubrigens.com/assets/images/favicon.png" !>
</head>
<body>
<div id="page" class="cf">
<div id="header" class="cf">
<a href="../" class="logo">Ü</a>
<ul class="nav cf">
<li><a href="../">Home</a></li>
<li><a href="../about.html">About</a></li>
</ul>
</div>
<div id="content"><div class="post">
<h2>
Demystifying iOS App Cracking
<span class="date">June 16, 2015</span>
</h2>
<p>This article is not a guide on how to crack iOS applications. It merely tries to explain the techniques used to circumvent the iOS DRM system. I do not in any way condone piracy.</p>
<hr />
<p>iOS apps come in packages with the filename extension <em>.ipa</em>. These packages are just renamed zip archives, and can easily be unpacked using appropriate tools. The resulting directory tree is of little interest to us here and has been documented elsewhere <a href="https://en.wikipedia.org/wiki/.ipa_(file_extension)">[1,</a> <a href="https://www.theiphonewiki.com/wiki/IPA_File_Format">2]</a>.</p>
<p>For a cracker the most interesting file is the executable, which can be found by inspecting the <code>Info.plist</code> file, specifically be looking up the value for the <code>CFBundleExecutable</code> key. Today, most binaries contain code for multiple architectures. Such files are called <em>fat</em> binaries, stemming from the fact that they contain code for multiple architectures like <em>ARMv7</em>, <em>ARMv7s</em> and <em>ARM64</em> (also known as <em>ARMv8</em>). On the Mac, the same concept is used, but the code inside such binaries typically targets Intel’s 32- and 64-bit processors.</p>
<p>At runtime, the dynamic linker (almost always <em>dyld</em>) will examine the file, determine the best architecture to run, process all load commands and then proceeds to execute the chosen slice. More information on the file format - <em>MachO</em> - and information on the various load commands can be found on Apple’s website <a href="https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/MachORuntime/index.html">[3]</a>.</p>
<figure>
<img src="../assets/images/blackbox_decryption.svg" alt="Architecture selection at runtime" /><figcaption>Architecture selection at runtime</figcaption>
</figure>
<p>Essentially, the OS kernel can be treated as a black box that automatically decrypts part of the supplied binary - The part that runs <em>best</em> on the available hardware. In this case, <code>posix_spawn</code> was chosen to launch the process, but any other similar function will do. To simplify things, the figure ignores the fact that only the decrypted portion is present in memory after launch.</p>
<p>On iOS, all third-party code must be code-signed by a valid developer ID. The code signature is specified as a load command just after the MachO header, so each <em>slice</em> - rather than the whole fat binary - has its own code signature. The signature is validated by the kernel, and apps with an invalid signature are killed immediately. On non-jailbroken devices, the integrity of the application bundle is ensured by the OS. On jailbroken devices, most of an apps’ contents are allowed to change, since critical security features are gone. Still, a code signature must be present for code to run - however, in this case, a pseudo signatures like those produced by <em>jtool</em> and <em>ldid</em> suffice.</p>
<p>Popular cracking tools such as <em>Clutch</em> <a href="https://github.com/KJCracks/Clutch">[4]</a> use an ugly workaround to crack as many slices of an iOS binary as possible: Let’s say an app contains code for all three architectures mentioned above. <em>Clutch</em> is then going to patch the header of the executable three times, each time forcing the operating system to execute a different slice. Obviously this only works if the device can execute the slice, meaning that an iPhone 6 can be used to create cracks containing decrypted copies of all three architectures, whereas an iPhone 4S can only decrypt the <em>ARMv7</em> portion.</p>
<p>Here is the process visualized. Again, the device in question is an iPhone 5.</p>
<figure>
<img src="../assets/images/clutch.svg" alt="Clutch on iPhone 5" /><figcaption>Clutch on iPhone 5</figcaption>
</figure>
<p>In this case, the original binary contains three slices for different architectures. Because we are on iPhone 5 which uses a <em>ARMv7s</em> compatible CPU, normally only the corresponding slice would be executed. <em>Clutch</em> abuses the fact that ARM processors are generally backwards compatible, meaning devices capable of running <em>ARMv7s</em> code can also execute <em>ARMv7</em> code. In total, <em>Clutch</em> executes the app twice, once for each supported architecture. In order to force the operating system to execute a specific slice, all other slices are set to contain Intel code.</p>
<p>Each slice is dumped by first spawning the new process using <code>posix_spawn</code> in a suspended state. This is accomplished by using the Apple only flag <code>POSIX_SPAWN_START_SUSPENDED</code>. No code by the application is ever executed, but the slice in question is automatically decrypted by the OS. Next, after aquiring the mach port for the spawned process using <code>task_for_pid</code>, its memory is copied to disk. Lastly, headers are patched where necessary (for example the <code>LC_ENCRYPTION_COMMAND</code> needs to be updated to reflect the fact that the new binary is no longer encrypted) and the processing of the next slice begins. If you are interested in the implementation details, check out the source code <a href="https://github.com/KJCracks/Clutch">[4]</a>.</p>
<p>Finally, the decrypted pieces are combined into a new binary. Because the iPhone 5 does not support <em>ARM64</em>, the output only contains two slices. Still, the binary runs on iPhone 6 - albeit possibly a tiny bit slower.</p>
<p>It is important for developers to understand how this process works. Although the public opinion is largely shaped by discussions about piracy, there are also legitimate uses for app cracking: Penetration testers looking for vulnerabilities in a clients’ app or developers working on <em>reproducible builds</em> <a href="https://github.com/WhisperSystems/Signal-iOS/issues/641">[5]</a>. There are profound implications for what I’ve written in here when we take into consideration <em>App Thinning</em> and <em>Bitcode</em>.<del>, which will be the topic of my next article! Stay tuned!</del></p>
<p>I am not going to get around to write an entire article on this topic, so here is the gist of it:</p>
<p><em>App Thinning</em> results in binaries that only contain one architecture, forcing crackers to use multiple devices to crack each individual slice and then manually combine them to create a version that runs on as many devices as possible. <em>Bitcode</em> on the other hand could allow Apple to create personalized versions of apps, allowing them to trace accounts that distribute cracked versions of an app (fittingly referred to as <em>traitor tracing</em>). If used, both technologies will hopefully reduce the impact of application cracking on the revenue of iOS developers.</p>
<hr />
<p>Changelog:</p>
<ul>
<li>June 17, 2015: Fixed date, changed title to better reflect the contents of this article.</li>
<li>September 10, 2015: Added disclaimer, added section on impact of <em>App Thinning</em> and <em>Bitcode</em> in iOS 9</li>
<li>November 1, 2018: Updated parts of the article.</li>
</ul>
</div>
</div>
<div id="footer">
Site created using <a target="_blank" href="http://jaspervdj.be/hakyll">Hakyll</a>. <a target="_blank" href="../atom.xml">Subscribe</a>.
</div>
</div>
</body>
</html>
|
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:
#pragma once
#include <qdialog.h>
#include "ui_SetTime.h"
class SetTimeWidget :
public QDialog
{
Q_OBJECT
public:
SetTimeWidget(QDialog* parent = NULL);
Ui::SetTimeWidget ui;
};
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 |
#pragma once
#include <qdialog.h>
#include "ui_SetTime.h"
class SetTimeWidget :
public QDialog
{
Q_OBJECT
public:
SetTimeWidget(QDialog* parent = NULL);
Ui::SetTimeWidget ui;
};
|
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:
# pick_and_place
rosrun keyboard keyboard
calibration:
in keyboard window hit 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>"
|
markdown
| 2 |
# pick_and_place
rosrun keyboard keyboard
calibration:
in keyboard window hit c
|
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 "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<curses.h>
#include<Windows.h>
#include "battle.h"
#include<time.h>
int x = 120;
int y = 30;
char ab[300][300];
void block1(int a, int b, int c, int d);
void tate(int a, int b, int ichi);
void yoko(int a, int b, int ichi);
void create(int dangion_number);
int main(int argc, char *argv[])
{
// 初期化
int a = 0;
int b = 0;
int px = 60;
int py = 15;
int j;
int i;
int key;
initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
for (int i = 0; i < 300; i++) {
for (int j = 0; j < 300; j++) {
ab[i][j] = '#';
}
}
create(2);
int count = 0;
while (true) {
erase();
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 120; j++) {
mvaddch(i, j, ab[i-a][j-b]);
}
}
mvprintw(15, 60, "@");
key = getch();
srand((unsigned)time(NULL));
int random = 0;
int mnumber = 0;
switch (key) {
case KEY_UP:
/* if (py == 226 && (150<px&&170>px) {
erase();
Battle(3);
}*/
//else {
if (ab[py - 1][px] != '#') {
a++;
py--;
random = rand()%8;
if (random == 7) {
mnumber = rand() % 2;
erase();
Battle(mnumber);
}
}
// }
break;
case KEY_DOWN:
if (ab[py + 1][px] != '#') {
a--;
py++;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 2;
erase();
Battle(mnumber);
}
}
break;
case KEY_RIGHT:
if (px == 250 && (py > 80 && py < 170)) {
erase();
Battle(1);
}
else {
if (ab[py][px + 1] != '#') {
b--;
px++;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 3;
erase();
Battle(mnumber);
}
}
}
break;
case KEY_LEFT:
if (ab[py][px - 1] != '#') {
b++;
px--;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 3;
erase();
Battle(mnumber);
}
}
break;
}
refresh();
// 1秒待機
}
return 0
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
cpp
| 2 |
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<curses.h>
#include<Windows.h>
#include "battle.h"
#include<time.h>
int x = 120;
int y = 30;
char ab[300][300];
void block1(int a, int b, int c, int d);
void tate(int a, int b, int ichi);
void yoko(int a, int b, int ichi);
void create(int dangion_number);
int main(int argc, char *argv[])
{
// 初期化
int a = 0;
int b = 0;
int px = 60;
int py = 15;
int j;
int i;
int key;
initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
for (int i = 0; i < 300; i++) {
for (int j = 0; j < 300; j++) {
ab[i][j] = '#';
}
}
create(2);
int count = 0;
while (true) {
erase();
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 120; j++) {
mvaddch(i, j, ab[i-a][j-b]);
}
}
mvprintw(15, 60, "@");
key = getch();
srand((unsigned)time(NULL));
int random = 0;
int mnumber = 0;
switch (key) {
case KEY_UP:
/* if (py == 226 && (150<px&&170>px) {
erase();
Battle(3);
}*/
//else {
if (ab[py - 1][px] != '#') {
a++;
py--;
random = rand()%8;
if (random == 7) {
mnumber = rand() % 2;
erase();
Battle(mnumber);
}
}
// }
break;
case KEY_DOWN:
if (ab[py + 1][px] != '#') {
a--;
py++;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 2;
erase();
Battle(mnumber);
}
}
break;
case KEY_RIGHT:
if (px == 250 && (py > 80 && py < 170)) {
erase();
Battle(1);
}
else {
if (ab[py][px + 1] != '#') {
b--;
px++;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 3;
erase();
Battle(mnumber);
}
}
}
break;
case KEY_LEFT:
if (ab[py][px - 1] != '#') {
b++;
px--;
random = rand() % 8;
if (random == 7) {
mnumber = rand() % 3;
erase();
Battle(mnumber);
}
}
break;
}
refresh();
// 1秒待機
}
return 0;
}
void block1(int a, int b, int c, int d) {
int i, j;
for (j = a; j < b; j++) {
for (i = c; i < d; i++) {
ab[j][i] = ' ';
}
}
}
void tate(int a, int b,int ichi) {
int i;
for (i = a; i < b; i++) {
ab[i][ichi] = ' ';
}
}
void yoko(int a, int b, int ichi) {
int i;
for (i = a; i < b; i++) {
ab[ichi][i] = ' ';
}
}
void create(int dangion_number) {
if (dangion_number == 1) {
block1(15, 30, 60, 140); //1
block1(110, 140, 100, 150); //2
block1(160, 200, 50, 100);//4
block1(170, 220, 145, 180);//5
block1(130, 150, 160, 200);//6
block1(15, 100, 170, 220);//7
block1(140, 180, 250, 270);//8
block1(230, 260, 220, 270);//9
tate(30, 110, 120);
yoko(150, 160, 135);
tate(150, 160, 170);
yoko(150, 171, 160);
tate(160, 170, 150);
yoko(70, 110, 120);
tate(120, 160, 70);
yoko(140, 170, 25);
yoko(220, 260, 55);
tate(55, 140, 260);
tate(180, 200, 260);
yoko(245, 261, 200);
tate(200, 231, 245);
tate(260, 286, 250);
yoko(160, 251, 285);
tate(270, 285, 160);
block1(222, 270, 150, 170);//10
for (int i = 158; i < 163; i++) {
ab[224][i] = 'X';
}
ab[225][158] = 'X'; ab[225][159] = 'o'; ab[225][160] = 'X'; ab[225][161] = 'o'; ab[225][162] = 'X';
ab[226][158] = 'X'; ab[226][162] = 'X';
for (int i = 159; i < 162; i++) {
ab[226][i] = '_';
}
for (int i = 158; i < 163; i++) {
ab[227][i] = 'X';
}
/*XXXXX
XoXoX
X___X
XXXXX*/
}
else if (dangion_number == 2) {
block1(15, 40, 60, 70);//1
yoko(60, 75, 30);
block1(20, 80, 75, 90);//2
tate(80, 100, 75);
block1(100, 130, 70, 90);//3
yoko(90, 100, 110);
block1(100, 180, 35, 45);//4
tate(130, 150, 80);
block1(150, 175, 60, 130);//5
tate(175, 220, 110);
yoko(110, 130, 220);
block1(190, 230, 130, 200);//6
yoko(90, 140, 110);
block1(100, 130, 140, 210);//7
tate(50, 150, 175);
yoko(175, 241, 50);
yoko(175, 241, 150);
tate(50, 150, 240);
yoko(240, 250, 110);
block1(80, 170, 250, 270);//8
for (int i = 108; i < 113; i++) {
if (i != 110) {
ab[i][261] = '{';
ab[i][262] = '}';
}
}
for (int i = 261; i < 268; i++) {
ab[110][i] = '=';
}
ab[110][260] = 'O';
/* {}
{}
O=======
{}
{}*/
}
}
|
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 'test_helper'
class MecanicaConsejerosControllerTest < ActionDispatch::IntegrationTest
setup do
@mecanica_consejero = mecanica_consejeros(:one)
end
test "should get index" do
get mecanica_consejeros_url
assert_response :success
end
test "should get new" do
get new_mecanica_consejero_url
assert_response :success
end
test "should create mecanica_consejero" do
assert_difference('MecanicaConsejero.count') do
post mecanica_consejeros_url, params: { mecanica_consejero: { nombre: @mecanica_consejero.nombre } }
end
assert_redirected_to mecanica_consejero_url(MecanicaConsejero.last)
end
test "should show mecanica_consejero" do
get mecanica_consejero_url(@mecanica_consejero)
assert_response :success
end
test "should get edit" do
get edit_mecanica_consejero_url(@mecanica_consejero)
assert_response :success
end
test "should update mecanica_consejero" do
patch mecanica_consejero_url(@mecanica_consejero), params: { mecanica_consejero: { nombre: @mecanica_consejero.nombre } }
assert_redirected_to mecanica_consejero_url(@mecanica_consejero)
end
test "should destroy mecanica_consejero" do
assert_difference('MecanicaConsejero.count', -1) do
delete mecanica_consejero_url(@mecanica_consejero)
end
assert_redirected_to mecanica_consejeros_url
end
end
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
ruby
| 1 |
require 'test_helper'
class MecanicaConsejerosControllerTest < ActionDispatch::IntegrationTest
setup do
@mecanica_consejero = mecanica_consejeros(:one)
end
test "should get index" do
get mecanica_consejeros_url
assert_response :success
end
test "should get new" do
get new_mecanica_consejero_url
assert_response :success
end
test "should create mecanica_consejero" do
assert_difference('MecanicaConsejero.count') do
post mecanica_consejeros_url, params: { mecanica_consejero: { nombre: @mecanica_consejero.nombre } }
end
assert_redirected_to mecanica_consejero_url(MecanicaConsejero.last)
end
test "should show mecanica_consejero" do
get mecanica_consejero_url(@mecanica_consejero)
assert_response :success
end
test "should get edit" do
get edit_mecanica_consejero_url(@mecanica_consejero)
assert_response :success
end
test "should update mecanica_consejero" do
patch mecanica_consejero_url(@mecanica_consejero), params: { mecanica_consejero: { nombre: @mecanica_consejero.nombre } }
assert_redirected_to mecanica_consejero_url(@mecanica_consejero)
end
test "should destroy mecanica_consejero" do
assert_difference('MecanicaConsejero.count', -1) do
delete mecanica_consejero_url(@mecanica_consejero)
end
assert_redirected_to mecanica_consejeros_url
end
end
|
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:
RSpec.describe ServiceUpdater do
subject(:service_updater) { described_class.new(latest_metadata) }
describe '#create_flow' do
let(:latest_metadata) { metadata_fixture('no_flow_service') }
before do
service_updater.create_flow
end
context 'creating flow objects from existing pages' do
let(:valid) { true }
let(:service_flow) do
{
'cf6dc32f-502c-4215-8c27-1151a45735bb' => {
'_type' => 'flow.page',
'next' => {
'default' => '9e1ba77f-f1e5-42f4-b090-437aa9af7f73'
}
},
'9e1ba77f-f1e5-42f4-b090-437aa9af7f73' => {
'_type' => 'flow.page',
'next' => {
'default' => 'df1ba645-f748-46d0-ad75-f34112653e37'
}
},
'df1ba645-f748-46d0-ad75-f34112653e37' => {
'_type' => 'flow.page',
'next' => {
'default' => '4b8c6bf3-878a-4446-9198-48351b3e2185'
}
},
'4b8c6bf3-878a-4446-9198-48351b3e2185' => {
'_type' => 'flow.page',
'next' => {
'default' => 'e337070b-f636-49a3-a65c-f506675265f0'
}
},
'e337070b-f636-49a3-a65c-f506675265f0' => {
'_type' => 'flow.page',
'next' => {
'default' => '778e364b-9a7f-4829-8eb2-510e08f156a3'
}
},
'778e364b-9a7f-4829-8eb2-510e08f156a3' => {
'_type' => 'flow.page',
'next' => {
'default' => ''
}
}
}
end
it 'creates the flow objects in the same order as the pages' do
page_uuids = latest_metadata['pages'].map { |page| page['_uuid'] }
flow_uuids = service_updater.latest_metadata['flow'].keys
expect(page_uuids).to eq(flow_uuids)
end
it 'creates the correct flow object structure' do
expect(service_updater.latest_metadata['flow']).to eq(service_f
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 |
RSpec.describe ServiceUpdater do
subject(:service_updater) { described_class.new(latest_metadata) }
describe '#create_flow' do
let(:latest_metadata) { metadata_fixture('no_flow_service') }
before do
service_updater.create_flow
end
context 'creating flow objects from existing pages' do
let(:valid) { true }
let(:service_flow) do
{
'cf6dc32f-502c-4215-8c27-1151a45735bb' => {
'_type' => 'flow.page',
'next' => {
'default' => '9e1ba77f-f1e5-42f4-b090-437aa9af7f73'
}
},
'9e1ba77f-f1e5-42f4-b090-437aa9af7f73' => {
'_type' => 'flow.page',
'next' => {
'default' => 'df1ba645-f748-46d0-ad75-f34112653e37'
}
},
'df1ba645-f748-46d0-ad75-f34112653e37' => {
'_type' => 'flow.page',
'next' => {
'default' => '4b8c6bf3-878a-4446-9198-48351b3e2185'
}
},
'4b8c6bf3-878a-4446-9198-48351b3e2185' => {
'_type' => 'flow.page',
'next' => {
'default' => 'e337070b-f636-49a3-a65c-f506675265f0'
}
},
'e337070b-f636-49a3-a65c-f506675265f0' => {
'_type' => 'flow.page',
'next' => {
'default' => '778e364b-9a7f-4829-8eb2-510e08f156a3'
}
},
'778e364b-9a7f-4829-8eb2-510e08f156a3' => {
'_type' => 'flow.page',
'next' => {
'default' => ''
}
}
}
end
it 'creates the flow objects in the same order as the pages' do
page_uuids = latest_metadata['pages'].map { |page| page['_uuid'] }
flow_uuids = service_updater.latest_metadata['flow'].keys
expect(page_uuids).to eq(flow_uuids)
end
it 'creates the correct flow object structure' do
expect(service_updater.latest_metadata['flow']).to eq(service_flow)
end
it 'creates valid service metadata' do
expect(
MetadataPresenter::ValidateSchema.validate(
service_updater.latest_metadata, 'service.base'
)
).to be(valid)
end
end
end
describe '#update' do
let(:service_id) { latest_metadata['service_id'] }
let(:latest_metadata) { metadata_fixture('no_flow_service') }
before do
expect(
MetadataApiClient::Version
).to receive(:create).with(
service_id: service_id,
payload: latest_metadata
).and_return(version)
end
context 'when there are no errors' do
let(:version) { double(errors?: false, errors: [], metadata: latest_metadata) }
it 'sends the metadata to the metadata api' do
service_updater.update
end
end
context 'when there are errors' do
let(:version) { double(errors?: true, errors: ['some error'], metadata: latest_metadata) }
it 'return false' do
expect(service_updater.update).to be_falsey
end
end
end
end
|
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 __TB_PointMatch_h__
#define __TB_PointMatch_h__
#include <map>
#include <GU/GU_Detail.h>
#include <UT/UT_SplayTree.h>
#include <GEO/GEO_Point.h>
#include <UT/UT_Vector3.h>
/// This is a basic infrastructure for finding correspondence between geometries.
/// At first we'd like to match points via points' ids, but I'm thinking also
/// about adding another options (see bellow TB_CORR_TYPES for a hint).
/// The main idea is to replace point access in Interpolants classes:
/// FOR_ALL_GPOINTS() {...
/// nextppt = gdp->points()p[i] ...}
///
/// with a method of TB_PointMatch:
/// TB_PointMatch * pm = TB_PointMatch(gdp);
/// pm->matchAttribute(id, *ppt);
///
/// where idx could be particle id for example.
///
/// Even better TB_PointMatch interface should allow to return
/// positions of a virtual point instead of an actual point, since
/// some of the methods may base on fitting displacements of non-equal
/// geometries.
namespace TimeBlender
{
/// Types for building geometry correspondence.
/// Currently only CORR_POINT_ID is implemented.
typedef enum {
CORR_POINT_ID,
CORR_UV_SPACE,
CORR_SPHERICAL_SPACE,
CORR_TEATRA_MATCH,
} TB_CORR_TYPES;
/// Node typedef for STL map (red/black tree):
typedef std::map<int, GEO_Point*> Tree;
/// TODO: This should be plain structre?
class TB_SplayNode
{
public:
TB_SplayNode();
TB_SplayNode(int i) {id=i;};
TB_SplayNode(int i, const GEO_Point *p) {id=i; ppt=p;};
int id;
const GEO_Point * ppt;
};
/// I'm removing Splay tree from here, since they're not optimial for
/// this kind of queries (with no coherence between sequantial searches)
/// and additionally not thread safe at access (important as we'd like to expose
/// point match in VEX). Generally speaking using Splay Tree here had
/// no sense at all.
class TB_PointMatch
{
public:
/// Requires initialization:
TB_PointMatch() {};
/// Deallocate splay tree on exit:
~TB_PointMatch() {
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 __TB_PointMatch_h__
#define __TB_PointMatch_h__
#include <map>
#include <GU/GU_Detail.h>
#include <UT/UT_SplayTree.h>
#include <GEO/GEO_Point.h>
#include <UT/UT_Vector3.h>
/// This is a basic infrastructure for finding correspondence between geometries.
/// At first we'd like to match points via points' ids, but I'm thinking also
/// about adding another options (see bellow TB_CORR_TYPES for a hint).
/// The main idea is to replace point access in Interpolants classes:
/// FOR_ALL_GPOINTS() {...
/// nextppt = gdp->points()p[i] ...}
///
/// with a method of TB_PointMatch:
/// TB_PointMatch * pm = TB_PointMatch(gdp);
/// pm->matchAttribute(id, *ppt);
///
/// where idx could be particle id for example.
///
/// Even better TB_PointMatch interface should allow to return
/// positions of a virtual point instead of an actual point, since
/// some of the methods may base on fitting displacements of non-equal
/// geometries.
namespace TimeBlender
{
/// Types for building geometry correspondence.
/// Currently only CORR_POINT_ID is implemented.
typedef enum {
CORR_POINT_ID,
CORR_UV_SPACE,
CORR_SPHERICAL_SPACE,
CORR_TEATRA_MATCH,
} TB_CORR_TYPES;
/// Node typedef for STL map (red/black tree):
typedef std::map<int, GEO_Point*> Tree;
/// TODO: This should be plain structre?
class TB_SplayNode
{
public:
TB_SplayNode();
TB_SplayNode(int i) {id=i;};
TB_SplayNode(int i, const GEO_Point *p) {id=i; ppt=p;};
int id;
const GEO_Point * ppt;
};
/// I'm removing Splay tree from here, since they're not optimial for
/// this kind of queries (with no coherence between sequantial searches)
/// and additionally not thread safe at access (important as we'd like to expose
/// point match in VEX). Generally speaking using Splay Tree here had
/// no sense at all.
class TB_PointMatch
{
public:
/// Requires initialization:
TB_PointMatch() {};
/// Deallocate splay tree on exit:
~TB_PointMatch() { delete tree;}
/// Alloc wiht parameters:
TB_PointMatch(GU_Detail * gdp, int correspond)
{
if (!initialize(gdp, correspond)) alloc = false;
}
/// Initilialize splay tree:
int initialize(GU_Detail *, int correspond);
/// Find corresponding point based on provided ID,
/// and assing finding to GEO_Point *.
GEO_Point * find(int d);
/// Get to the raw tree.
Tree * getTree() {return tree;}
/// Tree entries == npoints.
int entries() const {return (int)tree->size();}
/// Are we ready for searach.
bool isAlloc() {return alloc;}
private:
bool alloc;
Tree * tree;
const GU_Detail * detail;
};
} // End of Timeblender namespace
#endif
|
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 (
"github.com/gin-gonic/gin"
"net/http"
)
//初识 gin
//命令行测试
//curl -X GET "http://127.0.0.1:8080/ping"
func main(){
r:=gin.Default()
r.GET("/ping",func(c *gin.Context){
c.JSON(http.StatusOK,gin.H{
"msg":"pong",
})
})
r.Run(":8080")//默认是8080
}
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 (
"github.com/gin-gonic/gin"
"net/http"
)
//初识 gin
//命令行测试
//curl -X GET "http://127.0.0.1:8080/ping"
func main(){
r:=gin.Default()
r.GET("/ping",func(c *gin.Context){
c.JSON(http.StatusOK,gin.H{
"msg":"pong",
})
})
r.Run(":8080")//默认是8080
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package com.ridho.anindroid.intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class Sub2Activity extends ActionBarActivity {
public static String KEY_DATA = "data";
private String receiveData = null;
private TextView txtData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub2);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
txtData = (TextView)findViewById(R.id.txt_data);
receiveData = getIntent().getStringExtra(KEY_DATA);
txtData.setText(receiveData);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
}
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 com.ridho.anindroid.intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class Sub2Activity extends ActionBarActivity {
public static String KEY_DATA = "data";
private String receiveData = null;
private TextView txtData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub2);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
txtData = (TextView)findViewById(R.id.txt_data);
receiveData = getIntent().getStringExtra(KEY_DATA);
txtData.setText(receiveData);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
}
|
Below is an extract from a Java program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid Java code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical Java concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., concurrent programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching Java. It should be similar to a school exercise, a tutorial, or a Java course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching Java. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
package br.dmoura.dhouse.java.revisao.orientacaoobjeto;
public class Cliente extends Pessoa {
private int codigo;
public int getCodigo() {
return codigo;
}
public void setCodigo(int novoCodigo) {
codigo = novoCodigo;
}
public Cliente(String novoNome, Data novoNascimento, int novoCodigo) {
super(novoNome, novoNascimento);
codigo = novoCodigo;
}
@Override
public void imprimeDados() {
System.out.println(super.getNome() + "\n"
+ super.getNascimento().toString() + "\n"
+ codigo);
}
}
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 |
package br.dmoura.dhouse.java.revisao.orientacaoobjeto;
public class Cliente extends Pessoa {
private int codigo;
public int getCodigo() {
return codigo;
}
public void setCodigo(int novoCodigo) {
codigo = novoCodigo;
}
public Cliente(String novoNome, Data novoNascimento, int novoCodigo) {
super(novoNome, novoNascimento);
codigo = novoCodigo;
}
@Override
public void imprimeDados() {
System.out.println(super.getNome() + "\n"
+ super.getNascimento().toString() + "\n"
+ codigo);
}
}
|
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 <stdio.h>
int main() {
char msg[101];
scanf("%s", msg);
printf("%c", msg[0]);
int i = 1;
while (msg[i] != '\0') {
if (msg[i] == '-')
printf("%c", msg[i + 1]);
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>"
|
cpp
| 2 |
#include <stdio.h>
int main() {
char msg[101];
scanf("%s", msg);
printf("%c", msg[0]);
int i = 1;
while (msg[i] != '\0') {
if (msg[i] == '-')
printf("%c", msg[i + 1]);
i++;
}
}
|
Below is an extract from a JavaScript program. Evaluate whether it has a high educational value and could help teach coding. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the program contains valid JavaScript code, even if it's not educational, like boilerplate code, configurations, or niche concepts.
- Add another point if the program addresses practical JavaScript concepts, even if it lacks comments.
- Award a third point if the program is suitable for educational use and introduces key concepts in programming, even if the topic is advanced (e.g., asynchronous programming). The code should be well-structured and contain some comments.
- Give a fourth point if the program is self-contained and highly relevant to teaching JavaScript. It should be similar to a school exercise, a tutorial, or a JavaScript course section.
- Grant a fifth point if the program is outstanding in its educational value and is perfectly suited for teaching JavaScript. It should be well-written, easy to understand, and contain step-by-step explanations and comments.
The extract:
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import BackButton from '../../../../components/BackButton/BackButton';
import Header from '../../../../components/Header/Header';
import HelpTopicsHeader from '../../../../components/HelpTopicsHeader/HelpTopicsHeader';
import OurService from '../../../../components/OurService/OurService';
import './Answers.css';
const WaterProof = (props) => {
return (
<div id='Answers'>
<Header />
<HelpTopicsHeader />
<div className='row p-0 m-0 w-100'>
<div className='col-12'>
<div className='row m-0'>
<div className='col-12'>
<BackButton data='Back to all Help Topics' />
<h1 id='title'>Are LEGO® bricks waterproof?</h1>
</div>
</div>
<div className='row m-0' id='main-content'>
<div className='col-12 col-sm-10 offset-sm-1 col-lg-6 offset-lg-3 p-0'>
<p className='answer'>
Do you want to play with your LEGO® bricks in water? No problem!
Standard LEGO® bricks are not harmed by water. Some specially
designed one-piece boat hulls will even float on the surface of
water, although most LEGO® creations will not.
</p>
<div className='row'>
<div className='col-6'>
<p class='text-center'>
<img src='/HT0506_1.png' alt='' width='100%' />
</p>
</div>
<div className='col-6'>
<p className='answer'>
On the other hand, we don’t recommend you use your LEGO®
bricks as decorations in aquariums or fish tanks.
Additionally, there are also a few types of LEGO® parts that
should never be put into water:
</p>
<h3 className='question'>Electronic parts</h3>
<p className='answer'>
Please be careful to make sure electronic parts like motors,
sensors, lights, and battery boxes don’t come into contact
with water. Putting electronic parts in water can damage th
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 React from 'react';
import { Link, withRouter } from 'react-router-dom';
import BackButton from '../../../../components/BackButton/BackButton';
import Header from '../../../../components/Header/Header';
import HelpTopicsHeader from '../../../../components/HelpTopicsHeader/HelpTopicsHeader';
import OurService from '../../../../components/OurService/OurService';
import './Answers.css';
const WaterProof = (props) => {
return (
<div id='Answers'>
<Header />
<HelpTopicsHeader />
<div className='row p-0 m-0 w-100'>
<div className='col-12'>
<div className='row m-0'>
<div className='col-12'>
<BackButton data='Back to all Help Topics' />
<h1 id='title'>Are LEGO® bricks waterproof?</h1>
</div>
</div>
<div className='row m-0' id='main-content'>
<div className='col-12 col-sm-10 offset-sm-1 col-lg-6 offset-lg-3 p-0'>
<p className='answer'>
Do you want to play with your LEGO® bricks in water? No problem!
Standard LEGO® bricks are not harmed by water. Some specially
designed one-piece boat hulls will even float on the surface of
water, although most LEGO® creations will not.
</p>
<div className='row'>
<div className='col-6'>
<p class='text-center'>
<img src='/HT0506_1.png' alt='' width='100%' />
</p>
</div>
<div className='col-6'>
<p className='answer'>
On the other hand, we don’t recommend you use your LEGO®
bricks as decorations in aquariums or fish tanks.
Additionally, there are also a few types of LEGO® parts that
should never be put into water:
</p>
<h3 className='question'>Electronic parts</h3>
<p className='answer'>
Please be careful to make sure electronic parts like motors,
sensors, lights, and battery boxes don’t come into contact
with water. Putting electronic parts in water can damage the
parts and pose a safety risk.
</p>
<h3 className='d-none d-lg-block question'>
Assemblies and Mechanical components
</h3>
<p className='d-none d-lg-block answer'>
Any parts that are made of multiple smaller pieces which
can’t come apart, like a Technic gearbox or DUPLO® vehicle
should not be put into water. There’s no safety risk from
immersing these, but water could get inside the part and
never fully dry, resulting in mold or mildew growth.
</p>
</div>
</div>
<h3 className='d-lg-none question'>
Assemblies and Mechanical components
</h3>
<p className='d-lg-none answer'>
Any parts that are made of multiple smaller pieces which can’t
come apart, like a Technic gearbox or DUPLO® vehicle should not
be put into water. There’s no safety risk from immersing these,
but water could get inside the part and never fully dry,
resulting in mold or mildew growth.
</p>
<p className='answer'>
For information on how to clean your LEGO® bricks,
<Link to='/cleaninglego' className='link'>
check out this help topic
</Link>
.
</p>
</div>
</div>
</div>
</div>
<OurService />
</div>
);
};
export default withRouter(WaterProof);
|
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 { CustomerModel } from './customer.model';
import { ProductModel } from './product.model';
export class PrescriptionModel {
Customer: CustomerModel;
Products: ProductModel[];
Id: string;
Date: Date;
Description: 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
| 1 |
import { CustomerModel } from './customer.model';
import { ProductModel } from './product.model';
export class PrescriptionModel {
Customer: CustomerModel;
Products: ProductModel[];
Id: string;
Date: Date;
Description: 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:
class Gossip < ApplicationRecord
has_many :join_table_gossips_tags
has_many :tags, through: :join_table_gossips_tags
belongs_to :user
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 Gossip < ApplicationRecord
has_many :join_table_gossips_tags
has_many :tags, through: :join_table_gossips_tags
belongs_to :user
end
|
Below is an extract from an HTML document. Evaluate whether it has a high educational value and could help teach web development. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the document contains valid HTML markup, even if it's not educational, like boilerplate code or standard tags.
- Add another point if the document addresses practical HTML concepts and uses semantic elements appropriately.
- Award a third point if the document is suitable for educational use and introduces key web concepts, even if the topic is somewhat advanced (e.g., forms, metadata). The code should be well-structured and use clear, descriptive naming.
- Give a fourth point if the document is self-contained and highly relevant to teaching HTML. It should be similar to a school exercise, a tutorial, or an HTML course section for early learners.
- Grant a fifth point if the document is outstanding in its educational value and is perfectly suited for teaching HTML to beginners. It should be well-organized, easy to understand, and ideally include some explanatory comments or demonstrate best practices in HTML structure.
The extract:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="favicon.ico">
<title>Title</title>
<link rel="stylesheet" href="style.css">
<link href="jquery.bxslider.css" rel="stylesheet" />
<script src="jquery-1.7.2.min.js"></script>
<script src="jquery.bxslider.js"></script>
<script>
$(document).ready(function(){
$('.bxslider').bxSlider();
});
</script>
</head>
<body>
<section id="header">
<div class="revolver">
<div class="top">
<a href="#"><img class="logo" src="logo.png" alt="logo" /></a>
<div class="navbar">
<ul>
<li><a href="#" class="active">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="intro">
<h2>Welcome to website</h2>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel</p>
</div>
<ul class="bxslider">
<li><img src="fields.jpg" /></li>
<li><img src="talltrees.jpg" /></li>
<li><img src="greens.jpg" /></li>
<li><img src="storm.jpg" /></li>
</ul>
</div>
</section>
<section id="content">
<div class="steps">
<div class="pattern"></div>
<div class="center">
<h3>DESIGN</h3>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet ma
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
html
| 2 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="favicon.ico">
<title>Title</title>
<link rel="stylesheet" href="style.css">
<link href="jquery.bxslider.css" rel="stylesheet" />
<script src="jquery-1.7.2.min.js"></script>
<script src="jquery.bxslider.js"></script>
<script>
$(document).ready(function(){
$('.bxslider').bxSlider();
});
</script>
</head>
<body>
<section id="header">
<div class="revolver">
<div class="top">
<a href="#"><img class="logo" src="logo.png" alt="logo" /></a>
<div class="navbar">
<ul>
<li><a href="#" class="active">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="intro">
<h2>Welcome to website</h2>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel</p>
</div>
<ul class="bxslider">
<li><img src="fields.jpg" /></li>
<li><img src="talltrees.jpg" /></li>
<li><img src="greens.jpg" /></li>
<li><img src="storm.jpg" /></li>
</ul>
</div>
</section>
<section id="content">
<div class="steps">
<div class="pattern"></div>
<div class="center">
<h3>DESIGN</h3>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra,</p>
</div>
<div class="center">
<h3>DEVELOP</h3>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra,</p>
</div>
<div class="center">
<h3>RELEASE</h3>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra,</p>
</div>
</div>
</section>
<section id="simple">
<div class="title">
<h2>Simple</h2>
<h2>Yet</h2>
<h2>Beautiful</h2>
</div>
</section>
<section id="resume">
<span class="clouds"></span>
<div class="res">
<h3>RESUME</h3>
<p>This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit.</p>
<div class="btn">
<button value="view" type="button">View</button>
<button value="download" type="button">Download</button>
</div>
</div>
</section>
<footer id="footer">
<div class="end">
<div class="navbar2">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div class="social">
<a href="#" class="twitter"></a>
<a href="#" class="facebook"></a>
<a href="#" class="google"></a>
<a href="#" class="linkedin"></a>
</div>
<div class="copyr">
<small>©<strong>Website</strong>2014</small>
</div>
<div class="btmLogo">
<img class="logo" src="logo.png" alt="logo" />
</div>
</div>
</footer>
</body>
</html>
|
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:
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
typedef int uint32_t ;
struct TYPE_5__ {int** m; } ;
typedef TYPE_1__ VG_MAT3X3_T ;
/* Variables and functions */
void vg_mat3x3_mul(VG_MAT3X3_T *a, const VG_MAT3X3_T *b, const VG_MAT3X3_T *c)
{
uint32_t j, i;
for (j = 0; j != 3; ++j) {
for (i = 0; i != 3; ++i) {
a->m[j][i] =
(b->m[j][0] * c->m[0][i]) +
(b->m[j][1] * c->m[1][i]) +
(b->m[j][2] * c->m[2][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
| 4 |
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
typedef int uint32_t ;
struct TYPE_5__ {int** m; } ;
typedef TYPE_1__ VG_MAT3X3_T ;
/* Variables and functions */
void vg_mat3x3_mul(VG_MAT3X3_T *a, const VG_MAT3X3_T *b, const VG_MAT3X3_T *c)
{
uint32_t j, i;
for (j = 0; j != 3; ++j) {
for (i = 0; i != 3; ++i) {
a->m[j][i] =
(b->m[j][0] * c->m[0][i]) +
(b->m[j][1] * c->m[1][i]) +
(b->m[j][2] * c->m[2][i]);
}
}
}
|
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 pl.touk.widerest.api.products.search;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FacetDto {
private Boolean active;
private String label;
private List<FacetValueDto> facetOptions;
}
After examining the extract:
- Briefly justify your total score, up to 100 words.
- Conclude with the score using the format: "Educational score: <total points>"
|
java
| 1 |
package pl.touk.widerest.api.products.search;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FacetDto {
private Boolean active;
private String label;
private List<FacetValueDto> facetOptions;
}
|
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
/**
* Created by PhpStorm.
* User: grin
* Date: 13.05.2018
* Time: 15:40
*/
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\DateTime;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// $builder->add('firstname');
$now = new \DateTime();
$builder
->add('firstname', TextType::class, ['data' => 'Nickolay'])
->add('lastname', TextType::class, ['data' => 'Grin'])
->add('city', TextType::class, ['data' => 'Moscow'])
->add('country', TextType::class, ['data' => 'Russia'])
->add('birthdate', BirthdayType::class, ['data' => $now->sub(new \DateInterval('P20Y'))])
->add('sex', ChoiceType::class, [
'choices' => [
'M' => 'male',
'F' => 'female',
]]
)
->add('email', EmailType::class, ['label' => 'form.email', 'translation_domain' => 'FOSUserBundle'])
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'options' => array(
'translation_domain' => 'FOSUserBundle',
'attr' => array(
'autocomplete' => 'new-password',
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
/**
* Created by PhpStorm.
* User: grin
* Date: 13.05.2018
* Time: 15:40
*/
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\DateTime;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// $builder->add('firstname');
$now = new \DateTime();
$builder
->add('firstname', TextType::class, ['data' => 'Nickolay'])
->add('lastname', TextType::class, ['data' => 'Grin'])
->add('city', TextType::class, ['data' => 'Moscow'])
->add('country', TextType::class, ['data' => 'Russia'])
->add('birthdate', BirthdayType::class, ['data' => $now->sub(new \DateInterval('P20Y'))])
->add('sex', ChoiceType::class, [
'choices' => [
'M' => 'male',
'F' => 'female',
]]
)
->add('email', EmailType::class, ['label' => 'form.email', 'translation_domain' => 'FOSUserBundle'])
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'options' => array(
'translation_domain' => 'FOSUserBundle',
'attr' => array(
'autocomplete' => 'new-password',
),
),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
->add('registerdate', DateTimeType::class, array(
'data' => $now,
))
;
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
// For Symfony 2.x
public function getName()
{
return $this->getBlockPrefix();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.